Wordpress Ajax can't use POST, can't pass object - php

I am trying to reach wordpress ajax from the admin back office, inside a custom post creation.
I have tried with no result to send a POST request, to which the server answers : 0, with an error 400.
I have tried to dump the $_REQUEST from amin_ajax.php and it is empty when i use this :
$.ajax({
url : ajaxUrl,
type : 'POST',
data : {
action : "gMapsLatLong",
adresse : adresse,
adresse2 : adresse2,
code_postal : code_postal,
ville : ville
},
contentType: "application/json; charset=utf-8",
dataType: "json",
});
I have tried both with and without serializing the data object, with no result.
When I try to use GET, I can only pass the "action" variable, the others are not present in the request.
In my function.php file, I have put :
add_action('wp_ajax_gMapsLatLong', 'gMapsLatLong');
add_action('wp_ajax_nopriv_gMapsLatLong', 'gMapsLatLong');
Can anyone see something obvious I am missing here?

You have said contentType: "application/json; charset=utf-8", but the value you pass to data is not JSON.
Either don't override the Content-Type header (which would cause PHP to not parse the request body as it doesn't have native support for JSON encoded requests) or pass JSON to data (by encoding the JavaScript object using JSON.stringify).
If you take the latter approach, then the PHP will need to read the raw request body and parse the JSON explicitly.

