Ajax $array post method results in error sometimes - javascript

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!

Related

Running Ajax .POST on Local Host server and it always fails?

So I've been working on getting the .POST method for AJAX to run for a local host program.
The idea is that a user clicks on a row in a table, the col[0] of that row, which corresponds to a ID, gets saved and sent to database to retrieve the rest of the data associated with that ID. The clicking works, the ID does get saved as 'alias', but the POST always fails.
I've tried different datatypes, JSON.stringifying the data, adding content-type, and nothing has worked. I have a feeling something is wrong with my URL, but I'm just not familiar enough with this stuff to know what. Before, I was using 'http://localhost:5000/GetTestPoint.php' but that threw an invalid syntax error, so I used the IP address instead. This got rid of the syntax error, but POST still fails and I think I would have to change the IP address every time the program is run on a different computer, so I don't think that is a long term solution either. Also as a side note we don't have internet access on the work pcs so any solutions that would require that are not possible, unless the only solution is to add another package or something.
A few things to note:
alias looks like this : 420060300100
Also, for the console.log results:
jqXHR.status returns 0.
textStatus returns error.
and errorThrown returns
{"notifyType":"consoleItemLog","message":{"message":"","styles":"","hasFormatString":true,"filURL":"http://localhost:5000/TestPoints","lineNumber":37832, "columnNumber":21}}
To be honest I have no clue what the errorThrown response means, it just seems to be backend code? The line # is the line of console.log(errorThrown) but that's about the extent of I understand from it.
So my main questions are, would there be any reason that .POST doesn't work for localhost? Is my syntax correct? Is there something wrong with my url? Any help would be appreciated!!
$.ajax({
type: "POST",
url: "10.20.100.91:5000/TestPoint.php",
data: alias,
dataType: 'text'
})
.done(function() {
alert("success"); })
.fail(function( jqXHR, TextStatus, errorThrown ){
alert("failed");
console.log(jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
})
GetTestPoints.php
<?
echo $_POST["alias];
?>
There's barely anything in there, I just wanted to confirm .POST would work before I added more code to it.

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 failing silently

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

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