" '$' is null or not an object " error in ajax response? - javascript

I am sending the ajax request to the tomcat server and getting response as ,
function getAgentName(){
$.ajax({
type: "POST",
url: "agentName.html",
success: function(response){
// we have the response
if(response != null && response !="" && response !="null"){
alert( "response :"+$.trim(response)); // line 10
}
},
error: function(e){
alert('Error: ' + e);
},
complete:function(){
getAgentName();
}
});
}
I got the error in response success alert in the line 10 as '$' is null or not an object .
Edit : I have already added the Jquery 1.9.1.js.
Don't know how to solve this. Hope our stack users will help me .

I guess the link to your JQuery library might be wrong. Check if you included the right one.
Here is the latest hosted by jQuery: http://code.jquery.com/jquery-latest.min.js

There's a quite a chance that there's error in response. But just to give it a proper shot, instead of using
$.trim(response)
use
response.trim()
If you're still getting issue, then it's a response related issue, else you've already solved your problem.

Related

JSON data from javascript to PHP with Jquery AJAX

Using the following code i am trying to send JSON data via javascript to a PHP script
Watching "isRunning" while stepping through the code returns true, ie suggests AJAX isn't running, however once the code progresses to the next portion of AJAX code "isRunning" changes to false;
I have tried to trap the error on the second portion - which returns "Unexpected error"
Does anyone have an suggestions as to what i am doing wrong, or how I can trap a more informative error response ?
var isRunning = true;
$.ajax({
url: url,
success: function(resp) {
isRunning = false;
}
});
jsonString = JSON.stringify(row);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'email_rma.php',
data: {
json: jsonString
},
success: function(data) {
console.log('The answer from the PHP file: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
Thank you
Thanks to everyone or their suggestions, I think the issue lies with the JSON.stringify conversion, also i noticed i didn't include the PHP side, which i have kept to a minimum basically
$data = json_decode($_POST['json']);
echo "Data:-".$data."<BR>";
Is it possible that the problem lies on the PHP side ?
As discussed many times before ajax is asynchronous which means it runs while you are requesting the isRunning variable. If you want to know if this call succeed use a network console like most modern browsers have. This will show you if the call will be made and the server response.
For the second part, the code looks to be correct. However if you run the code from your browser you only see the client side. I suggest you use the network console here as well. A small error in the url may already get your code to output Unexpected error. Either way, you need more information like server response, error codes etc..
Have you tried logging jqXHR.responseText with the unexpected error too? Or put a breakpoint on that line and examine the variables in the debugger.
If that doesn't help you could try debugging the php side and seeing how the code executes there and what goes wrong.
Also remember that ajax is asyncronous, so your isRunning could change halfway down the page, or when it's all done.
edit:
If you don't have a debugger for php it would definitely save you a ton of headaches in the long run to get one setup.
I'd recommend netbeans, since it has a robust toolset for many languages (including both javascript and php). You'd also need to configure xdebug on your server to allow remote debugging.
To handle the errors, use the error setting as you're doing, but PHP can return the JSON data too, so you can handle more errors from PHP.
$.ajax({
type: 'POST',
dataType: 'json',
url: 'email_rma.php',
data: {
json: jsonString
},
success: function(data) {
if(data.errorCode) {
console.log('The answer from the PHP file: Error #' + data.errorCode + ' - ' + data.errorException);
} else {
console.log('The answer from the PHP file: ' + data.responseText);
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
And in your PHP file, you can handle the errors, returning this if the things worked fine:
$response = array(
"responseText" => "AJAX is working OK.",
"errorCode" => 0,
"errorException" => ""
);
This if you have to return an error, like MySQL error or something like that:
$response = array(
"responseText" => "",
"errorCode" => 1,
"errorException" => "Your error message here."
);
And finally sends the JSON data back to the AJAX:
echo json_encode($response);

call to $.ajax from firefox extension not working

I am trying to make a firefox extension that will list all the videos on a page. I had already got it working as a normal js script (not as an extension) so I know the script works.
My problem is that the $.ajax inside my firefox extension doesn't get called at all. If I look at the error console it shows a message like "unsafe use of Jquery". I've tried searching Google and other sites but I couldn't come up with a solution.
Here's the code where the problem is:
var listMainVid = function ()
{
// Make a JSONP call. We are using JSONP instead of JSON because we have to make a cross-domain AJAX call
$.ajax({
url: vidinfo_q_url + "?jsoncallback=?", // Don't forget to put in the 'jsoncallback=' part
dataType: 'jsonp', // Make a JSONP request, have it received as text, and interpreted by jQuery as JSON: "jsonp text xml."
data: {
video_url: '' + doc.document.location
},
success: function ( data, textStatus, jqXHR ) // Keep in mind that this is just the request sending success.
{
if ( data.status === 'SUCCESS' )
{
var vid_loc = data.url, img_url=data.image_url;
if( Object.prototype.toString.call( vid_loc ) === '[object Array]' ) // Check if it's an array
vid_loc = data.url[0];
if( Object.prototype.toString.call( img_url ) === '[object Array]' ) // Check if it's an array
img_url = data.image_url[0];
addVideoToVidDiv( data.id, vid_loc, img_url );
}
else // Error
{
//alert ( " Error! Data=" + data.status );
}
afterMainVid();
},
error: function( xhRequest, ErrorText, thrownError )
{
Application.console.log( " Can't do because: " + ErrorText + ", " + thrownError );
afterMainVid();
}
});
afterMainVid();
}
Any help/pointers would be greatly appreciated.
OK, I finally figured it out on my own. This is to anyone else who might run into the same problem. Change the dataType: 'jsonp', TO dataType: 'json', And that's it! I don't know why but FF doesn't seem to support 'jsonp' calls from inside extensions. One thing to note here is that inside FF extensions, you don't need 'jsonp' anyway as the extensions are free to make cross-domain ajax calls. Hope this will help.
Have you fully installed the extension? You can't just execute the .xul file, you have to install it properly to let Firefox know you "trust" the extension before letting it do stuff like AJAX requests.
OK, as SomeKittens requested, I am answering my own question (didn't know I could do that).
The solution to the problem is to change the dataType: 'jsonp', To dataType: 'json'.
I don't know why but FF doesn't seem to support 'jsonp' calls from inside extensions. One thing to note here is that inside FF extensions, you don't need 'jsonp' anyway as the extensions are free to make cross-domain ajax calls. Hope this will help.
I've also provided the answer in the question itself.

AJAX $.ajax not working

This is my $.ajax function. volunteerDist is an array in a previous function and it calls myAjax(volunteerDis);However, the program always calls the error and complete functions, with an error message of undefined. What should I do? Thanks
admin-view-available-volunteeers.php is the filename where this is located
volunteerDist is an array that contains floats
function myAjax(volunteerDist){
$.ajax({
type:'POST',
url: 'admin-view-available-volunteeers.php',
data : ({
distance:volunteerDist
}),
success: function(){
alert('worked');
},
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
complete : function(){
alert('thanks');
}
});
}
If your error: handler is being called, then the remote script returned an error.
Fix the script, not the JS code!
To get better debugging on error you need to update your code, this
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
will not work - as err is a jqXHR object!
change it to this :
error: function(jqXHR, textStatus, errorThrown) {
alert("Error : " + errorThrown);
}
This will output the message sent by the server.
All the details for the params of .ajax() are documentation here
Update
Check the name of your PHP file ...
admin-view-available-volunteeers.php
has 3 es in the word volunteer ... is this the problem ?
I always get this a lot. In your admin-view-available-volunteers.php you need to make sure that you're outputting the right headers.
To do that you need to put this in your php before anything is output:
header("HTTP/1.01 200 OK");
header("Content-type: text/html");
Otherwise it is returned as a 404 to jQuery's ajax and then goes into the error and complete bits.
You may wish to try loading a different test file first, something simple that way you can test the js separately and ensure that when you hit the php script directly in your browser that there are no errors shown.
Also in the future make sure you have all these ajax calls on the same domain as your php scripts(like you do now), otherwise ajax won't work across domains without adding a "Access-Control-Allow-Origin", "*" header.

How to find the ajax status with jQuery 1.2.6

I'm using jQuery 1.2.6 (I know it's old, but I don't have a choice) I need to check the status of my ajax calls. I either want to use:
statusCode, or I could even use error(jqXHR, textStatus, errorThrown), except that textStatus, errorThrown and statusCode, aren't in my jQuery version.
Basically what I have to do, is know if the ajax call was aborted, or had an error for another reason. Any ideas how I can do this?
you could get the status text from the error callback:
$.ajax({
url: "/foo",
dataType: "text",
error: function(obj){
alert(obj.status + "\n" + obj.statusText);
}
});
http://jsfiddle.net/jnXQ4/
you can also get it from the complete callback if the request resulted in an error.
Edit: the ajax request also returns the XMLHttpRequest which you can then bind events to, though I'm not sure how cross-browser it is.
var request = $.ajax(options);
request.onabort = function(){
alert('aborted');
}

How do I catch jQuery $.getJSON (or $.ajax with datatype set to 'jsonp') error when using JSONP?

Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):
jQuery.ajax({
type: "GET",
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
And also:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
});
I've also tried adding the $.ajaxError but that didn't work either:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
Here's my extensive answer to a similar question.
Here's the code:
jQuery.getJSON(handlerURL + "&callback=?",
function(jsonResult){
alert("Success!");
})
.done(function() { alert('getJSON request succeeded!'); })
.fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
.always(function() { alert('getJSON request ended!'); });
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's a patch which may be a possible solution using a timeout callback. See bug report #3442. If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.
Detecting JSONP problems
If you don't want to download a dependency, you can detect the error state yourself. It's easy.
You will only be able to detect JSONP errors by using some sort of timeout. If there's no valid response in a certain time, then assume an error. The error could be basically anything, though.
Here's a simple way to go about checking for errors. Just use a success flag:
var success = false;
$.getJSON(url, function(json) {
success = true;
// ... whatever else your callback needs to do ...
});
// Set a 5-second (or however long you want) timeout to check for errors
setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
As thedawnrider mentioned in comments, you could also use clearTimeout instead:
var errorTimeout = setTimeout(function() {
if (!success)
{
// Handle error accordingly
alert("Houston, we have a problem.");
}
}, 5000);
$.getJSON(url, function(json) {
clearTimeout(errorTimeout);
// ... whatever else your callback needs to do ...
});
Why? Read on...
Here's how JSONP works in a nutshell:
JSONP doesn't use XMLHttpRequest like regular AJAX requests. Instead, it injects a <script> tag into the page, where the "src" attribute is the URL of the request. The content of the response is wrapped in a Javascript function which is then executed when downloaded.
For example.
JSONP request: https://api.site.com/endpoint?this=that&callback=myFunc
Javascript will inject this script tag into the DOM:
<script src="https://api.site.com/endpoint?this=that&callback=myFunc"></script>
What happens when a <script> tag is added to the DOM? Obviously, it gets executed.
So suppose the response to this query yielded a JSON result like:
{"answer":42}
To the browser, that's the same thing as a script's source, so it gets executed. But what happens when you execute this:
<script>{"answer":42}</script>
Well, nothing. It's just an object. It doesn't get stored, saved, and nothing happens.
This is why JSONP requests wrap their results in a function. The server, which must support JSONP serialization, sees the callback parameter you specified, and returns this instead:
myFunc({"answer":42})
Then this gets executed instead:
<script>myFunc({"answer":42})</script>
... which is much more useful. Somewhere in your code is, in this case, a global function called myFunc:
myFunc(data)
{
alert("The answer to life, the universe, and everything is: " + data.answer);
}
That's it. That's the "magic" of JSONP. Then to build in a timeout check is very simple, like shown above. Make the request and immediately after, start a timeout. After X seconds, if your flag still hasn't been set, then the request timed out.
I know this question is a little old but I didn't see an answer that gives a simple solution to the problem so I figured I would share my 'simple' solution.
$.getJSON("example.json", function() {
console.log( "success" );
}).fail(function() {
console.log( "error" );
});
We can simply use the .fail() callback to check to see if an error occurred.
Hope this helps :)
If you collaborate with the provider, you could send another query string parameter being the function to callback when there's an error.
?callback=?&error=?
This is called JSONPE but it's not at all a defacto standard.
The provider then passes information to the error function to help you diagnose.
Doesn't help with comm errors though - jQuery would have to be updated to also callback the error function on timeout, as in Adam Bellaire's answer.
Seems like this is working now:
jQuery(document).ajaxError(function(event, request, settings){
alert("Error");
});
I use this to catch an JSON error
try {
$.getJSON(ajaxURL,callback).ajaxError();
} catch(err) {
alert("wow");
alert("Error : "+ err);
}
Edit: Alternatively you can get the error message also. This will let you know what the error is exactly. Try following syntax in catch block
alert("Error : " + err);
Mayby this works?
.complete(function(response, status) {
if (response.status == "404")
alert("404 Error");
else{
//Do something
}
if(status == "error")
alert("Error");
else{
//Do something
}
});
I dont know whenever the status goes in "error" mode. But i tested it with 404 and it responded
you ca explicitly handle any error number by adding this attribute in the ajax request:
statusCode: {
404: function() {
alert("page not found");
}
}
so, your code should be like this:
jQuery.ajax({
type: "GET",
statusCode: {
404: function() {
alert("page not found");
}
},
url: handlerURL,
dataType: "jsonp",
success: function(results){
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("Error");
}
});
hope this helps you :)
I also posted this answer in stackoverflow - Error handling in getJSON calls
I know it's been a while since someone answerd here and the poster probably already got his answer either from here or from somewhere else. I do however think that this post will help anyone looking for a way to keep track of errors and timeouts while doing getJSON requests. Therefore below my answer to the question
The getJSON structure is as follows (found on http://api.jqueri.com):
$(selector).getJSON(url,data,success(data,status,xhr))
most people implement that using
$.getJSON(url, datatosend, function(data){
//do something with the data
});
where they use the url var to provide a link to the JSON data, the datatosend as a place to add the "?callback=?" and other variables that have to be send to get the correct JSON data returned, and the success funcion as a function for processing the data.
You can however add the status and xhr variables in your success function. The status variable contains one of the following strings : "success", "notmodified", "error", "timeout", or "parsererror", and the xhr variable contains the returned XMLHttpRequest object
(found on w3schools)
$.getJSON(url, datatosend, function(data, status, xhr){
if (status == "success"){
//do something with the data
}else if (status == "timeout"){
alert("Something is wrong with the connection");
}else if (status == "error" || status == "parsererror" ){
alert("An error occured");
}else{
alert("datatosend did not change");
}
});
This way it is easy to keep track of timeouts and errors without having to implement a custom timeout tracker that is started once a request is done.
Hope this helps someone still looking for an answer to this question.

Categories