I want to know why we need to serialize a JavaScript Object before sending to the server.
Example:
var send_data= {
id : 10,
name : 20,
school : {
name : "xyz",
location : "some place"
}
}
If I send this data without serializing, using ajax like this
$.ajax({
type: "POST",
url: "some.php",
data: { "info" : send_data}
})
Is there something wrong with this code? Because I can access all the data without unserializing...
$data = $_POST["info"];
echo $data["school"]["name"];
The data MUST be serialized, because network traffic consists of series of bytes. At some point, your data structures must be turned into something that can be sent over a network.
However, jQuery's .ajax() function already does serialization if you use an object instead of a string for its data argument. So no need to do it there.
I don't know PHP well but if the code you have there works, then apparently PHP also automatically unserializes the data.
So I'd say that yes, serializing is necessary, but doing it the way you describe actually does serialize it in the background.
Related
I am practicing ajax and want to send big amount of data to server (for instance I want to make tags for a post which can be up to 20 tags). Currently all I do is concatenate each tag with specific symbol between them and then in server I filter it and convert it to many tags again but I don't think that's the natural way. So what is the best way to send say, 30 - 40 entries to server with ajax optimally.
UPDATE (As some of the people suggested I am showing js code example):
$(document).ready(function(){
var tagsToSend = "tag1%tag2%tag3%tag4%tag5%tag6%tag7%tag8%tag9%tag10%tag11%tag12%tag13";
$.ajax({
url: "test.php",
method: "POST",
data: {
tags: tagsToSend
},
success: function(result){
alert(result)
}
});
})
So basically in server I'll just iterate over the given tags string and filter each tag. And I want more natural way.
I think the better way is to sending tags as a json array and not GET parameter. Something like this:
var postData = {};
postData['tagsToSend'] = ["tag1", "tag2", ...];
And inside your ajax config:
data: JSON.stringify(data)
Now, you can get a json in your php file and parse it into php array.
This can help you to have more readable and cleaner request to the server.
I have different results by using filter_input(INPUT_POST, 'attribute') and $_POST['attribute'] and don't know why this happens.
The Post-Request is send by a JavaScript build with JQuery and looks like that:
// type javaScript
var formData = {
field_a: "valueA",
field_b: "",
field_c: undefined
};
$.ajax({
url: 'serverAddress',
data: {action: 99, formData: formData},
dataType: 'json',
method: 'post',
success: function(){
console.log(arguments)
}
});
My PHP-Script looks like that:
// type php
$requestMethod = INPUT_POST;
$response = [
"fi-result" => filter_input($requestMethod, 'formData'),
"direct-result" => $_POST['formData'];
];
echo json_encode($response);
the result what is coming back is not what i was awaiting because the access via filter_input returns falsein my tests and not an json object like the direct access on the super global $_POST.
// type json response
{
"fi_result": false,
"direct-result": {
"field_a": "valueA",
"field_b": ""
}
}
Why are there differences between using filter_input and direct access on $_POST?
I don't want to access the super global $_POST. Is there any way to use filter_input like above without encode formData to a String in JavaScript and decode it in PHP one simple step after encoding?
By the way. I'm using TypeScript to generate my JavaScript. That is not supporting the FormData Object (transpiler throws error on new FormData()). So i can't use this.
I found the answer deep in the PHP docs. POST is not build to transport deep object. And filter_input method tries to get simple datatypes like string or int. this method does not parse internal so i have to send it as JSON string and decode it or i can't use filter_input in my case.
i took the first and send now strings.
Does anyone know how pass form values into PHP and still return the data to JavaScript? (For use in Google Charts if anyone is wondering.)
I have an HTML form with 4 radio boxes. I'd like to pass the value of the form so that my PHP request will be modified based on the user's selection.
The results from the PHP request need to be passed to JavaScript for processing.
In the radio button on click event place a javascript function that will perform an XMLHttpRequest to the php page and have the PHP page echo some JSON content that can be decoded in the return of the XHR in Javascript.
Example of such
May this can help you.
I think that you must do an Ajax request
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( data) {
alert( "Data Saved: " + data);
});
You send data to server form your form (here sent are name and location). You read this data with javascript with OnSelect and transfert it to your PHP code and,
You get back data from server into your JavaScript code and you can do what you want with it.
Sorry if my solution use JQuery, it is better for cross-browser with less code writing !
You could use this line to parse an array into json and use it later in javascript:
json_encode($rows); //format array named $rows into json data
More info: http://php.net/manual/en/function.json-encode.php
I have a mongo collection with documents containing a boolean field :
{
name : "Tom",
active : true
}
{
name : "Jerry",
active : false
}
On the client side of my application I have an element that when clicked fires off an AJAX post that looks for all documents containing either active is equal to true or active is equal to false.
So the ajax post is as follows :
jQuery.ajax({
url : "/dev/search/searchMongo",
type : "POST",
data : {
JSON.stringify({ active : false })
},
success : function(html) {
alert(html)
}
})
The problem is is that the false value in the query is parsed to a string as part of the POST. As far as I know theres nothing I can do about that.
Is it possible to structure the query so that mongo treats the string as a boolean?
I've looked through the docs and found the $type operator that allows you to search based on a values datatype so I thought there might be some way to achieve what I'm looking for. If not I'll throw in some server side conversion logic but I'd like to avoid this if possible.
The problem here is how you are sending the data and how you are treating it on the receiving end. What you really want to do is post the "body" of the request as JSON and then make sure your server implementation is parsing that JSON body in a way where you have that data available. The default as you are doing is "form encoded".
Your ajax request should look like this:
jQuery.ajax({
url : "/dev/search/searchMongo",
type : "POST",
data : JSON.stringify({
active : false
}),
success : function(html) {
alert(html)
}
})
Then your application end on the server "parses" the body which allows the JSON to come out as an object. Very simple for JavaScript.
On the other end the "body parser" part of your otherwise normal "RESTful" service should translate the JSON "String" to an actual object. This should be the case for other languages other than JavaScript for your server but you might need to look at the parser implementation.
I'm looking for a way to return a single JSON/JSONP string from a cross-domain "AJAX" request. Rather than request the string and have JQuery return it as a generic object automatically, I want to get a hold of the string BEFORE that conversion happens. The goal here is to parse it myself so I can turn it straight into new objects of a certain type (e.g. a Person object).
So, just to make this clear, I don't want any string-to-generic-object conversion going on behind the scenes and this must work using a different domain.
Here's a non-working example of what I would like to do:
$.ajax({
type: 'GET',
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'text',
success: parseToPerson
});
function parseToPerson( textToParse ) {
// I think I can do this part, I just want to get it working up to this point
}
I'm perfectly happy if JQuery isn't involved in the solution, as long as it works. I would prefer to use JQuery, though. From what I've read, the javascript techniques used to get JSONP data (dynamically creating a script element) would probably work, but I can't seem to get that to work for me. I control the domain that I am requesting data from and I can get the data if I change the dataType in the AJAX call to 'JSONP', so I know that is working.
If your data is being retrieved from another domain, you will need to use JSONP (there are other options, but JSONP is by far the easiest if you control the service). The jQuery call will look like this:
$.ajax({
// type: 'GET', --> this is the default, you don't need this line
url: 'http://www.someOtherDomain.com/GetPerson',
dataType: 'jsonp',
success: parseToPerson
});
The actual request that goes to your service will be http://www.someOtherDomain.com/GetPerson?callback=arbitrary_function_name. On the service side, you will need to return data like this:
arbitrary_function_name("the string (or JSON data) that I want to return");
So you'll need to inspect the querystring parameters, get the value of the callback parameter, and echo it out as if you're calling a Javascript function with that name (which you are), passing in the value you want to provide through the service. Your success function will then get called with the data your service provided.
If you're deserializing the returned data into a Javascript object, you might be better off returning JSON data than a string, so the data your service returns might look like this:
arbitrary_function_name({
"name":"Bob Person",
"age":27,
"etc":"More data"
});
That way you don't have to worry about parsing the string - it'll already be in a Javascript object that's easy to use to initialize your object.
Not sure how this will work in conjuction with jsonp, but maybe converters is what you're looking for?
$.ajax(url, {
dataType: "person",
converters: {
"text person": function(textValue) {
return parseToPerson(textValue);
}
}
});