Post data don't send using jQuery Ajax request - javascript

how to send large base64 data Array using jQuery Ajax. Here is my code :
$.ajax({
type: "POST",
url: "addPhoto.php",
data:{photosArray:photosArray},
dataType: "json",
success: function(data) {
$(data).each(function(){
...
});
}
});
photosArray contains between 3 and 12 very long strings like :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0...
Is there any limit for POST data size in Ajax?

Open your php.ini file and find the line stating upload_max_filesize. The default it set to 2M, which is 2MB. Try increasing it to 3MB and see if you are still receiving the error.
And use
"cache": false

Is your data properly declared ? It can be either String, object or array. try following
$.ajax({
type: "POST",
url: "addPhoto.php",
data:"{photosArray:photosArray}",
dataType: "json",
success: function(data) {
$(data).each(function(){
...
});
}
});

Related

unable to iterate through json array from $.ajax

I am facing some problem in assigning data to div on my view page.
The code is something like this:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
alert(data);
$('#responsestatus').text(data.Response);
$('#divResult').html(data);
});
Here, as you can see, I can see the whole data in alert box. also, I have assigned the whole data to div and i can see whole data perfectly on my page.
The Sample Response which i got back is a huge data so i am posting link for it http://pastebin.com/eEE72ySk
Now I want to iterate through each and every data but unable to do it.
Example:
$('#responsestatus').text(data.Response.ResponseStatus);
Then error is:
UncaughtTypeError:Cannot read property 'ResponseStatus' of undefined
Please Someone tell me what is wrong here. Why cant I iterate over data in response
You are getting your response back as a string, but trying to operate on it like it were a javascript object.
There is one of two things you could do
Tell the server you're expecting json data back
Parse the string response to json after it is received.
The first should be as simple as setting the datatype property on the request
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
datatype: 'json',
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
$('#responsestatus').text(data.Response.ResponseStatus);
});
The second involves parsing the response before using it
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
Use Json datatype..i wrote a sample here..
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});

Ajax call not sending to POST

I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}

ERROR: bad URI when sending data as JSON with GET method to a Rails resource

Hello I'm performing a GET request on a RESTful Rails resource, like so:
function getGroups(category) {
$.ajax({
type: 'GET',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "category":category }),
success: function(data) {alert(data)},
contentType: "application/json",
dataType: 'json'
});
});
getGroups("own_groups");
The problem is that Webrick server errors out like this:
ERROR bad URI
`/groups.json?{%22access_token%22:%22569669d8df0456%22,%22category%22:%22own_groups%22}'.
It must be something related with how the JSON data is parsed, because I am having no problems with another GET request WITHOUT JSON data, and a POST request WITH JSON data...
Update: adding code for POST request (where JSON.stringify is required)
function addGroup(name, description) {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/groups.json',
data: JSON.stringify({"access_token":"569669d8df0456", "group_name":name, "group_description":description}),
success: function(data) { alert("ok")},
contentType: "application/json",
dataType: 'json'
});
};
addGroup("nice group", "full of people");
Do not use JSON.stringify. Simply put:
data: {"access_token":"569669d8df0456", "category":category },
Moreover, you do not need to specify complete url http://localhost:3000/groups.json, it can be just simply groups.json

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!

Array Initialiser Too Large In ajax Response

I made ajax request for getting byte of data from server using jquery.but when I get response from server at that time I get following error.
array initialiser too large
So is there any way to find out solution.
I have following code.
$.ajax({
type: 'POST',
url: 'test',
contentType: 'application/jsonp',
crossdomain: true,
dataType: "text",
dataType: "jsonp",
success: function (txt) {
}
});

Categories