Scenario:
I have a jQuery.ajax call that is submitting three arrays to the server for saving to the database. I need to decode that combined data object that is being transferred to the server back into three arrays.
The server runs in php
If the scenario is ambiguous, what I am asking, how do you split the $input back into three arrays again. (This is on the php side.)
Expected results:
Breaking the object back into three seperate arrays for processing.
Current results:
Internal Server Error when I start to process the first array.
Note before we get to the code: I am still learning, please any tips/pointer are always welcomed.
Code:
jQuery.ajax
jQuery.ajax({
url: "save_all.php",
type: "POST",
dataType: 'json',
data: { grades: JSON.stringify($scope.grades), commutators: JSON.stringify($scope.commutators), sGrades: JSON.stringify($scope.sGrades)},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
save_all.php
<?php
$input = json_decode(file_get_contents("php://input"), true);
$grades = $input["grades"];
$commutators = $input["commutators"];
$sGrades = $input["sGrades"];
You don't have JSON as the entire POST data, you have URL encoded key/value pairs, of which the values are JSON, so you don't need to access the raw POST data. Each of your JSON strings are in the standard $_POST array.
PHP:
$grades = json_decode($_POST['grades']);
$commutators = json_decode($_POST['commutators']);
$sGrades = json_decode($_POST['sGrades']);
Note: the dataType: 'json' in your ajax request refers to the response data type, not the request.
Related
I'm trying to send data through AJAX and most places I read online say I need to send it as JSON. However, If I try to send it as JavaScript Object it actually works, wheres if I try to send it as JSON it gives me a CORS error (but that's another topic: here's a link to the issue: API Gateway CORS: no 'Access-Control-Allow-Origin' header (NON-PROXY)).
I guess my question is, is it perfectly fine for me to send the data as JavaScript object as oppose to JSON? is there a benefit of doing one over the other?
Example:
This works: (Sending data as JS Object):
$("#xform").submit(function (event) {
event.preventDefault();
var obj = { xnumber: 1 };
$.ajax({
type: 'GET',
url: 'adddresshere',
data: obj,
dataType: 'json',
contentType: 'application/json',
}).done(function (result) {
table.clear();
table.rows.add(result).draw();
});
});
This doesn't work - (sending data as JSON)
$("#xform").submit(function (event) {
event.preventDefault();
var obj = { xnumber: 1 };
var myJSON = JSON.stringify(obj);
$.ajax({
type: 'GET',
url: 'adddresshere',
data: myJSON,
dataType: 'json',
contentType: 'application/json',
}).done(function (result) {
table.clear();
table.rows.add(result).draw();
});
});
So can I just stick with sending JS object from now on as long as it works (like it does for me right now)?
Short Answer is Yes.
Explanation:
When the online blogs says that you need to pass JSON objects - They mean you need to send Java Script Object Notation objects. When you write it like:
var obj = { xnumber: 1 }
You are already creating a JSON object. This is good to send via ajax call. When you do a JSON stringify operation, it basically converts the above JSON into string. Hence, the server is unable to treat as JSON object and it will fail.
Your JavaScript Object is deserialized JSON. As Heretic Monkey pointed out, JSON.stringify serializes your JavaScript Object to be sent over the wire.
I'm posting four JSON objects to the server using a jQuery ajax request. Each object can be up to 30k characters. When all of the parameters are large the last parameter or even the last two parameters do not show up on the server. Everything works fine when the parameters are smaller though.
In chrome's network tab I see all of the parameters in their entirety. In fiddler I see the parameters in their entirety but the parameters that don't show up on the server will not have a name.
Fiddler
The structure of my request is as follows:
var formData = "json0=" + JSON.stringify(json0) + "json1=" + JSON.stringify(json1); //etc
$.ajax({
type: 'POST',
url: url,
data: formData,
success: function (result) {},
error: function() {}
});
I wouldn't think there would be a limit on a POST but it's acting like the data is being truncated for some reason. Server side I'm in Java using ParameterAware to retrieve the data but I think the issue is before it gets there since fiddler doesn't have the parameters' names.
Query strings are not made for large amounts of data, you should pass your data to your Ajax call in an object:
$.ajax({
type: 'POST',
url: url,
dataType: "JSON",
data: {
json0: json0,
json1: json1
// etc
},
success: function (result) {},
error: function() {}
});
Have a look at this article discussing the maximum length of query strings.
jQuery AJAX documentation: http://api.jquery.com/jQuery.ajax/
First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
Recently I realized that I needed to use easyXDM instead of jQuery's $.ajax in order to make a cross domain post request. After getting easyXDM set up I see that the functions line up fairly closely:
jQuery:
$.ajax({
url: "/ajax/",
method: "POST",
data: myData
});
easyXDM:
xhr.request({
url: "/ajax/",
method: "POST",
dataType: 'json', // I added this trying to fix the problem, didn't work
data: myData
});
myData is setup something like:
myData = {};
myData[1] = 'hello';
myData[2] = 'goodbye';
myData[3] = {};
myData[3][1] = 'sub1';
myData[3][2] = 'sub2';
myData[3][3] = 'sub3';
When I make the request with jQuery it handles the sub fields properly, but not with easyXDM.
Here is how the POST request comes into the server with jQuery:
screenshot-with-shadow.png http://img37.imageshack.us/img37/4526/screenshotwithshadow.png
And here is how it comes in with easyXDM:
screenshot-with-shadow.png http://img204.imageshack.us/img204/4526/screenshotwithshadow.png
How can I send an javascript object/array of key-value pairs via an easyXDM / XHR request like jQuery does?
In light of the limitations of easyXDM discussed in the comments, the only way you can use it would be to serialize your data manually when passing it to .request i.e.
xhr.request({
url: "/ajax/",
method: "POST",
data: {jsonData: JSON.stringify(myData)}
});
Alternatively you could create your own postMessage solution but you will be excluding IE7 and below.
I think you are mistaken about sending a request cross-domain via AJAX. You CAN indeed send a request cross-domain via AJAX regardless of the JavaScript API. However, in order to receive a response cross-domain, the response needs to be of data type JSONP.
JSONP is simply JSON with padding, for example:
JSON:
{ Key: "Hello", Value: "World" }
JSONP:
callback({ Key: "Hello", Value: "World" })
It is a subtle difference but JSONP by-passes browser same-origin policy and allows you to consume JSON data served by another server.
To consume JSON data coming from another server via jQuery AJAX try this:
$.ajax({
url: "http://mydomain.com/Service.svc/GetJSONP?callback=callback",
dataType: "jsonp",
data: myData,
success: function(data) {
alert(data);
}
});
For this to work you must make sure that your web service is returning results as JSONP and not JSON.
As easyXDM can't serialize properly you need to serialize data manually:
JSON.stringify(myData)
Since the request will now contain a json string rather than object then Index.html should not parse the properties to create json structure. Go to index.html that comes with easyXDM and locate the following code:
var pairs = [];
for (var key in config.data) {
if (config.data.hasOwnProperty(key)) {
pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(config.data[key]));
}
}
data = pairs.join("&");
Don't execute this code in a case of POST request. Just assign config.data to data:
data = config.data;
Say I need to use ajax to asynchronously ask the server for an xml file containing relevant data. What is the best practice on what this message should look like? Should it be a string like get_data or something similar? Should it be xml? I don't really need long polling since its a one-time (or close to it) request.
Thanks.
You can use standard a HTTP Post or Get to send the request to your server. If you don't need to specify any parameters to your server side script ( user_id, etc ) then simply appending get_data as a url parameter will work fine.
http://www.domain.com/script?get_data
If you need to send any parameters to the server in order to retrieve data it is best to encode the parameters in JSON or XML and send them as the data portion of your AJAX request. With JQuery and JSON data:
$.ajax({
type: "GET",
url: "http://www.domain.com/script",
data: { key: "value", key2: "value2" },
async: true,
dataType: "json",
success: function( data, textStatus ) {
someCallbackFucntion( data );
}
});
The message should be the url.
For example: http://www.example.com/get_data could return the data you need in the format you need (xml, json).
If you need some other data, use an other url. http://www.example.com/someotherdata
It really depends on the purpose, if everything else is XML, go for XML. Personally I perfer JSON (for the client-side at least).
In a recent implementation I made, I used a simple POST request where the key represented the type of data and the value contained the time-interval it should return.
Which could be (jQuery):
$.ajax({
type: "POST",
url: "http://www.domain.com/script",
data: { stock_value: "last_30_min", group_activity: "last_20" },
async: true,
dataType: "json",
success: function( data, textStatus ) {
someCallbackFucntion( data );
}
});
A server-side controller would then handle the request appropriately and the client-side would know what data to expect when it returned. Also the key and value would be humanly readable from both client- and server-side. Of course the time-intervals could be a timestamp or otherwise, whatever fits the need.