I am trying to pass an array via ajax to a remote php script for execution.
This is a snippet from what i tried
$arr=["12","13"];
$.ajax({
url:"script.php",
data:{"arr":$arr}
success: function(data){console.log(data);},
error:function(data){console.log("error in xhr");},
complete:function(data){},cache: false,type: "POST",dataType: 'json'
})
<?php
$return['arr']=json_decode($_POST['arr']);
echo json_encode($return);
?>
I caught the error in firebug : json_decode() expects parameter 1 to be string, array given.
However when i process the same php script alone.. it works fine!
Where am i going wrong and what would be the best way to handle the array ?
Try this,
data:{"arr":JSON.stringify($arr)}
let me know is this helpfull?.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Related
I am looking for get json response from third party website. Its providing me json data when I call with ajax. Its fine. I am looking for pass same json data to my PHP file. so I can decode that json data and can store in MYSQL database. So for I am trying like this
<script>
$("#diary").click(function(){
$.ajax({
type:'get',
url:'https://example.com,
data:{
},
dataType:'json',
success:function(result){
console.log(result);
$.ajax({
type: "POST",
url: "dd.php",
data:result,
dataType: "json",
success: function (msg) {
console.log(msg);
}
});
}
});
});
</script>
Its working for get data from third party site but in my php page, I am not receiving proper data so json_decode function not working. May be I am not posting correct json data to PHP page. I am not able to use CURL in PHP because its giving me connection error, its possible that third party site have some security function which does not allow me to connect via CURL so ajax is the only method for get data.
My PHP file is like below
<?php
$ajax = json_decode(file_get_contents('php://input'), true);
print_r($ajax);
?>
Let me know if anyone here can help me for solve my issue.
Thanks!
You need to call JSON.stringify() on the result and pass that through data in your ajax request. You are just sending a string that happens to be JSON data. In PHP you can call json_decode() on $_POST['data'] and you should have your data.
I am currently trying to pass a json object from ajax to php. But it does not get me anything..Below is my code. I already tried print_r[$_POST] it just returns Array(). What's wrong with this code?
This is my code: screenshot of my code
If ajax is sent with "GET" instead of "POST", you should use $ _GET in your code.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Are you sure that the Type parameter is post?
or use
print_r($_GET);
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here
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 using this function to send json to a php page:
function update_records(data) {
data = data;
$.ajax({
type: 'POST',
cache: false,
timeout: 2000,
contentType: 'application/json',
url: 'update.php',
data: data, //'data='+data+'&aid=0',
success: function() {
success_message('success');
},
error: function(){
failure_message('failure');
}
});
In firebug I can see the posted data:
[{
"postid": 66,
"values": [
"field_key=a",
"oldvalue=b",
"newvalue=c dad"
]
}]
On my php page how can I $_REQUEST the object? Or am I doing it all wrong?
i actually did solve this one using this code on my js
this is how i collected my data
i have created the object
jsonObj={"postid":postid,"value":value};
var jsonString=JSON.stringify(jsonObj);
now i sent the object using ajax
$.ajax({
type: 'POST',
url: siteurl+'/wp-content/themes/crm/modules/update_lead.php',
dataType : 'json',
data: {action:actionType,data:data},
});
and this on the target PHP file ( /wp-content/themes/crm/modules/update_lead.php)
$json=json_decode(stripslashes($_POST['data']), true);
hope this helps ...
You can use the json_decode function to decode your JSON string into an array.
JQuery has a neat function that allows us to read external and local JSON files.
jQuery.getJSON( url, [data], [callback] )
The first parameter of this function, the URL you are planning to read, is required. The second parameter is used if you need to POST data to the URL. Last but no least, the callback function, although not required, is almost always necessary.
First of all you should pass the data as "application/json" and not as "application/x-www-form-urlencoded".
...,
data: JSON.stringify(data),
...,
On the server side use json-decode() to decode the JSON encoded string into an object. This functions is very strict and relies on properly written JSON.
It tried it with the JSON you provided and it worked perfectly.
Example:
http://codepad.org/WOH2wGZv
I recommend to get rid of the surrounding square brackets if you pass only one object. I would also ensure the "values" are passed in JSON format instead of a string. This results in the following JSON:
{
"postid":66,
"values":{
"field_key":"a",
"oldvalue":"b",
"newvalue":"c dad"
}
}
On the PHP side, use $_POST['postid'] to get '66', etc. If you used type: 'GET' in your AJAX query, you should've used $_GET['postid'] on the PHP side.