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.
Related
I've got a html form and trying to send it with jQuery to a php script. In this script i am looking for the params.
$(document).ready(function(){
$("#myselect").change(function(e){
e.preventDefault();
$.post("mypath/toscript/",$("#form").serialize(), function(data){
alert(data);
});
});
});
I need all uri parts. So im fetching it with $_SERVER['REQUEST_URI'].
I am requesting something like this:
mypath/toscript/?p1=A&p2=B&p3=C
When i type this URI in the browser it works like it should.
But with the jQuery above i am getting with $_SERVER['REQUEST_URI'] only mypath/toscript/ without params.
Using $_POST shows me the prams p1=A&p2=B&p3=C
So why? Where is the difference when doing a post with $.post() to typing it directly
POST doesn't use the request URL to send the query string like GET does. POST instead sends the query string in the HTTP message body. When you type the query string into the browser, you are using method GET.
Here is an article from W3Schools about it.
That doesn't mean you should switch to using $.get necessarily though. There are drawbacks to using GET over POST, such as having a length limit or being less secure. Read the article to learn more.
To fix your code, you will have to choose which HTTP method suites your needs, and then align the jQuery and PHP code so that they both use the same method.
In your case try this will solve your problem ..
$.get("mypath/toscript/",$("#form").serialize(), function(data){
GET - Requests data from a specified resource..
POST - Submits data to be processed to a specified resource..
from w3school
You should use GET where you're doing a request which has no side effects, e.g. just fetching some info. This request can:
Be repeated without any problem - if the browser detects an error it
can silently retry Have its result cached by the browser Be cached by
a proxy
You have to provide serialize in formatted array way something like this
var data = $('#form').serializeArray();
$.post("mypath/toscript/",data , function(data){
alert(data);
});
Use parse_str to parse your serialized POST data into an array.
// $_POST['form'] : "num=12&obj=3&obs=text"
$form = array();
parse_str($_POST['form'], $form);
// you get :
$int_num = (int) $form['num']; // 12
$int_obj = (int) $form['obj']; // 3
$str_obs = $form['obs']; // "text"
A serialized form data is commonly used to update a database, so it's recommended to use POST vars.
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
Here is my JS:
<script>
dojo.require("dijit.form.Button");
function sendText(){
var button = dijit.byId("submitButton2");
dojo.connect(button, "onClick", function(event){
// The parameters to pass to xhrPost, the message, and the url to send it to
// Also, how to handle the return and callbacks.
var xhrArgs = {
//type: "POST",
url: "http://testjson.php",
content: dojo.toJson({key1:"value1",key2:"value2"},true),
handleAs: "text",
load: function(newContent){
dojo.byId("response2").innerHTML = newContent;
},
error: function(error){
// We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
// docs server.
dojo.byId("response2").innerHTML = "Message posted.";
}
}
dojo.byId("response2").innerHTML = "Message being sent..."
// Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
});
}
dojo.ready(sendText);
</script>
Here is my PHP:
<?php
foreach($_POST as $key => $val) echo '$_POST["'.$key.'"]='.$val.'<br />';
?>
The problem is that nothing is being returned.
If I put content instead of postData I have $_POST[0]='{', $_POST[1]='k' etc character by character, limited to 1000. This is a big problem.
Please can somebody tell me what I'm doing wrong? I got this code right from the dojo website, so it should be alright.
The php $_POST array only shows form encoded data. In your example you are POSTing json, so it won't directly show up in $_POST.
You have a couple options here. You could continue to post the data as json and read the POSTed json directly from the php input stream: $data = json_decode(file_get_contents('php://input'));. This is probably the easiest, and it replaces accessing the $_POST array for the data.
Other options include not POSTing json (just send form encoded data) and POSTing json as form encoded data:
In that case, your content would become something like
content: 'my_post_data='+dojo.toJson({key1:"value1",key2:"value2"}, true), (you may need to change handleAs fyi)
Then on the server side you would likely see something like
$_POST['my_post_data']= '{"key1":"value1","key2":"value2"}' which could be processed by json_decode()
I believe your content is being sent character by character because you are converting your content object into JSON. According to the dojo.xhrPost documentation, the content property is expected to be a JavaScript Object. I hope this helps solve your problem.
It should be noted that this module is deprecated in favor of dojo/request/xhr, so it is better to use that unless you have lower version requirements.
In an earlier post today the answer has led me down the route of using a JSON feed to populate elements in my page.
Something new to learn!!
the JSON data is created from a PHP script which retrieves the data from a Mysql database. The php script retrieves a specific record which I need to pass to the php script with the getJson call.
I've had success with creating the url with the parameters added as a GET method but I can't find an example of a POST method - the parameters should go as an optional parameter. here's what I have so far...
function loadData(index) {
alert(index);//debug
$.getJSON('loadJSONholeData.php' ,
{hole: index} ,
function(data) {
I've found examples for a twitter feed which shows a parameter like option: "cat", but can't find an option where the value is in a variable.
I don't understand how to use the parameters - where am I going wrong. Appreciate this is probably a fundamental issue but I'm learning.
Thanks
Update:
I've revised the code per the responses below and used both suggestions to pass the POST parameter, but the receiving PHP code is not reading the POST parameter and just returns the default query values.
I even used as static value of 1 both as a value and as a string but no joy.
Here's my receiving PHP code which accesses the POST values:
$hole = 3;
if (isset($_POST['hole'])) {
$hole = $_POST['hole'];
}
I'm missing something basic here. The value in 'index' definitely exists as it shows in the debug and JSON data is being returned )(but the default). I can go back to my GET method but want to see this work!!
Thanks
Update: Success!!
I played around further with the revised code. I removed the content type parameter from the code and it all works now, the PHP is returning the correct query.
I assume then that by specifying the JSON type in contentType it passes the POST parameter in a different way to PHP which expects it in anpther way?
Onwards and upwards - thanks
The $.getJSON() method does an HTTP GET and not POST. Try something like this -
$.ajax({
url: 'loadJSONholeData.php',
data: JSON.stringify({hole: index }),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
//(result.d) has your data.
}
});
Each key/value pair in the arguments object will represent a parameter in the HTTP POST. You can use variables as values, but I believe they will be converted to strings, so it's better to do the conversion yourself (so you can make sure they have the correct format). A simple example:
var dynamicValue = foo();
$.post('my/url', { var1:"static value", var2:dynamicValue }, function(data) {
// Your callback; the format of "data" will depend on the 4th parameter to post...
}, "json"); // ...in this case, json
Now, in case your server is expecting a json encoded object/list, you can pass it by using JSON.stringify:
function foo() {
return JSON.stringify({ my:"object" });
}
JSON should be available in most modern browsers, in case it's not, you can get it here (json2.js, under "JavaScript").
ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})