I get null when I pass JSON array with JQuery AJAX - javascript

I am facing a problem with the JQuery ajax function.
I am trying to send a simple json through the ajax asshown below.
$.ajax({
url: 'NewFile.jsp',
type: 'GET',
data: {"datasource":"hello1", definition:[{val1:"hello3"}]},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert("Successfully posted "+JSON.stringify(json));
}
});
The problem is that when I do
System.out.println(request.getParameter("datasource"));
System.out.println(request.getParameter("definition"));
in my NewFile.jsp then I get hello1 for the first and null for the second.
Why I get null value in the second println()?
Thanks

In the url variable inside your ajax object, give the full URL of your request. Like so:
$.ajax({
url: 'www.google.com/',
type: 'GET',
data: {"datasource":"hello1", definition:[{val1:"hello3"}]},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert("Successfully posted "+JSON.stringify(json));
}
});
Also, always make sure that there is a failure variable inside your object literal, so that you know it happened, but failed. Helps with debugging.

Related

jQuery.ajax returns html instead of json

echo json_encode($mockImageUrl); //I do this in php
In js (just the essence):
formdata.append('variation_id', variation.id);
formdata.append('image_url', s3_url);
jQuery.ajax({
url: 'http://everframe.wordpress.dev/wordpress/wp-admin/admin-ajax.php',
type: 'POST',
data: formdata,
dataType: 'json',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
and of course the problem is that I get an error "unexpected token.." as it tries to parse html as json. Tried to set contentType: 'application/json', but it starts returning only 0 without further necessary results.
Yet not sure how I could handle this.

DataTables not redraw my data

I have a problem with _fnReDraw in DataTables, I am using DataTables and that receive data of the my controller C#, my controller return json with Exception or sucess, but my DataTables ReDraw only a first situation.
For exemplo, if firs moment my controller return Exception my Datatables Redraw only exception, but se first moment return sucess my dataTables ReDraw only sucess.
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: JSON.stringify(json),
datatype: "JSON",
async: true,
contentType: "application/json; charset=utf-8",
success: function(result) {
eval($('#MydatatTables').dataTable())._fnDraw();
},
});
As is said in the comments, there doesn't seem to be any reason for you eval().
It is hard to understand exactly what you are saying in your question, but are you receiving table data back from your ajax call? If so, you need to repopulate the table with the new data before calling a table refresh. Using the new datatables api), you would do something like this:
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: JSON.stringify(json),
datatype: "JSON",
async: true,
contentType: "application/json; charset=utf-8",
success: function(result) {
var dtApi = $('#MydataTables').DataTable();
dtApi.clear(); //clear old data from table
dtApi.rows.add(result);
dtApi.draw();
}
});
If you do not need to update the data, you can just leave out the clear and rows.add. Hope this helps.

File input with a string as ajax parameter separately

I want to make an ajax call which has 2 parameters value. One file object and another string value. I need to pass 2 parameters as service will accept 2 parameters. I have written like this
$.ajax({
url: serviceParameter.url,
dataType: "JSON",
type: 'POST',
data: {fileInput: fileobject, uploadType: 'test'},
//enctype: 'multipart/form-data',
//processData: false, // Don't process the files
//contentType: false,
contentType: 'multipart/form-data',
cache: false,
success: function(response){
console.log(data);
},
error: function(e){console.log(e);}
})
It giving 404 not found exception. Please help me with some idea.

JavaScript array getting encoded when posting jQuery

I'm trying to post part of my Knockout viewmodel to our server using jQuery.Ajax.
When I build the data object it looks fine in the console, but when it gets sent via the jQuery Ajax Post the array within gets encoded. The results on the other end are readable by the server, so it works, but it disturbs me greatly (the payload is bigger for one thing).
Here's the code:
var items = $.map(self.Items(), function (item) {
return item.Key() ? {
Key: item.Key(),
PromoCode: item.PromoCode,
Qty: parseInt(item.Qty(), 10)
} : undefined;
}),
data = {
"InEditMode": true,
"Items": items
};
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
success: function (order) {
<snip>
The result as seen by FireBug is this.
Here's the decoded JSON Object
InEditMode true
Items[0][Key] 2730M0ARAX1111AAAAX0
Items[0][PromoCode]
Items[0][Qty] 3
Items[1][Key] 2730M0ARCX1111AAAAX0
Items[1][PromoCode]
Items[1][Qty] 5
Here's the Raw view
InEditMode=true&
Items%5B0%5D%5BKey%5D=2730M0ARAX1111AAAAX0&
Items%5B0%5D%5BPromoCode%5D=&
Items%5B0%5D%5BQty%5D=3&
Items%5B1%5D%5BKey%5D=2730M0ARCX1111AAAAX0&
Items%5B1%5D%5BPromoCode%5D=&
Items%5B1%5D%5BQty%5D=5
Like #codenoire said in his comment, you aren't specifying the content type. Add contentType: 'application/json; charset=utf-8' to your $.ajax call, like so:
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
<snip>
I think you need to stringify your JSON object before you post it. Use JSON.stringify(data) before you post it.
I was so close! The answer is a combination of rwisch45 and Saeedses
I had already tried adding the contentType before, but that caused it to break and I hadn't pursued it any further then that.
the solution is to add the content type AND JSON.stringify it, as so.
$.ajax({
url: '/api/order/',
type: 'POST',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
Thanks all for your help!

jquery and json ajax....how to parse the data

Below is my jquery ajax call. I see from fire bug that I am getting the json response.
Content-Type application/json
{x:1363590711.97,y:0.277528026651}
However...I cant event pop up and alert of the data? How do I get the parsed json object so i cna start working iwth it?
$.ajax({
type: 'GET',
url: 'ajax_test',
crossDomain: false,
dataType: 'json',
success: function(responseData) {
alert(responseData);
//seriesJsonData[0]['data'].push({y: responseData.y, x: responseData.x});
}
});
Your return data is already parsed when you request dataType: 'json'
$.ajax({
type: 'GET',
url: 'ajax_test',
crossDomain: false,
dataType: 'json',
success: function(responseData) {
alert(responseData.x + " " + responseData.y);
seriesJsonData[0]['data'].push(responseData);
}
});

Categories