When you post json to PHP, it won't show up in the $_POST global. If you are wanting to send is as a normal, 'application/x-www-form-urlencoded; charset=UTF-8' post, then you should remove the contentType, and it will then show up in $_POST. If you do want to post json, then you need to do:
$.ajax({
url : ajaxUrl,
type : 'POST',
data : JSON.stringify({
action : "gMapsLatLong",
adresse : adresse,
adresse2 : adresse2,
code_postal : code_postal,
ville : ville
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
And then in PHP you can do:
$_JSON = json_decode(file_get_contents('php://input'), true);

After some try and error I found two issues :
jQuery.ajax({
instead of
$.post({
and my values were undefined due to some silly misconception.
Thanks for your read !

Related

json is not being received by php

I have an Ajax call:
let jFormData = JSON.stringify(formData);
// {"list":["17810","17811","17812"],"chosen":"17812"}
$('#json').val(jFormData);
$.ajax({
url : 'db_ajax/regDupAjax.php',
type : 'POST',
data : jFormData, // our data object
dataType : 'json',
})
The JSON has been validated.
It is being sent to a php script and being read by
$json = $_POST['jFormData'];
but $json is an empty string.
What have I overlooked? I have tried dataType text, and have reviewed all the suggested similar questions without success.
The parameter data in ajax request wait for object. If you want pass json string to jFormData key in $_POST you must pass it as new object:
$.ajax({
url : 'db_ajax/regDupAjax.php',
type : 'POST',
data : { jFormData: jFormData }, // our data object
dataType : 'json',
})
Using the browser's developer console, you can track ajax post from the network section and check the sent values. You will be sure whether the values are sent correctly or if the post operation is successful.

Jquery ajax contentType confused me

I'm using jquery ajax function.
I noticed an issue when I post JSON data to the server.
The type of post data is JSON. So I added the code to specify what I sent was JSON.
contentType: "application/json".
I wrote below code:
var data = {"data": "mytestdata" };
var option = {
url: 'Handler1.ashx',
type: 'POST',
dataType: 'html',
success: function (result) {
alert(result);
},
data: data,
contentType: "application/json"
};
$.ajax(option);
At the server side, I used below code:
string s = context.Request["data"];
But the result s was null.
Logically,setting contentType="application/json" and posting json data are perfect. But it's false.
Also I tried code in php file:
echo $_POST["data"];
PHP says $_POST["data"] doesn't exist.
So I tried to remove the code -- contentType: "application/json".
Now,everything is OK.
But it confused me.
Why needn't set contentType as json when we post the real json data?
You don't need to do contentType: "application/json", when you don't specify content type, it converts the data to be sent in http params, from the json..which are accessible via $_GET, or $_POST params..
But if you want to send json data only..you can try this code on server side to get the data:
<?php
$data = #file_get_contents('php://input');
print_r(json_decode($data));
?>
You were not sending JSON data back. jQuery considers it an error when the ajax content type is set to accept JSON, but malformed JSON is sent back.
echo $_POST['data'] will likely throw the exception "Catchable fatal error: Object of class stdClass could not be converted to string" -- so that actually gets printed out. That's not valid JSON.
What you probably want to do is echo json_encode($_POST['data']);

using ajax to retrieve an xml response and display results

I know how to post using $.ajax method.
I have a form that posts data to a payment API this is what the response looks like:
<ns2:GetTransactionsResponseType xmlns:ns2="http://www.paymentgateway.com/schema/api/2.0/service.xsd">
<Timestamp>2012-08-14T17:33:55.213+10:00</Timestamp>
<Version>2.0</Version>
<Status>Success</Status>
<total>0</total>
</ns2:GetTransactionsResponseType>
as you can see the total of transactions is 0,
so step 1 make the post request using $.ajax, then on success: I want to do $('#results'),html('the total transactions are: '+numberoftransactions);
any ideas/suggestions ? thank you
you can try something like this
$(function(){
$.ajax({
type: "GET",
url: $uri,
dataType: "xml",
async: false,
contentType: "text/xml; charset=\"utf-8\"",
complete: function(xmlResponse) {
// So you can see what was wrong...
console.log(xmlResponse);
console.log(xmlResponse.responseText);
$("#preForXMLResponse").text(xmlResponse.responseText);
}
});
});
try finding required value in responseText
for more information please visit this link
The XMLHttpRequest Object
I guess rahul has answered your question so I just wanted to add that if you're trying to pass data to the url and get back response accordingly then you could take advantage of the data property while making ajax request.
suppose you're trying to get xml response according to user profile so you have to pass user id to the url to get accurate response. You can just do it like this
$(function(){
$.ajax({
type: "GET",
url: $uri,
data: $user_id, //this id will be passed with the request to the url as query string
dataType: "xml",
async: false,
contentType: "text/xml; charset=\"utf-8\"",
complete: function(xmlResponse) {
// So you can see what was wrong...
console.log(xmlResponse);
console.log(xmlResponse.responseText);
$("#preForXMLResponse").text(xmlResponse.responseText);
}
});
});
Hope this helps or may be I didn't understand properly, what you were looking for.

POST json data via ajax sends an empty array

I'm trying to post data via ajax, this is my info:
var jsondata =
{"address" : [
{ "id": addid, "streetaddress": streetaddress, "city": city, "state": state, "zipcode": zipcode, "latitude": latitude},
]
};
var jsontosend = JSON.stringify(jsondata, null, 2);
ajax function:
$.ajax({
type: "POST",
url: "process.php",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: jsontosend,
success: function(msg){
alert(msg);
}
});
return false;
alert('Data sent');
}
on the php end, when i print_r($_POST) it just says
array(0) {
}
I'm alerting (jsontosend) and its showing me everything perfectly, as well as in firebug using post mothod, its showing all the params sent in a perfect clean manner.
The only way it passes any data is if I use GET method.
Any advice is greatly appreciated!
EDIT: adding POST data from firebug.
this is whats being alerted from the alert function:
{"address":[{"id":1473294,"streetaddress":"3784 Howard Ave","city":"Washington DC","state":"DC","zipcode":20895,"latitude":39.027820587}]}
this is what firebug is showing as whats being passed when using POST method:
myData=%7B%0A++++%22address%22%3A+%5B%0A++++++++%7B%0A++++++++++++%22id%22%3A+76076%2C%0A++++++++++++%22streetaddress%22%3A+%223784+Howard+Ave%22%2C%0A++++++++++++%22city%22%3A+%22Washington+DC%22%2C%0A++++++++++++%22state%22%3A+%22DC%22%2C%0A++++++++++++%22zipcode%22%3A+20895%2C%0A++++++++++++%22latitude%22%3A+39.027820587%0A++++++++%7D%0A++++%5D%0A%7D
and this is the response for var_dump of $_POST:
array(0) {
}
this is a var_dump of $_POST['myData']
NULL
I'm skeptical of the way you're using the contentType property. Try taking out contentType. The default content type is
application/x-www-form-urlencoded (http://api.jquery.com/jQuery.ajax/).
Also, use something like {mydata: jsontosend} for your data property.
$.ajax({
type: "POST",
url: "process.php",
//contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: {mydata: jsontosend},
success: function(msg){
alert(msg);
}
});
Use
data:{myData: jsontosend}
It should send myData as a parameter in your request.
PHP doesn't understand application/json requests (by default).
See this question: How to post JSON to PHP with curl
I found that the comment provided by dkulkarni was the best solution here. It is necessary to read directly from the input stream to get POST data of any complexity. Changing the value of $.ajax({contentType: ''}) did not work for me..
In order to troubleshoot this problem I had set up a controller method to echo back the JSON I was posting to my server. Changing the ContentType header made no difference.
But after reading dkulkarni's comment I changed my server code from this:
return $_POST;
to this:
$data = file_get_contents('php://input');
return json_decode($data);
It worked perfectly.
As dkulkarni commented in his post (Jan 24 at 7:53), the only way to retrieve JSON sent with Content-Type application/json seems to be to retrieve it directly from the input stream.
I made a lot of tests with different approaches, but always when I set Content-Type to JSON, the $_POST in PHP is empty.
My problem is I need to set Content-Type to JSON, because the server (where I don't have access) expects it, otherwise it returns unsupported datatype. I suppose they are retrieving directly from input stream.
Why I have to reproduce that in own PHP file? Because I need to make a proxy for testing issues, but thats not the point of this thread.
Taking contentType out is not a good idea. You DO want to send this data in JSON format. Key is to do what has been mentioned above, instead of trying to access the data on the receiving end (the target php file) with $data= $_POST it is critical to use $data = file_get_contents('php://input');
Here is an example of the entire round trip for a scenario with php and knockout.js:
JS (on requesting page):
function() {
var payload = ko.toJSON({ YOUR KNOCKOUT OBJECT });
jQuery.ajax({
url: 'target.php',
type: "POST",
data: payload,
datatype: "json",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result);
}
});
};
And then in target.php (the page receiving the request):
$data = file_get_contents('php://input');
$payload_jsonDecoded = json_decode($data
Try removing ' dataType: "JSON" ' from the ajax request and check.

problem receiving data from post in php

This is my called by post to mi php in the server
$.ajax({
async: false,
type: "POST",
url: "services/ModelsService.php",
data: "{IdModelo: "+$("#brand").val()+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(values){
//do something
}
});
Now when i'm going to uses the value send from the js. always failed appears blank. But the data it's sending good because when i debug the called with charles debugging proxy works well the request
this is my php file
$json = json_decode($_POST,true);
echo $json[1]; //this bring me always blank
What i'm doing wrong in my code
echo $json['IdModelo'];
This is how you get it.
Passing the second argument true to json_decode will return an associative array so you should access array values using associative (string) index.

Categories