Okay I think I am going mad because I have done this a million times before and now I can't make it work. I am doing an ajax post to a PHP script with some simple JSON and then returning the JSON from my PHP, however it is currently showing $_POST as an empty array.
Here is my js:
$.ajax({
type: "POST",
url: "/account/book-promo.php",
data: '{"firstName":"Peter" , "lastName":"Jones"}',
success: function(response) {
console.log(response);
}
});
And my PHP:
<?php
var_dump($_POST);
exit;
Firebug shows that my request is using POST as it is supposed to and my data is being sent as JSON yet I am getting a response of:
array(0) {
}
The only thing I can think is that there is some kind of server settings that are preventing this from working, however I cant think why there would be. Maybe I have missed a bracket or something, it is driving me mad!
Any and all suggestions welcome!
send it like if you want to send it as json.
data: { data : '{"firstName":"Peter" , "lastName":"Jones"}' },
and if you want to send it as POST just remove quotes '
data: {"firstName":"Peter" , "lastName":"Jones"},
You have to do this:
$.ajax({
type: "POST",
dataType: "json", // <---------------its required if response is json
url: "/account/book-promo.php",
data: {"firstName":"Peter" , "lastName":"Jones"}, //<---instead of string send the object this way
success: function(response) {
console.log(response);
}
});
You said in your post retuning the JSON from my PHP:
so you need to use dataType:"json" and the data you are sending to your php should be sent as object (which is usually to be pair of key and values separated by : like {key:value}) as of your code you are sending a string.
Related
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.
I'm running into a problem with JQuery Mobile (new to me) and the AJAX-call. I'm using the following code:
$.ajax({
type: "POST",
url: "http://**correct url**/post/todoitem",
beforeSend: addHeaders,
dataType: "json",
contentType: "application/json",
data: { "todoitem":"test" }, // this is just as a test
success: function(result) {
alert("Success: " + JSON.stringify(result));
},
error: function() {
alert("Error: " + JSON.stringify(arguments));
}
});
While executing this, it calls a PHP script where I need the data from the todoitem, so in this case the string "text" (in the end, multiple variables are to be send, but for now I'm just using one parameter for simplicity).
My PHP code looks like this (also just for testing purposes):
echo json_encode($_POST));
The result is: nothing, null. The $_POST seems to be empty. I've searched and tried many things, but most answers (even here on stackoverflow) are about forms and people say I need to serialize the contents of the form. However, I'm not using a form at all.
I also tried
data: JSON.stringify({ "todoitem" : "test" })
as some suggested but this did not work either.
I do know that the data is being transfered because of this little PHP hack I tried:
echo file_get_contents('php://input');
That exactly shows the data: todoitem = test. So where does this all go wrong? I'm working on this for days now! Thnx in advance
The problem is with this part of your code:
contentType: "application/json",`
Removing that line should make the sent Content-Type header default to application/x-www-form-urlencoded and PHP will decode the request into $_POST.
I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)
I'm doing an AJAX call using jQuery's JSON feature.
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
pop_word_list(json, paging_value);
}
});
}
As you can see, I'm sending the response to another JavaScript function, but what I'd like to do is send the response to PHP. Is this possible, say to directly convert the response into a PHP array (not using JavaScript) and then use PHP to handle the array, etc?
Thanks in advance.
You could perform another Ajax call to the php script in the success function, passing along the JSON data as a POST param.
do this?
js (ajax) -> php (array conver to ajax) -> js (ajax) -> php ?
function get_words_json(address, username, paging_value) {
$.ajax({
type: "GET",
url: "json/" + address,
dataType: "json",
data: "username=" + username + "&paging_no_st=" + paging_value,
success: function(json){
json["paging_value"] = paging_value;
$.post("x.php", json);
}
});
}
The whole idea doesn't stick together at all... but:
If there is a reason to do that - then You want to do the $.post('phpfile.php',json,function(){},'text or whatever type You want in return');
and the whole json object goes to PHP's $_POST[] as suggested above, but I can see NO case where it should be done that way.
If You get that json from some code You can't change and want to use data in php do:
use cURL to get the data from another thing
use json_decode($data,true) to get assoc table of the whole thing
If You don't know what You're doing :)
just pass the object to another function without useless sending stuff back and forth. You might want to do empty AJAX call to trigger the php file, nothing more.