$.ajax({
url: "/Course/GetChapters/",
type: "GET",
data:{id:2},
beforeSend: function () { },
success: function (result) {}
})
.done(function () {});
Can i pass a complex object via data?
JQuery Ajax - Documentation
Data -> Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So as long as you have simple name/value pairs it should work. Of course the length of the URL is limited to 2,083 characters.
try this:
var data = 'param1=' + value+ '¶m2=' + value;
OR
var data = '{param1:'val1',param2:'val2',}'.
Related
I am creating a DDBB Insert trough $.ajax:
$(document).on('click','.submitMessage', function(){
content=$('textarea').val();
img=$('#messageImg').val();
stdMsg=$('.ms_stdMsg').val();
prefix=$('.prefix').val();
phone=$('.cuadroTelefono').val();
$.ajax({
url: "../actions/newMessage.php",
type: "POST",
data:{ms_content:content, ms_img:img,ms_prefix:prefix,ms_phone:phone},
contentType: false,
cache: false,
processData:false,
success: function(data)
{
alert("Enviado");
}
});
});
And this is the way I receive code on newMessage.php:
$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];
Console gives an error
Notice: Undefined index: ms_content in C:...\newMessage.php on line 9
one for each variable passed (I have ommited entire URL)
As the posted information is an object, I guess I must decode it someway on PHP, but trying:
$ms_content = json_decode($_POST['ms_content']);
...has neither workd
You need to specify the data that you are sending with contentType parameter. For more references
$(document).on('click','.submitMessage', function(){
content=$('textarea').val();
img=$('#messageImg').val();
stdMsg=$('.ms_stdMsg').val();
prefix=$('.prefix').val();
phone=$('.cuadroTelefono').val();
$.ajax({
url: "../actions/newMessage.php",
type: "POST",
data:{ms_content:content, ms_img:img,ms_prefix:prefix,ms_phone:phone},
cache: false,
success: function(data)
{
alert("Enviado");
}
});
});
Please remove processData:false, contentType: false and then try.
You can use this $_REQUEST instead of $_POST in your php file.
$ms_content = $_REQUEST['ms_content'];
Instead of
$ms_content = $_POST['ms_content'];
Second Maybe due to url path
try giving full url path.
Third
Provide a contentType.
I think you have to access the $_GET parameters because jquery documentation says:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
http://api.jquery.com/jquery.ajax/
So you will get your data with
$ms_img = $_GET['ms_img'];
"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there
Trying to pass a array using ajax call.
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info: info, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
However when i try to catch it on the server side using :
request.getParameter("info"); //Displays null**
Also, if i wish to send an array of arrays ? is it possible?
I tried using serialize however my IE throws error that serialize : object doesnt support this property i Did include jquery lib.
You can use JSON.stringify(info) to create a JSON representation of the object/array (including an array of arrays). On the server side you should be able to get the string via getParameter and then unserialize it from JSON to create constructs JSP can use.
Yes,It is Possible to send arrays.
var info_to_send = ['hi','hello'];
$.ajax({
type: "POST",
data: {info: info_to_send, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
You can only provide strings in a request url.
You could encode the array like so:
info = JSON.stringify(info);
// results in "['hi', 'hello']"
Then send it to the server, also JSON parse on the server.
You will need to go to http://www.json.org/ to get a Java implementation of JSON parsing.
I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.
I have this code snippet in .js file
$(function () {
// KeyDates
var url = "http://localhost:8732/Design_Time_Addresses/Intel.IIP.MDF.WCF/ProgramCalendarService/GetKeyDatesCalendarNew";
$.ajax({
url: url,
data: null,
type: 'POST',
contentType: 'application/json',
dataType: 'json',
success: function (GetKeyDatesCalendarDataNew) {
alert(GetKeyDatesCalendarDataNew);
$(document).ajaxStop($.unblockUI);
}
});
});
How do i process the key value pair in GetKeyDatesCalendarDataNew?
You probably want to know how to access an object's props. For that, use the for in loop to iterate over the object's values:
success: function (GetKeyDatesCalendarDataNew) {
for(var key in GetKeyDatesCalendarDataNew)
{
var value = GetKeyDatesCalendarDataNew[key];
// do somehitng based on the key and/or value iterated
}
}
For this case, the argument of the success function is the evaluated JSON that was returned from the Ajax request. Therefore GetKeyDatesCalendarDataNew, which you should rename to something like data, becomes the actual data that your server returned.
You can only process the data if you know its structure. One simple way of knowing this would be to do console.log(GetKeyDatesCalendarDataNew) and then easily process it with a for loop if it's an array or for x in.. if it's an object.
You can use JQuery "getJSON" function where you need to pass the url and specify a callback function.Your ajax call will be handled by the getJSON function. In the callback function, you can access the Keys as properties. A nice example
Lav G
$.each(GetKeyDatesCalendarDataNew,function(key,value){
//do something here
})