send an array per ajax to an python-server-script - javascript

I want to send all my names,values and labels of my form-elements when I klick on a button, I didnt make a submit-button, beause the I got them in a wrong order, so I make this in JavaScript:
$('#mybutton').click(function() {
m.modal('show');
var all=[];
$('textarea, select, input').each(function(index){
var label= $(this).parent().find('label').html();
var value= $(this).val();
var name= $(this).attr('name');
all.push([name,value,label]);
})
$.ajax({
dataType: "text",
url: "befund",
data: {
wert : all
},
success: function(data){
$('#mymodal').find('.modal-body').html(data);
}
})
});
in the python server-script (bottle) I try this:
#app.route('/web/befund')
def modalcontent() -> str:
x = request.query.wert[0][1]
print (x)
return('test')
the problem is that I see in the browser, that the right array is send but when I try to see one element of the array with "request.query.wert[0][1]" I only get a http-error 500 (internerl server error). Can anybody help me please?

You can use POST for this (and should, if this is sensitive data and your connection is secure).
However, you need to turn the data into a JSON string, then decode it on the server.
data: {
wert: JSON.stringify(all)
},
On the server:
wert = json.loads(request.params.wert);
print wert[0][1]

I think the wert it is the object on the server side. Try accesing data by `x=request.query.wert[0]
or
x=request.query['wert'][0]
Im not using python now, but it seems like right

Related

How do I return a variable from Javascript to PHP for using it for a query "onchange"?

JAVASCRIPT
$(document).ready(function() {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
success: function (data)
{
console.log(data); //<------ this gives me an empty output
alert("success!");
}
});
});
});
I am trying to get a the id of a selected value out of the selectpicker, when i change the selectpicker, i get the alert "success!" and in the console it shows the result, which is correct. When i want to use this result in PHP, which i am using ajax for, it gives me an odd output so i can't use the variable for the following sql statement.
What am i doing wrong? For you to understand i want to get the post input for product, so i can filter the next selectpicker by the id of "product", so i want to get dependant selectpicker "onchange". I already read many other questions, and it works in other examples when i use something like this in the success function:
success: function (data)
{
$('#state').html(data);
}
But this isn't working for my example here, because when i use the "$_POST['produkt_id']" it either gives me an empty query or it has a mistake in it, since it passes the data from my screenshot. Thanks in advance and feel free to ask questions.
UPDATE:
This is where I am trying to get the previous input.
case 'linie':
if(isset($_POST['pId'])) {
$t = $_POST['pId'];
$sql = 'SELECT id, bezeichnung '
. 'FROM l "
. 'LEFT JOIN ' .produkte p ON p.id=l.p_id '
. 'WHERE l.p_id =' . "$t" . 'AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
}
the error says it. PHP you're using is calling "include_once" and the file which you're trying to include, doesn't exist.
that makes the PHP to return a response with error in it, and the response - because of that error text - is not a valid JSON anymore.
In your ajax code you should put your url route path for file request it hink you put the file path of your project system that's why your ajax file could not find and include your file for ajax request execution
$.ajax({
url: "modules/ausschuss/ausschuss.class.php", //remove this
url: "full url for your file execution"
method: "POST",
data: {produkt_id: produkt_id},
success: function (data)
{
alert("success!");
}
});

Updating MySQL Database with ajax

I'm trying to send a JS array to a .php file on the click of a button, and run the php file's code on the click, using the array that was sent.
I have a button:
<button id="submit" class="button1" >Submit<span></span></button>
Which I try to run this JS ajax with:
$('#submit').click(function() {
$.ajax({
method: "POST",
url: "submit.php",
data: selectedImageArray
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In my submit.php file, I connect to the database, then have this:
$array = $_POST['selectedImageArray'];
$sql = $dbh->prepare("INSERT INTO pending_trades (steam_id, trade_items, is_giving, is_receiving, has_started) VALUES (:steamid, :itemlist, '1', '0', '0')");
$sql->bindParam(':steamid', $steamprofile['steamid']);
$sql->bindParam(':itemlist', $array);
$sql->execute();
}
When I click the "submit" button, I get the message saying "Data saved", but nothing is happening with my database. Should clicking the button run the submit.php code?
$('#submit').click(function(){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray}, // this is supposed to be JSON
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
And
$_POST['selectedImageArray'] // see the quotes
You have a syntax error with your JS. Also, since #submit is an ID, qualifying it with button is unnecessary.
Your code should read:
$('#submit').click(function() {
$.ajax({
method: "POST",
url: "submit.php",
data: selectedImageArray
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Edit 1:
I see that you have incorporated the above code into your JS. Now on to your problem on the server side (PHP/SQL).
Firstly, why are you decoding $_POST[selectedImageArray] then re-encoding it? Doesn't make sense to me.
Secondly, what is the value of $steamprofile['steamid']?
Thirdly, what is the schema of your SQL table? Are you sure you're not violating any unique / not null / fk constraint?
Do yourself a favour, and use a debugging/logging solution on the server-side. It can be as simple as printing debug lines into a log file so you can inspect later on to find out what is happening.
What I'd do:
check value of $_POST[selectedImageArray]. It should be a string.
check the value for $array. It should be an array.
read the error logs to see what else it says.
$sql->execute(); returns a bool (TRUE on success). Use it in your script to return either success or failure message.
Log down the value of $sql->errorCode(); on failure.
With all the above, you should have enough to troubleshoot what went wrong there.
I suppose that steam_id is a primary key with auto increment, so if you are trying to insert a row to database with the same value for steam_id, then it is a possibility that your data cannot be added.
To debug in a better way, try to generate the query in the server and echo it. Then try to run the same query in your MySQL console to find the response.

Javascript get current page html (after editing)

I have a page that I have edited after load and what I want to do is get the pages current HTML and pass that off to a PHP script.
I first passed document.documentElement.innerHTML but that ended up including a bunch of computed style garbage at the top which I did not want. After googling around I found I could use ajax to get a copy of the current file on the server and then replace the edited part afterwards.
I can get the copy of the file using this:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
Which works fine and gets me the html I expected and see when viewing the page in notepad.
The next step is what I cannot figure out. All I want to do is swap out the innerHTML of a div with an id of 'editor' with what the current value is, so I have tried this:
origPage.getElementById('editor').innerHTML = e.html;
But I get the error "TypeError: undefined is not a function". I must be doing something simple wrong I feel but I don't know the proper formatting to do this. I have tried the following variations:
alert($(origPage).getElementById('editor').innerHTML);
//Different attempt
var newHtml = $.parseHTML( origPage );
alert($(newHtml).getElementById('editor').innerHTML);
//Different attempt
alert($(origPage).html().getElementById('editor').innerHTML);
But I always get "TypeError: undefined is not a function" or "TypeError: Cannot read property 'getElementById' of undefined". How can I do this properly?
EDIT:
Complete page html below:
<!DOCTYPE html>
<html>
<body>
<div id="editor">
<h1>This is editable.</h1>
<p>Click me to start editing.</p>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="snapeditor.js"></script>
<script type="text/javascript">
var editor = new SnapEditor.InPlace("editor", {onSave: function (e) {
var isSuccess = true;
//var origPage = e.html;
var origPage;
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
// Actually perform the save and update isSuccess.
// Javascript:
$.ajax({
url: filename,
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
origPage = data; // can be a global variable too...
// process the content...
}
});
//origPage shows expected html as this point
//alert($(origPage).getElementById('editor').innerHTML);
//alert($(origPage).html().getElementById('editor').innerHTML);
$(origPage).getElementById('editor').innerHTML = e.html;//fails here
alert(origPage);
//alert(newHtml.getElementById('editor').innerHTML);
$.ajax({
data: {html: origPage, docName: 'example1.html'},
url: 'savePage.php',
method: 'POST', // or GET
success: function(msg) {
alert(msg);
isSuccess = true;
}
});
return isSuccess || "Error";
},
onUnsavedChanges: function (e) {
if(confirm("Save changes?")) {
if(e.api.execAction("save")){
//location.reload();
}
} else {
e.api.execAction("discard");
}
}});
</script>
</body>
</html>
It seems that you get the user's changes in a variable - you called the var e.html. That is not a good variable name, BTW. If you can, change it to something like htmlEdited
Question: If you add the command alert(e.html); what do you get? Do you see the HTML after user edits?
If yes, then what you need to do is send that variable to a PHP file, which will receive the data and stick it into the database.
Code to send the data:
javascript/jQuery:
alert(e.html); //you should see the user-edited HTML
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'userStuff=' + e.html, //var_name = var_contents
success: function(d){
window.location.href = ''; //redisplay this page
}
});
another_php_file.php:
<?php
$user_edits = $_POST['userStuff']; //note exact same name as data statement above
mysql_query("UPDATE `your_table_name` SET `your_col_name` = '$user_edits' ") or die(mysql_error());
echo 'All donarino';
The AJAX javascript code will send the var contents to a PHP file called another_php_file.php.
The data is received as $user_edits, and then inserted into your MySQL db
Finally, I presume that if you redisplay that page it will once again grab the contents of the #editor div from the database?
This is where you haven't provided enough information, and why I wanted to see all your code.
ARE you populating that div from the database? If not, then how do you expect the page to be updated after refreshing the page?
You would benefit from doing some tutorials at phpacademy.org or a thenewboston.com. Do these two (free) courses and you'll be an expert:
https://phpacademy.org/videos/php-and-mysql-with-mysqli
https://phpacademy.org/videos/oop-loginregister-system
If all you need to do is insert the contents of e.html to replace the #editor div, then try this:
$('#editor').html(e.html);
HOWEVER, you need an event to trigger that code. Are you able to do this?
alert(e.html);
If so, then put the first bit of code at that same spot. If not, we need more information about when your code receives that variable -- that is where you put the $('#editor').html(e.html); statement.

how do I get AJAX to pass button click to python?

I'm a novice. I would like to pass a value from an HTML button click on the client's browser to a python script on the server to send a value to a PostgreSQL db. I must be missing something. Here's what the javascript, and AJAX in the HTML look like:
<div class="note" id="(Untitled)">
<script type="text/javascript" src="./jquery-2.1.1.js">
$(function () {
$("#one").click(function () {
$("#one").trigger("click", ["1"]);
do_it(1);
});
$("#two").click(function () {
$("#two").trigger("click", ["2"]);
do_it(2);
});
});
function do_it(n) {
$.ajax({
type: "POST",
url: "~/script_for_practice_jun20.py",
datatype: "json",
data: {param: 'n'}
success: success
}),
}
)
Here's the python part that I am using...
def cgi_get_from_ajax(self):
import json
import cgi
data = cgi.FieldStorage()
chosen = data["param"].value
return chosen
def set_choice(self):
process = Name_of_class()
choice = process.cgi_get_from_ajax()
entry = []
if choice == '1':
entry = [1,0,]
else:
entry = [0,1]
return entry
My deadline is approaching. Please help me. Please. Please.
url: "~/script_for_practice_jun20.py",
this is a server friendly url. jquery cant use url with ~ sign.
correct you url, either relative to current page, or absolute from root directory.
Did You Got Any Error In Console?

How to send a JQuery Variable to another PHP page via dblclick()?

So guys, I made a listbox and if I dblclick to an item the value of it gets saved into "val", but I can't send it to the next PHP File. I also alerted "val" - the value is really saved in it. I also get the function succes displayed in the browser console. what to do?
thanks
My Function:
$(document).ready(function () {
$("option").dblclick(function () {
var lb = document.getElementById("liste");
var val = lb[lb.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'about.php',
dataType: 'HTML',
data: {
aufid: val
},
success: function (data) {}
});
});
});
PHP Code in about.php:
$id = $_POST['aufid'];
Can you try to see what variables are in the $_POST superglobal?
print_r($_POST);
try to set the url your full adrees
url: 'http://myadress.com/about.php',
java script is running on your local computer so it might send the request to you own pc where no about.php exist

Categories

Resources