I have several different ajax calls on the same php page, but I get undefined index for only one function (createAlbum).
I send exactly the same parameters in each of my ajax calls. It worked fine for a few tests, but now it only works for the other ones, but not for this specific call.
I suspected that the .js file was still in the browser cache, so I cleared it and tried with other browsers, which worked for a few more attempts.
Now, I can't get it working on any browser, and definitely don't understand why.
Here is my ajax call :
$.ajax({
type: "POST",
url: BASE_URL,
data: {
action: "createAlbum",
data: JSONAlbum
},
cache: false,
success: callback
});
My php file handling the request ($_POST['action'] is always undefined with the above request) :
if (isset($_POST['action'])) {
switch ($_POST['action']) {
// Handle the action
// ...
}
} else {
echo 'ACTION : '.$_POST['action'];
}
The header containing the ajax parameters ("data" is a json containing one or more blob images, this might be the problem, but I didn't find anything saying so) :
And finally, the response containing the error :
I really hope this is not a dumb error of mine, but I asked a friend before posting, and he can't find the solution either.
Thanks for your help !
You said that the error not happens all the time (in some call yes, in other no).
The body post is sent, you see it in console. So we can exclude javascript problem.
So the problem is something that happens before or during the process.
PHP has some limitations on input vars, you can see it in php.ini.
I see that you send images in base64, so it's probable that something of these limitations are triggered.
See for example:
max_input_time
max_input_vars
post_max_size
Related
I have looked at the following thread
jQuery Ajax - Status Code 0?
However I could not find a definitive answer and I am having serious trouble trying to find the source of my issue so I am posting here in the hopes that someone can point me in the right direction.
In my code I am performing an Angular HTTP post which just sends basic JSON data, then within the on success callback I am using AJAX to upload files to the same server. (I know I should not be using jQuery and Angular however I can't change this for the moment)
It looks something like this
var deferred = $q.defer()
// first post
$http.post(url,payload,{params: params, headers: headers)
.then(function(response) {
uploadFiles(response,deferred);
// I am also sending google analytics events here
}, function(error) {
// do error stuff
}
return deferred.promise;
// upload files function
function uploadFiles(response,deferred){
$ajax({
type: 'POST',
processData: false,
contentType: false,
data: data // this new FormData() with files appended to it,
url: 'the-endpoint-for-the-upload',
dataType: 'json',
success: function(data) {
// do success stuff here
deferred.resolve(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var message = {};
if (jqXHR.status === 0) {
message.jqXHRStatusIsZero = "true";
}
if (jqXHR.readyState === 0) {
message.jqXHRReadyStateIsZero = "true";
}
if (jqXHR.status === '') {
message.jqXHRStatusIsEmptyString = "true";
}
if (jqXHR.status) {
message.jqXHRStatus = jqXHR.status;
}
if (jqXHR.readyState) {
message.jqXHRReadyState = jqXHR.readyState;
}
if (jqXHR.responseText) {
message.jqXHR = jqXHR.responseText;
}
if (textStatus) {
message.textStatus = textStatus;
}
if (errorThrown) {
message.errorThrown = errorThrown;
}
message.error = 'HTTP file upload failed';
logError(message);
deferred.resolve(message);
}
}
})
}
Not my exact code but almost the exact same.
The issue is that is works almost all of the time, but maybe three or four in every few hundred will fail. By fail I mean the error handler function is called on the file upload function and the files are not uploaded.
I get jqXHRStatus 0 and jqXHRReadyState 0 when this occurs.
The only way I am able to replicate the issue is by hitting the refresh on the browser when the request is being processed, however users have advised they are not doing this (although have to 100% confirm this)
Is there perhaps a serious flaw in my code which I am not seeing? Maybe passing deferred variable around isn't good practice? Or another way the ajax request is being cancelled that I am not considering? Could sending google analytics events at the same time be interfering?
Any advice would be great and please let me know if you would like more information on the issue.
This means, the request has been canceled.
There could be many different reasons for that, but be aware: this could be also due to a browser bug or issue - so i believe (IMHO) there is no way to prevent this kind of issues.
Think for example, you get a 503 (Service Unavailable) response. What you would do in such a case? This is also a sporadic and not predictable issue. Just live with that, and try to repost your data.
Without reinventing the wheel, I suggest you to implement:
Retrying ajax calls using the deferred api
My guess is that your code is executing before it actually gets back from the call. I.e. the call goes back and nothing was returned and it gives a 0 error. This would make sense as the error is variable. Most of the time it would return fine because the backend executed fast enough but sometimes it wouldn't because it took especially long or something else happened etc. Javascript doesn't ever REALLY stop execution. It says it does but especially passing between angular and jquery with multiple ajax requests it wouldn't be surprising if it was executing the second ajax call before it actually completed your angular post. That's why a refresh would replicate the error because it's would clear your variables.
Some things you can do to test this:
On the backend make a timer that goes for a few seconds before it returns anything. This will probably make your code fail more consistently.
Set breakpoints and see when they are being hit and the values they contain in the javascript.
Good luck!
I'm totally lost, I copied this from my other apache server where this works just great (I get response as json etc...), now I tried this on other apache server and this does not work (the post goes in to server but not as json). If I have 'json' I don't get response (because I have jsonencode in php, but if I just echo result, it will come back, however this javascript will never go to function(r), so it does not ever even alert('test').
When I remove 'json', it works just fine, however I can't have proper response because php handles it and return it in jsonencoded array. This also goes behind function(r) and shows me the results...
There is no javascript error or php errors. I don't even know where to start debugging...
I also tried $.ajax({ equilevant to both methods and same results.
$.post('request.php', { getcontent: 'modal' }, function(r) {
title.html(r.title);
content.html(r.content);
footer.html(r.btns);
$('#modal').modal('show');
tinymce.remove();
tinymce.init({ selector: 'textarea', plugins: 'link anchor code image fullscreen textcolor colorpicker' });
},'json');
Some pointers to look at:
The last argument is the expected datatype of the response, not of the sending object. Maybe php does not receive the post correctly.
You might want to set an header in php to:
header('Content-type: application/json');
To make sure your response is in json.
The url (request.php) of your post might not be reachable
Something strange is going on with an Ajax call I'm making and I can't figure out why its happening, maybe someone can shed some light.
This is the call
$.ajax({type:'POST', url: apiURL+"misc/"+cola, headers: {'apikey':localStorage.apiKey}, dataType: 'html', success:function(data) {
$("#pagina").html(data);
postCarga("pagina");
}, error: function() {
sinConexion();
}});
Now, this should take the "data" received from Ajax and fill div#pagina with it, but the div stays empty.
Here's the strange part, I called console.log(data) to see if the data is getting through and then it not only logs to the console but properly fills in the div#pagina with the returned data.
If I just try to fill it in directly, the div stays empty, but if I do anything beforehand (even something like var xxx = data;), it gets filled in correctly.
I worked around it by moving the filler function into postCarga so my final code looks like this:
$.ajax({type:'POST', url: apiURL+"misc/"+cola, headers: {'apikey':localStorage.apiKey}, dataType: 'html', success:function(data) {
postCarga(data,"pagina");
}, error: function() {
sinConexion();
}});
,but that feels strange.
// EDIT //
Here's the whole function
function postCarga(datos,que) {
$("#"+que).html(datos).animate({top:'0%'},350,'ease-in',function() { $("#cargando").css("display","none"); });
}
,originally, all it did was animate and then hide the loader, the html(datos) is part of my fix.
Ok, I just found the reason. I was testing out different things by side-stepping the received data and just trying $("#pagina").html("Hello") and other things, after all of those worked I went trough the html returned by the Ajax call and that's where I found the answer.
I changed the return from the API to send just
<h1>Hello</h1>
and it worked fine, afterwards I manually built up the whole HTML string until I had a carbon copy of what the script generated, sometimes it would load and sometimes not, which was stranger still.
I passed the returned HTML through various lints and checkers and only one of them returned an error, one of the images in the block returned a 404, so I removed that image (and only that image) from the returned HTML and it loaded fine.
In essence, it seems that when Ajax is set to html (dataType: 'html'), each and every thing - direct or remote - in the entire block must be valid html and return a success when called, or it will be silently ignored.
Changing dataType to "text" makes it skip that check and just inject everything into the div as intended.
I'm working on a scraper of my bank statements with CasperJS, so far I've managed to login and get to the statements page. I accomplished to get the table with the first page of the statement, but I need to get it complete.
The bank's web have the option to export to a .txt file (sort of a CSV actually), but in order to download it I have to be able to download the file that comes as an attachment in the response header of a POST request when I submit a form by clicking a button.
So I figured that I could do the POST via AJAX, get the response and output it. I tried running the code on the firebug console and it works, but for some reason it just doesn't work in CasperJS.
Btw, I have tried using --web-security=no , still doesn't work
This is how I'm trying to do it:
this.then(function() {
eurl = "http://bankurl.com";
response = this.evaluate(function() {
params = $("#lForm").serialize();
$.ajax({
type: "POST",
url: eurl,
data: params,
success: function (data) {
return data.responseText;
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
I wasn't able to test this with the code you provided, but it looks as though you just aren't returning anything back from the evaluate().
return __utils__.sendAJAX(url, 'POST', params);
You would probably also need to call CasperJS with the following:
casperjs --ignore-ssl-errors=true /path/to/script.js
Well, after struggling finding a way to solve this I finally did, I just put the ajax call inside a try catch and found that the error was that it wasn't reading the eurl variable (I declared it outside the evaluate). I put it inside and it worked. Thanks for your help
I've read loads of other questions about this argument, but none could solve my problem.
I make a call to a php page in this way.
$.ajax({
url: 'https://mydomain/page.php',
type: "POST",
data: {
"arg1": arg1,
"arg2": arg2
},
success: function(data, textStatus, xhr) {
//do stuff
},
error: function(xhr, textStatus) {
alert("doLogin\n- readyState: "+xhr.readyState+"\n- status: "+xhr.status);
}
});
Now, if I put this stuff on the same server as the php it works fine. Troubles start when I launch it from localhost.
In that case I receive the following in the xhr:
readyState=0, status=0, statusText="error".
Reading some answers on the topic it seems to be because of a same-origin restriction, so I added a few parameters to the call. notably:
dataType:"jsonp",
crossDomain: true,
Apparently this works better, cause now I receive readyState=4, status=200, statusText="success". Trouble is, textStatus="parsererror". I also tried other things as jsonpCallback, cache, async, jsonp in many configurations with no luck.
Now, I receive no data back, cause this call will only give me a cookie that I need.
My question is: am I doing things correctly, for starters? In both cases, what is the reason of such an error? Does the fact that I call a 'https'/POST change something, rather than a plain http/GET?
Second question is, later on I will have to call some webservices through soap requests, which will return data in xml. Will using this same technique work (assuming jQuery doc is fine and I can write dataType:"jsonp xml" to have it converted on the fly (and assuming it is the right technique as well))? I assume it won't be, as jsonp expects something on the line of callbackFN({...}) rather than an xml, right?
If none of this is correct, what would the correct way to proceed be? I can't touch the server, thus I am limited to client side.
If you set dataType as JSONP, you can only get data as JSON.
So if the url (https://mydomain/page.php) doesn't response a JSON object, you will get parsing error, because it tries to parse it and fails.
JSONP is for JSON format data only! So if you receive a parseerror this means that the output of your PHP might not be well-formed JSON
And no, it is not easily possible to have XML as response to a JSONP call ..