Variable undefined after Ajax request - javascript

I have a globally defined JavaScript function which performs an ajax request to fetch some data from a model. The issue I am having is that when I load the page and inspect element, it gives the error:
Uncaught ReferenceError: response is not defined
Here is the function:
function getRating(work_id)
{
$.ajax({
url: '/read/getRatings',
type: 'GET',
async: true,
data: { field1: work_id},
success: function (data) {
//your success code
response = data;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
return response;
}
The function gets called in my HTML like this:
<div class="extra">
<script>
document.write(getRating(112));
</script>
</div>
Error in browser console]:
The Ajax request works fine as when I inspect it in Chrome's developer tools, the correct response comes back. However the variable response does not get initialized in the $.ajax() method.
When I try to add $response = ""; at the start of the function so that it gets explicitly defined, it always returns the empty string and the variable does not get changed inside the ajax request as it should.
Anyone know what's going wrong here?

This is a common misunderstanding of asynchronous programming. You don't have a result to return when the initial call ends-- you need a callback to do the writing for you (the success part).
function getRating(work_id, selectorToWriteTo)
{
$.ajax({
url: '/read/getRatings',
type: 'GET',
async: true,
data: { field1: work_id},
success: function (data) {
//your success code
$(selectorToWriteTo).html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error: " + thrownError);
}
});
}
HTML:
<div class="extra" id="myDiv">
<script>
getRating(112, '#myDiv')
</script>
</div>

Related

How to get HTML of a URL which response with a 404 error in jQuery?

Suppose I am trying to fetch page which throws a 404 not found response yet shows an html page. I want to get html elements of that page using jQuery.
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
console.log($(data).find('#reviews .card').text());
},
error: function(data) {
console.log($(data).find('.not-found').text());
}
});
I get this message in console window
GET http://example.com/page/2/ 404 ()
Suppose I wanna grab the title from the page which says "Page does not exist." and the JSON object data returned between the <script> </script> of the html of the page, how should I do it?
do you mean this?
jQuery Ajax error handling, show custom exception messages
success: function(){
...
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr); // I believe this returns an object
console.log(xhr.statusText); //"Not Found"
console.log(xhr.status); //404
},
});
I too had this problem:
error: function (err) {
console.log(err); // This will throw the whole error.
console.log(err.response); // This will throw the object you want to modify
console.log(error.response.status); // This will throw the status code you want!
},
Hope this works!
As stated by #RoryMcCrossan I used responseText and rewrote the code again to something like this.
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
var html = $(data);
console.log(html.find('#reviews .card').text());
},
error: function(data) {
var html = $(data.responseText)
console.log(html.find('.not-found').text());
}
});

Multiple Ajax calls appear to be treated as synchronous requests when they should not be

I have an Ajax request which changes the content of an input field on success. That input field triggers another series of Ajax requests on change. The code works, but according to the console in Chrome, it is reported that "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience". It appears this error message indicates that synchronous requests are being made.
Here is the code:
$.ajax({
type: 'GET',
url: '/widgets/test',
async: true,
success: function (response) {
$("#widgetData").val(JSON.stringify(response));
$("#widgetData").trigger("change");
},
error: function (xhr, textStatus, errorThrown) {
console.log("There was a problem requesting the widget endpoint!");
}
});
$("#widgetData").change(function () {
var obj = jQuery.parseJSON($("#widgetData").val());
$.each(obj, function (id, url) {
$("#mainContent").append("<div class='widget' id='widget" + id + "'></div>");
$("#widget" + id).load(url);
});
});
I intend all of the requests to be asynchronous and believe that what I have written should accomplish that task. Please help me determine what is wrong, and why I am getting the aforementioned error!
It appears that your first ajax request is setting async flag to false. You can change that call to following
$.ajax({
type: 'GET',
async: true,
url: '/widgets/test',
success: function (response) {
$("#widgetData").val(JSON.stringify(response));
$("#widgetData").trigger("change");
},
error: function (xhr, textStatus, errorThrown) {
console.log("There was a problem requesting the widget endpoint!");
}
});
This should fix your warning message

How retrieve responseJSON property of a jquery $.ajax object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this javascript:
$ajax = $.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
console.dir($ajax);
console.dir($ajax.responseJSON);
console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined:
Well, of course it's undefined, because at the moment when you run console at last lines of your code, response hasn't yet came from the server.
$.ajax returns promise, which you can use to attach done() and fail() callbacks, where you can use all the properties that you see. And you have actually used callback error and success, and that's where you can run code and other functions that rely on data in the response.
You can use this trick to get the response out:
jQuery.when(
jQuery.getJSON('DBConnect.php')
).done( function(json) {
console.log(json);
});
It's late but hopefully will help others.
The response, is the "data", in success... so you can access to that writing data[0], data[1], inside the success.
For example:
success: function(data) {
alert(data[0]);
},
If you want this response, out of the success, you can set a variable outside, and try this:
success: function(data) {
myVar = data;
},
Hope, this help.
For those who don't really mind if it's synchronous, like I was, you can do this:
$('#submit').click(function (event) {
event.preventDefault();
var data = $.ajax({
type: 'POST',
url: '/form',
async: false,
dataType: "json",
data: $(form).serialize(),
success: function (data) {
return data;
},
error: function (xhr, type, exception) {
// Do your thing
}
});
if(data.status === 200)
{
$('#container').html(data.responseJSON.the_key_you_want);
}
});
It runs through the motions, waits for a response from the Ajax call and then processes it afterwards if the status == 200, and inside the error function if something triggered an error.
Edit the options to match your situation. Happy coding :)

Why does jQuery enter the success function when I have a cross-domain error?

When I execute the following code from localhost, for some reason jQuery enters the success function call, when really, I am getting a cross-domain issue (CORS isn't enabled on thirdpartydomain.com and I can't change it). The value of result is undefined.
var statusCheckUrl = "https://www.thirdpartydomain.com/webchat/live?action=avail";
$.ajax({
crossDomain: true,
dataType: "script",
url: statusCheckUrl,
success: function(result) {
console.log("result is: "+result);
eval(result);
},
error: function (jqXHR, textStatus, msg) {
unavailable();
},
timeout: 2000,
cache: false
});
I would have thought that the error function would be executed in this instance. Can you tell me why it's entering the success function call?
I am using jQuery 1.10.2.

App does not have permission to make this call

Even if i give all the permission (from "https://developers.facebook.com/tools/explorer/") for my app to make a call , returned error says "App does not have permission to make this call" for an "Unlike" call. My request is below in JavaScript
$(function () {
UnLike("598330036881973");
});
function UnLike(id) {
$.ajax({
url: 'https://graph.facebook.com/' + id + '/likes?access_token=CAACEdEose0cBAEKjZCFGXGFK1uzVRsx5RZBc8lwXZA9kgnAq8ahGBKX0oIUZB0UH20m1quLukJOFOQS6PBFzGxI43QP3zpxgGWRgtoUTZADZBnkGo0HsvRry0YLnZAbsxG30XihcVQ1OHNKflOTFOjwmgaVuQdSVZCBMPRFfxsQ4Y9evjX0TqFR7Pj3GYK9c2gX4uZBvwN0VLagZDZD',
type: 'DELETE',
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
document.write(xhr.responseText);
}
});
}
What do you think the problem is? Is unliking using the OpenGraph API forbidden?

Categories