AJAX failing silently - javascript

I am having a problem with one of my AJAX requests. All of this was working earlier, then I moved some files around in folders, and it must have broken something, but I have been unable to figure out what may be wrong with my pathing.
What is happening
AJAX request seems to be being ignored, nothing goes to console or the network tab, responseText is "", and I put a break point in the first line of the PHP which is never hit. It goes straight from $.ajax to the first line in my error callback. Additionally, when this PHP code is called by going straight to the page, or cron, it works fine.
I have a very similar call later to another file in the same folder that is working just fine.
What I have tried
As mentioned before, I have looked at responseText, console output, network tab, and breakpoints in my PHP (which are never reached), and I have looked around Google and stackoverflow. If I intentionally change the name to a non-existing file, I promptly get an error in the console.
Code below
$.ajax({
type: "POST",
url: "PHP/myFile.php",
data: '',
success: function () {
//Success code
},
error: function (xhr) {
var response = xhr.responseText; // response is ""
//Error code
}
});
Any ideas?
Here is the code, later in the file, which (successfully) grabs code from a file in the same folder.
$.ajax({
type: "GET",
cache: false,
url: "PHP/myOtherFile.php",
dataType: 'json',
success: function (data) {
// Success code
},
error: function () {
// Error Code
}
});
Pretty basic AJAX calls, not sure what is going on :/

Error callback is called on http errors, but also if JSON parsing on
the response fails
From: Jquery ajax error callback
From your working file, the code dataType: 'json' im blindly assuming your doing some kind of json parsing.
Try just making the "myFile.php" a simple echo 'x'; script, and check the response text. If your get something, then its because your script contains JSON parsing code, but your not passing any data to the script anyways.
Hence, the error callback would be called because the script is trying to JSON parse nothing (i.e. data: '')
I cant suggest anything else, from reading your questions description, hopefully someone else figures it out. goodluck

Related

Jquery load function throws "XML Parsing Error: not well-formed" error in firefox

Trying to load an xml file and getting the xml parsing error.
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt', function() { MD.ui.editPallets.editform_definition(); } );
Should not throw any error. Note the url provided is valid and accessible from a browser directly. The function is also being called. Somehow even after the error reported on console, page loads successfully.
Do not want to see any errors reported on console.
I think Firefox expects an Content-Type and Chrome ignores it.
$.ajax({
url : "https://192.168.23.10/SystemServices/main?system:run=html/indicators/templates/editApp-definition.xml&Id=1000205&palletId=testtt",
contentType: "text/xml",
success : function(response) {
$("#analyticForm_description").html(response);
}
});
or for the load method use ajaxSetup:
Description: Set default values for future Ajax requests. Its use is
not recommended.
$.ajaxSetup({
contentType: "text/xml"
});
$("#analyticForm_description").load('https://192.168.23.10/SystemServices/...', function() {
MD.ui.editPallets.editform_definition();
});
I was also facing a similar error and upon search i stumbled upon this post, after debugging code for a while i found out the reason.
Error shown in console
XML Parsing Error: undefined entity
Location: path-to-file.html#link3
Line Number 26, Column 29:
Here is why i was getting this error
I was dynamically generating url that i want to hit, and due to some typo i was getting undefined as the url which was used in making ajax calls resulting in this issue
$.ajax({
url: url, //this was undefined
type: "get",
data: data,
contentType: "text/xml",
success: function (response) {
//some code
},
});
Posting this as it might help someone facing the same issue.

$.ajax() returns syntax error: Unexpected end of json input

