I'm using $.post to send a form via ajax to a PHP page, which returns JSON data. Once upon a time, it worked perfectly, and the function(data) executed as normal. Somehow, I've broke it, and now it doesn't even touch the function(data). I've tried undoing most of what I've done, but I still can't find the problem.
Here's the script :
$("#modifyhome").submit(function(event) {
if($("#modifyhome").valid()) {
event.preventDefault();
var $form = $( this ),
title = $form.find('input[name="title"]').val(),
content = $form.find('textarea[name="content"]').val();
$.post("?action=page-accueil", {"title": title, "content": content},
function(data) {
if(data['error'] == 1)
{
$().message(data['message']);
$("div.jquery-message").effect("shake", {times: 3}, 900);
}
else if(data['error'] == 0)
{
$().message(data['message']);
$("div.jquery-message").effect("bounce", {times: 3}, 900);
}
else
{
$().message("Erreur de connexion au serveur : veuillez réessayer.");
$("div.jquery-message").effect("shake", {times: 3}, 900);
}
}, "json"
);
}
else
{
$("[id^=qtip-]").effect("pulsate", {times: 3}, 600);
return false;
}
});
And here is what the PHP page (?action=page-accueil) returns :
{"error":0,"message":"Page modifiée."}
That all checks out as valid JSON, but it's as if jQuery doesn't recognize it for some reason. Any help is greatly appreciated :)
You're not clear about what the problem is. At the beginning you say
Somehow, I've broke it, and now it doesn't even touch the function(data)
but then you say that jQuery is not recognizing your JSON, which means the callback function was invoked. You need to test each phase of the process to discover your error. Browser console is a must for debugging in this case.
Test cases:
is the server returning anything? If not
Is there an error in the php code? May return 500 error or could return OK, but with error message as string.
Is there a same-origin issue? Perhaps going form HTTP -> HTTPS?
If the server is returning something but it is not being parsed correctly.
Is the data being returned valid JSON? For PHP you should use json_encode function if available or something similar. jQuery side there is jQuery.parseJSON()
Is there an issue with response-type headers? In this case you will want to use normal $.ajax and set the beforeSend parameter to something like beforeSend: function(xhr){ xhr.setRequestHeader("Accept", "text/javascript") }. You will need to further research this option.
To test any of this it is fundamental that you are familiar with the browser console. Chrome Network Panel or Firebug Net Tab
I used to get this problem too, I am exactly not sure of the reason why. But I have a solution that works.
$.post("?action=page-accueil",
{"title": title, "content": content},
function(data) {
data = eval("("+data+")");
//.... Then continue it
});
Or, use .parseJSON() function to read the string as JSON, if you dont want to use eval()
$.post("?action=page-accueil",
{"title": title, "content": content},
function(data) {
data = $.parseJSON(data);
//.... Then continue it
});
Related
I'm having a big problem over the last week and I can't seem to figure out a solution.
I'm trying to post some raw XML to a server that another company has developed for us that has, I think a listener to receive this XML input. I'm posting and sending the information just fine the thing is that I don't get any response back (just like every girl I liked in highschool...).
The error i get from Chrome is: >POST http://xx.xxx.xxx.xxx:xxxx/SLISMESSAGE net::ERR_EMPTY_RESPONSE
and I've tried other browsers also but all of them the same deal except for Firefox that gives me a CORS error.
When I post the listener on the the server just says: Get Request /SLISMESSAGE.
var template = [
'<?xml version="1.0"?><request type="create-order"><PATIENT><CODE><?CODE?></CODE><DEPARTURE_DATE><?DEPARTURE_DATE?></DEPARTURE_DATE><LASTNAME><?LASTNAME?></LASTNAME><FIRSTNAME><?FIRSTNAME?></FIRSTNAME><BIRTHDAY><?BIRTHDAY?></BIRTHDAY><SEX><?SEX?></SEX><PHONE1><?PHONE1?></PHONE1><EMAIL><?EMAIL?></EMAIL><HOTEL><?HOTEL?></HOTEL><HOTELNO><?HOTELNO?></HOTELNO></PATIENT><ORDER><ORDERNO><?ORDERNO?></ORDERNO><ORDERDATE><?ORDERDATE?></ORDERDATE><ORDERTIME><?ORDERTIME?></ORDERTIME><SENDERCODE><?SENDERCODE?></SENDERCODE></ORDER><TESTS><TEST><?TEST?></TEST></TESTS></request>'
].join('\r\n');
function update() {
var len = 10;
var randomId = parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
//console.log(randomId.toString());
var variables = {
'CODE': $('input[name="wpforms[fields][25]"]').val(),//randomId.toString(),
'DEPARTURE_DATE':$('input[name="wpforms[fields][3][date]"]').val(),
'DEPARTURE_TIME':$('input[name="wpforms[fields][3][time]"]').val(),
'LASTNAME': $('input[name="wpforms[fields][6][last]"]').val(),
'FIRSTNAME': $('input[name="wpforms[fields][6][first]"]').val(),
'BIRTHDAY': $('input[name="BIRTHDAY"]').val(),
'SEX': $('input[name="wpforms[fields][9]"]').val(),
'PHONE1': $('input[name="wpforms[fields][14]"]').val(),
'EMAIL': $('input[name="wpforms[fields][15]"]').val(),
'HOTEL': $('input[name="wpforms[fields][16]"]').val(),
'HOTELNO': $('input[name="wpforms[fields][17]"]').val(),
'TEST':$('input[name="wpforms[fields][2]"]').val(),
'ORDERNO':$('input[name="wpforms[fields][25]"]').val()
};
var newXml = template.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
console.log(newXml);
var parsedNewXml = $.parseXML(newXml);
//console.log(parsedNewXml);
var order_num = document.getElementById("wpforms-1034-field_25")
$.ajax({
url: "http://xx.xxx.xxx.xxx:8008/SLISMESSAGE",
method: 'POST',
crossDomain: true,
cache: false,
async: true,
timeout:0,
data: newXml,
contentType: "application/xml",
dataType: "xml",
success : function(){
console.log('XML Sent');
alert("Data sent");
},
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
console.log('HEYYYYYYYYYYYY');
alert(order_num);
}
});
The thing is when I try to post the same XML from postman I get a response. And the weirdest of them all, when I try to post with a python script I also get a response! ????????
Note that I'm not that good at JS or jQuery and there might be something I'm really missing here but if not then WTH?
I don't know what to do. At this point I'm almost at the point of giving up even though that would mess up a lot of things in the future but I have no idea what to do...
Python Code
Response Time
Results of Python Code and JS jQuery
Python is in blue JS in red
Note that I'm not that good at JS or jQuery and there might be something I'm really missing here but if not then WTH?
I don't know what to do. At this point I'm almost at the point of giving up even though that would mess up a lot of things in the future but I have no idea what to do...
It could be a CORS issue. You can see in the console tab in developer tools if you are getting cors error. Because browser blocks the response if cors is not properly configured. When you hit the api from Python the cors issue wont be happening because the cors check happens in the browser and not in Python
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 using the jQuery Post function, for example:
var fooVar = true;
var barVar = 1;
var bazVar = "baz";
$.post("url",
{
foo: fooVar,
bar: barVar,
baz: bazVar
},
function(){
alert("success");
}
);
In my logs, I'm seeing an intermittent issue where requests to "url" are being made without any form parameters, and I only have this one function which calls it.
Is there ever a situation in which the POST request can be fired, without sending the form parameters specified in jQuery Post?
I would expect to see:
foo=true&bar=1&baz=baz
However there are no form parameters at all:
UPDATE: This issue seems to be mainly on Internet Explorer browsers (IE7-IE11) from looking at the stats, however its not exclusive to IE (Chrome, Firefox have also had issues).
jQuery Post can send a request without form parameters when the parameter values are undefined.
For example if we have the following:
var fooVar = undefined;
var barVar = 1;
var bazVar = "baz";
$.post("url",
{
foo: fooVar,
bar: barVar,
baz: bazVar
},
function(){
alert("success");
}
);
Then the form parameters posted will be:
bar=1&baz=baz
Now this doesn't solve my actual issue (from what I can tell correct conditions have been put in place to only make the call if all variables have a value), but it does answer my question.
Sounds like a browser version specific issue, try to reproduce it locally with different versions of IE. It might be a typo in the code that is handled gracefully by some versions of IE but not the others (like the trailing comma in arrays) - run a JSLint/JSHint on your JavaScript code. Another scenario I can think of is CORS preflight OPTIONS request - that has no body. Are you sure that you are not executing a CORS request? Does your Ajax URL match the origin?
Instead of using the $.post shorthand, try using $.ajax instead; not sure whether that will solve it, but it certainly won't hurt to try it out.
Plus, you'll have one less function call to worry about. Micro-optimisations ftw!
$.ajax({
type: "POST",
url: "url",
data: { foo: bar }
});
$.post is a shorthand way of using $.ajax for POST requests, so there isn't a great deal of difference between using the two . maybe the problem is somewhere else in your code, not in jquery or you browser.
but try $.ajax. it is generally better to use if you require a greater depth of configuration over your ajax request. it should work
e.g.
$.ajax({
type: "POST",
url: "test_url",
data: { name: "John", location: "Boston" },
success: function(response) {
alert('success !');
}
});
here is more https://api.jquery.com/jQuery.ajax/
Jquery function:
$(document).ready(function() {
$(".checkbox").click(function(){
var selVal = $(this).val();
$.ajax({
type: "POST",
url: 'remove_task.php', //This is the current doc
data: ({sel: selVal}),
success: function(data){
//alert(selVal);
console.log(data);
}
});
});
});
My PHP function in remove_task.php:
function remove_selected_task()
{
$task_to_remove = $_POST['sel'];
echo $task_to_remove;
}
if (isset($_POST['remsubmit']))
{
remove_selected_task();
}
Not able to pass this successfully. Can anyone help me out? Thanks in advance.
try to pass the $_POST variable into the function for ex:
remove_selected_task($_POST['sel']);
function remove_selected_task($task_to_remove)
{
echo $task_to_remove;
}
Start by trying to diagnose the issue using the browser dev tools. Press F12 to get the dev tools panel, and go to the Network tab.
Now click your checkbox and watch for what happens...
Does the network panel show the request being made to remove_task.php?
If not, then there's a problem in your javascript where it registers the click event. Maybe the selector is wrong or something like that.
If the network panel does show the request being made, click on it there to get more info about it, and then look at the request data and the response data.
Does the request send the data you're expecting it to, and in the correct format?
If not, then you'll need to debug your Javascript to see why. I can't really help with that unless I actually see the data, but you should be able to get an idea of what the problem is by what's being sent incorrectly. Maybe the checkbox value is wrong?
If it does look right, then move on to the response.
Does the response contain the data you expect?
If it has a 404 response code, then your URL is incorrect. Maybe the path is wrong?
If the response includes an error message, then you should be able to debug the PHP from that. It'll have the relevant line numbers in it, so that should be enough to get you going.
If the response is blank, then your PHP code isn't sending anything back: Maybe a syntax error (with error suppression), or maybe the program ends before it gets to echo the data. Either way, further debugging in the PHP will be required.
That's about as much help as I can give, given the info you supplied in the question. I hope that's enough to get you started.
This will solve your problem, and next time add the full code in your question.
you check if "remsubmit" exists in your php file, but you don't send it ! This should work by modifying the line data: ({sel: selVal}) as below :
$(document).ready(function() {
$(".checkbox").click(function(){
var selVal = $(this).val();
$.ajax({
type: "POST",
url: 'remove_task.php', //This is the current doc
data: {sel: selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
console.log(data);
}
});
});
});
I have a really simple chat application on a site which works pretty good.
It requests by ajax like this:
$.ajax({
url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID,
dataType: "json",
cache: false,
success: function(data) {
if (data.session_active == 0) { //If other chatter ended session
alert("Session Ended");
}
else
{
$.each(data.messages, function(i,msg){
alert(msg.message.Body);
)};
}
}
});
and gets a json response that lookes like this:
{ "session_active": "1", "messages": [ {"message": {"MsgID": "100", "UserID": "1", "Body": "heyy"}}, ]}
It works really well in at least FF and Saf but in Chrome it never gets past the .each!
This is driving me nuts, have tried everything I've come across online for days but I can't seem to get it right.
Please someone help! I can provide testserver if someone wants to firebug it themselves ;)
Perhaps the trailing comma in your messages array is causing an issue. See the responses to the following question:
Can you use a trailing comma in a JSON object?
Possible incorrect mimetype: If you look at jQuery's parsing code, it seems that if the JSON data isn't a string passed to $.parseJSON(data) then it returns null. This might be a problem as if the AJAX response's mimetype is incorrectly identified by Chrome and it doesn't interpret the AJAX response as text, it'll return null and therefore pass null to the AJAX function. The mimetype served with the AJAX response (or possibly lack of one) may therefore also be the problem:
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "#")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},
Malformed JSON: The other reason why this might work in Firefox and other browsers but not Google Chrome is the jQuery parse function tries to use the native window.JSON.parse(data) function over new Function("return " + data) if native JSON parsing is available in that browser.
Google Chrome's parsing may be more strict than Firefox is at having things like trailing commas as specified by the standard at http://www.json.org/ as stated in Danilo Celic's answer.