i have a form that fetches all the data from database and in order to update the datas that is fetched i need to serialize the data.
alert($("form").serialize());
and this is the output
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
how to retrieve this data in php in order for me to update the database?
You have to combine functions $.submit() and $.post() or $.ajax():
$('form').submit(function() {
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script
}
});
return false;
});
Then in your PHP script you have to read your data from $_POST array. E.g.
$tid = $_POST['tid'];
To debug your incoming $_POST array use var_dump() or print_r().
If you want to send response to your javascript just pack whatever you want into variable and then just use die(json_encode());. E.g.:
$output = array('status' => true, 'message' => 'Success');
die(json_encode($output));
It also will be required to add to $.post() method attribute:
dataType : 'json'
In your PHP, at the top write this and you'll see what's happening.
//If method = GET
var_dump($_GET);
//If method = POST
var_dump($_POST);
exit();
This will show all variables that are being passed and stop the script so you can review on the page. Then just have your jquery put the response data in a div that you can view.
The problem seems to be that you are redefining your $_POST vars. They can not contain the same names/keys as you are sending them over currently. Essentially its like redefining a variable, it will no longer contain its previous value.
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
Notice how you have called tid and the other keys multiple times? Instead you would want to give them separate names,or pass an array of values to your PHP.
Example:
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid2=2&tname2=Super&tsize2=XS&quantity2=1&tprice2=2800&tid3**=3&tname3=Dota+Tees&tsize3=XS&quantity3=1&tprice3=700
Of course there are other ways of doing this as well.
Each key must have a unique identifier, other wise it will overwrite the previously defined $_POST value.
Instead of:
tid=1&
tid=2&
tid=3&
You would want:
tid1=1&
tid2=2&
tid3=3&
Looks like a job for PHP's parse_str() function. http://php.net/manual/en/function.parse-str.php
Related
I am new to php and am trying to update a hidden field value inside a php function and can't see to find a solution that works.
In template.php I have:
<input type="hidden" id="variable_ID" name="variable_name" value="variable_value">
This works fine.
However I need to update the value of the variable to the record ID of inserted record in a function in functions.php eg
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
// *** Set Hidden field value to $get_record_id here ***
}
I have tried a myriad of things but can't seem to find a solution.
Any pointers on how to solve this problem?
Here is the solution I used - thanks to #Steven and #El_Vanja for direction.
(I may need to change the question title now though because what I actually needed to do was return a variable to javascript from PHP using Ajax. I didn't need to use hidden fields).
PHP
function myFunction() {
$insert_record = $mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
$get_record_id = $mydb->insert_id;
echo json_encode($get_record_id);
exit;
}
JS
jQuery.ajax({
url: ajax_url,
type:'POST',
data: {
action: "myFunction",
anydata:"to be posted"},
success: process_record_ID
});
function process_record_ID(data_returned_from_myFunction){
recordID = data_returned_from_myFunction;
}
Hope this helps others!
Notes
I believe that we have to declare 'process_record_ID' as a separate function outside of AJAX because AJAX is asynchronous. If we define the function in the success handler, the function runs in AJAX before the value is actually returned from PHP.
In the AJAX success handler, we don't need to explicitly list the 'data_returned_from_myFunction' variable in the call to process_record_ID function. When the data is returned to the AJAX success handler from PHP, it still gets sent to the function.
Additional answer
You're correct AJAX is an asynchronous construct which means that certain tasks can be carried out before you might expect them to (from a synchronous perspective).
For example we can (as per the code in the original answer) use jQuery to update the value of a field directly in the success handler.
We can't update a JS variable directly, i.e:
some_variable = response.value;
If you attempt it the variable some_variable will likely be undefined.
The difference comes down to callbacks:
Callbacks allow the asynchronous function to call a function after it completes. Where as setting a variable happens on the spot.
There are two easy ways to solve this issue then:
Create a function outside of the AJAX request and allow it to callback that function once the AJAX request has completed -- as you've already discovered.
Use the complete option inside of your AJAX request.
Using a call back
Firstly we need to define out variable to be updated and the function which we will use to update it:
var inserted_id = "";
function update_id(data){
inserted_id = data.record_id;
}
Then we can make out AJAX call:
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : update_id
});
N.B.
Calling update_id in this fashion means we pass the entirety of the returned JSON object; not just the returned number.
Alternatively...
var inserted_id = "";
function update_id(data){
inserted_id = data;
}
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response){
update_id(response.record_id);
}
});
This method is effectively the same but we only pass the returned number to the update_id function.
Using complete
complete works the same way as success however activates once the AJAX request is... complete...
var inserted_id = "";
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
complete: function(data) {
inserted_id = data.responseJSON.record_id;
}
});
Original answer
Having not seen the rest of your code giving a complete answer is tricky. However, this should set you on the right track:
PHP
Firstly, in your PHP you need to make sure and output the data that you want returned to the webpage. In this case we want to return the insert id of the newly created record; to do this we're going to output a JSON object so that the AJAX call can interpret the value and update the page:
function myFunction() {
$mydb->query("INSERT INTO `Table`(`Name`) VALUES ('John')");
echo json_encode(["record_id" => $mydb->insert_id]);
exit;
}
N.B.
We don't want any output other than the JSON string. Hence exit has been used after the echo. You may want/need to adjust the echo and exit to fit with the rest of your code etc.
JS
Now that we have our PHP returning usable data to our ajax call (which should look something like the below) we can take the returned data aka response and update the value of the hidden field accordingly.
$.ajax({
type : "POST",
url : "/url/to/functions.php",
data : {data:"to be posted"},
dataType: 'json',
success : function(response) {
$("#id_of_hidden_field").val(response.record_id);
}
});
Maybe I need to go about it another way, but here is what I am trying to do (it's simple) I send data to a PHP function using ajax. Here is an example.
function myAjax(){
//The data here comes from an ajax call
$_POST['id'];
$_POST['x'];
$_POST['y'];
}
The ajax looks like this
jQuery.ajax({
type: "POST",
url: window.ajaxurl,
data: { "action": "myAjax", id: divid, x: pos_x, y: pos_y }})
}
This is not the complete ajax code, this is inside a jQuery UI event but it's irrelevant, the important part is the data:{}
The data from the PHP code is stored into a database, I run code inside the function to interact and add the variables, but again that is irrelevant... how can I access these variables outside of this function?
Lets say I am echoing a div and I want to use $_POST['id'] as an ID for that div. example
echo '<div id="'.$_POST['id'].'"></div>';
This code is obviously outside the function... so I am still a newbie and would be grateful if someone can point this out to me :)
First, in order to understand what data you are getting, you should do a var_dump in PHP:
var_dump($_POST);
This will show a list of key/value pairs, based on that you can then output the information as needed.
Note that jQuery might do some automatic conversion on the data, for example it might convert your object to JSON. In this case, decode the data server-side using json_decode.
Apparently you have to store request params somewhere and then pass them anywhere you need. For instance,
// well, this is quite straightforward
$requestParams = $_POST;
// then pass params to your function
function myAjax(array $params) {
// here you have local copy of your $_POST parameters
// EDITED: you can store data in database and return the result, an ID of
// the row for example
// some insert SQL
$id = mysql_insert_id();
return $id;
}
$newRecordId = myAjax($requestParams);
// here (outside function) you have a global $params variable which you can use
// to echo a div for example
I know ajax calls and $_POST have been around a lot lately, nevertheless i could not find an answer to my current problem.
In my Javascript, I have a two-dimensional data array:
var postData = new Array(new Array());
postData[0]['type'] = 'grid';
postData[0]['data'] = gridData;
I then try to send this array to a PHP script:
function export_report_pdf(postData){
console.log(postData);
$.post('/ajax/ExportReportPDF.ajax.php',{data: JSON.stringify(postData)},
function(postData){
console.log("Successfully requested report export.");
});
}
I have tried to receive the array in my PHP script:
print_r($_POST);
var_dump(json_decode(file_get_contents("php://input")));
but all I get in my $_POST is an empty two-dimensional array. When I do the console.log(postData) in the beginning of my function, the data is there.
I have also checked $_REQUEST and tried removing the JSON.stringify.
Your inner variable type should be an object instead of an array, otherwise it won't get serialized properly:
var postData = [];
postData.push({
type: 'grid',
data: gridData
});
have you tried using get instead of post.
try that that would atleast ensure that data is getting passed from client to server and problem is with POST request only.
Also when u try GET than check in console if u are getting any error.
Don't JSON.stringify your post data. jQuery will do that for you, regardless of whether you've done it yourself, so it's winding up double-encoded. If you check your logs, you'll see that, after unencoding the data, PHP has a single POST parameter that is all of your data, JSON encoded.
Your could should look like this:
$.post('/ajax/ExportReportPDF.ajax.php', {data: postData}, ...
function export_report_pdf(postData){
console.log(postData);
$.ajax(url:'/ajax/ExportReportPDF.ajax.php',type:'POST',{data: JSON.stringify(postData)},
success:function(postData){
console.log("Successfully requested report export.");
});
}
try this.
and make sure you have latest jquery included.
I am trying to get data from an SQL Database through jQuery, Ajax and PHP.
Here is the jQuery Code
$.ajax({
url: 'OpenQuiz.php',
data: '',
dataType:'json',
success: function(data) {
var one = data[0];
}
}
$(document).ajaxComplete(function(event,request,settings) {
alert("check");
}
Here are the json encode lines at the end of the PHP file called "OpenQuiz.php"
echo json_encode($QuizName);
echo json_encode($options);
echo json_encode($votes);
echo json_encode($row_num);
echo json_encode($percentage);
echo json_encode($TruncPercentage);
Please note:
$options, $votes, $Percentage and $TruncPercentage are all two-dimensional arrays.
$row_num is an integer.
$Quiz_Name is a single-dimensional array.
I find that the jQuery runs fine and the ajax request is called because the alert box for "check" shows up. The problem is that I dont know how to access the variables after they have been transferred. I know that it has something to do with data[0] but I don't really understand what "data[0]" means or what it represents. Basically how to I access the variables that I have sent using json_encode in the PHP file?
data[0] is the first json_encoded item in the array returned. You shouldn't json_encode everything separately, you should build an array and json_encode this.
$items = array('QuizName'=>$QuizName,'options'=>$options, ... ,'TruncPercentage'=>$TruncPercentage);
echo json_encode($items);
Then you retrieve with:
success: function(data) {
var qn = data.QuizName,
opt = data.options;
}
And so on for each item, with data.[whatever], and [whatever] being the name of the item you gave it in the array. I know I originally said to retrieve by index (data[0]), but I prefer to retrieve explicitly so that the code is more maintainable.
As a side note, you can eliminate the datatype:'json' declaration in your ajax call by simply setting the header correctly on the PHP side:
header('Content-type: application/json');
Placing that at the top of the document will force the server to recognize the page as json. Far more consistent and explicit than having jQuery look for it.
I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You might do that with $.post method of jQuery (for example) :
var myJavascriptArray = new Array('jj', 'kk', 'oo');
$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
// do something with received data!
});
Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.
Is it that ?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.
You might want to take a look at Creating JSON Data in PHP
IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.
You may be looking for a way to Serialize (jQuery version) the data.
jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:
here is the synatax:
jQuery.ajaxSetting.traditional = true;
here is the example
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend, //this will be an array eg.
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)
myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']
echo $_POST['arrayItems'] ;
will echo something like: array=>{[0]=>'first thing', [1]=> second thing}