So I'm working on a website where I have to implement a chat, currently the whole thing is running on localhost.
I'm getting this error:
SyntaxError: Unexpected end of JSON input
and can't figure out why. I have googled a little but can't find an answer, that actually works. I actually did this yesterday, on another computer and that worked super, but today it won't work and I can't figure out why.
Thank you for the great answers.
$(function() {
updateChat("updateChat", null);
$(".chat-form").submit(function(event) {
event.preventDefault();
if ($(".chat-form input").val() != "") {
updateChat("sendMessage", $(".chat-form input").val());
}
});
setInterval(function() {
updateChat("updateChat", null);
}, 3000);
function updateChat(method, message) {
$.ajax({
type: "POST",
url: "action/chat.php",
data: {
function: method,
message: message
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
})
}
})
Most likely there's an error or warning in your PHP code being displayed, and because you are expecting only json, that causes the syntax error.
There are a few ways to find out what's going on:
open the developer console in your browser and see what the response is the network tab
check your PHP error log
temporarily change your dataType to html and you'll see your console.log(data)
I was getting this error due to my backend php function NOT returning a response as it should have been. It was returning nothing. My parent function that should have been returning the response was calling a child function that WAS returning a response, but the parent function wasn't passing that child return back to the ajax call.
Another possible culprit for these type of errors could be an improper python "shebang" on your back-end (server side) script.
In my particular case I had ajax call to python cgi script via Apache web server and I could not find a more descriptive error message at front-end debug tools. However, Apache logs indicated that the back-end script had problems importing a one of the python scripts because the interpreter did not recognize it. After checking the "shebang" of that back-end script sure enough it had the wrong interpreter specified because I just copied a template file over and forgot to modify it..
So, check your "shebang" at the top of your script to make sure it points to correct interpreter. Example:
For MVC controller you must return a valid JsON
return new JsonResult() { Data = new { test = 123 } };
instead of
return new JsonResult();

Ajax $array post method results in error sometimes

I have a huge problem for weeks now, I have to say I don't have a lot of AJAX experience, so it can be an easy problem for someone I hope.
I have an AJAX script, which is used for importing a JSON array from a PHP file and it works fine like 80% of the time.
But sometimes for like 1 hour a day the $ajax part results in an error.
This is my script:
function getData() {
$.ajax({
url: '/php/home.php', //Url to .php file
data: {'data': data}, //Parameter to pass to the .php file, i.e. different query IDs, etc.. - DO NOT REMOVE!
type: 'POST', //Set Ajax to 'POST' type
dataType: 'json', //Tell the return data type to the JS engine
timeout: 10000,
error: function(xhr, status, error) { //If the query fails:
alert('BETA - The cause of error is: ' + xhr.responseText); //v1.1 - display the cause of the error
},
success: function(output) { //If query is successful:
drawChart(output); //Call the chart drawing function, pass the Ajax result as parameter
}
});
}
The referenced PHP file works fine always.
This even got stranger, because I tried to find the cause and the error function gave me the following:
status: error , error: empty , xhr.responsetext: empty
So as I said it works usually, and separate JS files result in an error for the same period of time.
I have already tried the following:
tried with different browsers;
tried to implement noconflicts() before the function;
contacted my hosting and asked if I get somehow limited, not and they don't see any errors in logs either;
tried to debug and it goes to the error;
Do you have any idea what can cause the problem?
Even a hint could help me a lot! Huge thanks to everyone!

jQuery AJAX request getting response but no callbacks are fired

I have code as such:
$.ajax({
method: "GET",
url: page,
dataType: 'html',
data:data,
success: function(data){
console.log(data);
},
error: function(){
console.log('error');
}
});
Using either Chrome or Firefox's debugger I can see that the request is successful with a response of 200 OK and the response contains the expected data.
My problem is, however, that no callbacks fire whatsoever. "Success" does not fire nor does "Error". Furthermore, no deferred methods fire either, such as "done", "then", or "always".
I've been trying to trouble shoot this for the past few hours to no avail. I'm at a total loss. I've also tried using methods such as "$.get" with the same result.
In short, I'm getting the response, but the code in jQuery is not firing any callbacks and all without any visible errors in the console.
One thing I see wrong in your code is that:
method: "GET",
should be:
type: "GET",
I don't see any documented property for method in the jQuery doc. The type property is supposed to default to "GET" so this may not be the only thing wrong here.
In addition, there are cases where the error callback will not be called even if the ajax call fails (in cross-domain requests). From the jQuery doc for the error callback:
This handler is not called for cross-domain script and cross-domain JSONP requests.
This is because jQuery is expecting the server to send back a particular form of javascript and if the server doesn't do what is expected, then jQuery never knows when the request comes back and can't process it.
In these cases, you often have to figure out what might be going wrong from looking at the network trace in the debugger.
Other things to check to make sure you aren't accidentally cross domain:
Make sure the domain/subdomain are exactly the same between ajax call and the page. For example, one common mistake is for one to have www. on it and the other not.
Make both page and ajax URL are both same http or https.
If using a non-standard port number, make sure both page and ajax URL are using the same port.
The following code works. Also note that AJAX will not work with cross site scripting.
If you want to get the error you can print the "errorThrown"
<script>
$(document).ready(function () {
$('#getLink').on("click", function () {
var url = $("#myUrl");
alert(url.val());
$.ajax({
type: "GET",
url: url.val(),
dataType: 'html',
success: function (data, textStatus, xhr) {
$("#data").text(textStatus);
},
error: function (data,textStatus, errorThrown){
$("#data").text(errorThrown);
}
});
});
});
</script>
<input id="myUrl" name="myURL" type="text" value="http://localhost:35460/Home/TestPage.cshtml" />
<input type="button" value="getLink" id="getLink">
<span id="data"></span>

Can not get json response using $.getJSON

I am currently developing a Ruby on rails 3 application.
My server controller function render a json object as response:
class DaysController < BaseController
...
def the_days
...
render :json => days
end
end
In my javascript,I use the following code to get json response from server( that's from the_day function in controller)
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
var result = data.response;
alert(result)
alert(data)
},
"json"
);
I use firefox browswer and checked with Firebug, in Firebug Net->XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful.
But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??
-----------------Edited------------------
I edited my code to this one:
$.ajax({
url: myURL,
type: 'GET',
data: {
emp_id: emp_id
},
dataType: "json",
success: function(data) {
alert("hi");
alert(data)
}
});
When I run this code, the browser is stuck at success: function(data)
If data is coming back null, but the response was otherwise successful, I'd say that you're sending the request in a manner that violates the Same Origin Policy.
The request needs to be sent to the same host/port/protocol that served the original page.
If this is only an issue in your development environment, you can test in Chrome by launching it from a Terminal application with --disable-web-security.
EDIT: Try changing the parameter name from data to something else, like dat or whatever.
Then try an alert:
alert( dat );
I've heard of some browsers having trouble with the data parameter when you utilize the data property of an AJAX call.
I'm guessing that the problem is that data does not have a response property. Try alerting just the data variable. It should be the days object itself.
I wish I could just leave a comment but I guess I don't have access to that yet.
Anyway, I'd start with something even more basic. Add some text alerts just to make sure you're actually making it to where you think you are. ie...
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
alert('hi') // add this
var result = data.response;
alert('bye') // add maybe even this
alert(result)
alert(data)
},
"json"
);
Sometimes when I'm debugging I find that even my most basic assumptions are wrong.
Edit: here's some sample code from working code I recently implemented
$.ajax({
url: 'users/check_username',
type: 'GET',
data: {
username: username
},
dataType: "json",
success: function(user_exists) {
alert(user_exists) // CHANGE THIS PART
}
});
It sounds like you are not sending the correct header in your ruby application. Firebug should report the response Content Type as application/json because that is what jquery is expecting it to be.
You could try changing the datatype in your ajax call to html to see if your alerts work with that, but that doesn't really help with the json parsing.
ALL, finally, I figured out the root cause. The reason is simply because of "Invalid json data" returned in server. That's in rails controller function 'def the_days':
render :json => days
should be modified to
render :json => days.to_json
Then, everything works smoothly:) Thank you all anyhow!

Categories

Resources