I'm trying to access an item in an api so I can start getting data from the json file, but I can't seem to get anything to work. I'm unable to log any of the data I'm trying to access to the console.
$(function() {
$.ajax({
type: 'GET',
url: "xxx",
dataType: 'json',
success: function(data) {
return console.log('success', data);
return console.log(data[0].id);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
}
});
});
It isn't working because you are returning before the second console.log. the return statement is used to exit a function at that line and return the value of the rest of the line. You are returning then trying to do something after the return which actually is never ran.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return
Remove the return statements and it should work.
$.ajax({
type: 'GET',
url: "xxx",
dataType: 'json',
success: function(data) {
console.log('success', data);
console.log(data[0].id);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + 'xxx');
}
});
1) You have a problem with returning before the Id is logged to the console, as you are returning it before your you logging your Id, a return statement ends the function execution. so removing the return will do the work
2) you don't really need to console.log() everything you can just put a 'debugger;' instead of return and you can reload the page with an open console window, it will pause the code execution at the debugger; and you can hover on the 'data' being received in the success function to see all the data being received on a successful AJAX call. hope this helps
Related
I'm trying to implement a function that after consulting a service brings the variables as global.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
callback(data);
}
});
}
and I'm trying to call like this:
ajax_test("str", function(url) {
//do something with url
console.log(url);
});
Now, if I just call ajax_test() it returns an error, saying that callback is not a function.
How would be the best way to simply call the function and get the results to use global variables?
Edit:
I think a good question is: what is a good alternative to async: false? How is the best way to implement synchronous callback?
Edit 2:
For now, I'm using $.post() with $.ajaxSetup({async: false}); and it works how I expect. Still looking a way I could use with a callback.
Have to set the scope inside the success method. Adding the following should work.
function ajax_test(str1, callback){
$.ajax({
url: '/path/service',
type: 'POST',
dataType: "json",
data: {'vars':$('form').serialize(), 'test':123},
success: function(data, status, xhr){
this.callback(data);
}.bind(this)
});
}
As an argument of the ajax_test function, callback is in the scope of the ajax_test function definition and can be called anywhere there, particularly in the successcase. Note that calling ajax_test() without arguments will as expected make your code call a function that does not exist, named callback.
The following sends an Ajax request to the jsFiddle echo service (both examples of callback as anonymous or global function are given in the jsFiddle), and works properly :
function ajax_test(str1, callback){
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars':$('form').serialize(),
'test':123
})
},
success: function(data, status, xhr){
callback(data);
}
});
}
ajax_test("unusedString", function(data){
console.log("Callback (echo from jsFiddle called), data :", data);
});
Can you check that the webservice you're calling returns successfully ? Here is the jsFiddle, I hope you can adapt it to your need :
https://jsfiddle.net/dyjjv3o0
UPDATE: similar code using an object
function ajax_test(str1) {
this.JSONFromAjax = null;
var self = this;
function callback(data) {
console.log("Hello, data :", data);
console.log("Hello, this :", this);
$("#callbackResultId").append("<p>Anonymous function : " + JSON.stringify(data) + "</p>");
this.JSONFromAjax = JSON.stringify(data);
}
$.ajax({
url: '/echo/json',
type: 'POST',
dataType: "json",
data: {
json: JSON.stringify({
'vars': $('form').serialize(),
'test': 123
})
},
success: function(data, status, xhr) {
console.log("Success ajax");
// 'self' is the object, force callback to use 'self' as 'this' internally.
// We cannot use 'this' directly here as it refers to the 'ajax' object provided by jQuery
callback.call(self, data);
}
});
}
var obj = new ajax_test("unusedString");
// Right after the creation, Ajax request did not complete
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
setTimeout(function(){
// Ajax request completed, obj has been updated
console.log("obj.JSONFromAjax", obj.JSONFromAjax);
}, 2000)
You cannot expect the Ajax request to complete immediately (don't know how it behaves with async: false though, this is why you need to wait for a while before getting the actual response.
Updated jsFiddle here : http://jsfiddle.net/jjt39mg3
Hope this helps!
I'm making multiple REST calls via Javascript to determine if a user is in several Sharepoint groups.
If the user is not in the group, the REST request returns a status of 500, along with a message saying "user cannot be found".
When an error is returned, I resolve my promise with "false", so my function works ok.
But - every REST response of 500 puts an error entry in the Javascript console - is it possible to suppress those entries?
I know they don't impact the function, but it clutters up the console.
function IsUserInGroupNumber(permissionRequested,userEmail,groupNumber){
var deferred=$.Deferred();
var url=L_Menu_BaseUrl+"/_api/web/sitegroups("+groupNumber+")/Users/getByEmail('"+userEmail+"')/Email";
$.ajax({
type: 'GET',
url: url,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json; odata=verbose");
},
processData: false,
success: function (data)
{
deferred.resolve({requestedPermission:permissionRequested,groupNumber:groupNumber,hasPermission:true});
},
error: function(data){
//user not found in the group returns a 500 error - but return value of 'false'
deferred.resolve({requestedPermission:permissionRequested,groupNumber:groupNumber,hasPermission:false});
}
});
return deferred.promise();
}
The service shouldn't respond with a 500 status code. That means something on the server is failing. You can't control how the JavaScript console / browser interprets and resolves an error or status.
Also, as of jQuery 1.5, $.ajax already returns a promise: http://api.jquery.com/jquery.ajax/
You could simplify your code a great deal with something like:
function IsUserInGroupNumber(permissionRequested, userEmail, groupNumber){
return new Promise(resolve, reject) {
$.ajax({
type: 'GET',
url: L_Menu_BaseUrl + "/_api/web/sitegroups(" + groupNumber + ")/Users/getByEmail('" + email + "')/Email",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json; odata=verbose");
},
processData: false,
})
.done(function() {
resolve(true)
})
.fail(function() {
resolve(false)
})
}
from an Ajax call that was build up like this:
function GetData() {
$.ajax({
type: "POST",
url: "#Model.RouteForAjaxLastValue",//"/RCharts/AjaxMethod",//
data: "{Id: " + lastID+ "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
})
I sometimes get responses like this:
I can see that this is meant to be displayed as a webpage since its an entire page html formatted.
But is there a way to display that directly as a new page mabye?
It cuts of the rest of the message in the alert before I can even get to read what the error may be...
Use $("html").html(response.responseText); inside your success function .
success : function(response){
$("html").html(response.responseText);
}
You should probably use console.log()
but this should append it to the body:
$('body').append(response.responseText);
I am making an ajax call below and getting an error I do not understand. The variable response in the success function looks like
{"status": "complete", "username": "test", "error": "0", "message": ""}
however when I call my three alert functions inside the success function, the first one prints out the value above, but the next two print out undefined. I know the error key exists, however the javascript does not recognize it. As a result my window crashes.
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
alert(response); //prints correct response
alert(response.error); //prints undefined
alert(response["error"]); //prints undefined
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
Can somone explain what is happening and how to fix this?
This is due to a combination of two factors:
The server is sending the JSON with the wrong content type
You've used the wrong capitalization for overriding it
Consequently, jQuery is interpreting the JSON as (probably) plain text (which is why alerting the value gives you the raw JSON and not [Object object]).
You should fix this by making sure the server sends the JSON with:
Content-Type: application/json
Since it looks like you are using PHP, you can do that with:
header("Content-Type: application/json");
You should also either remove datatype: 'json' or change it to dataType: 'json'.
that because response is not parse as JSON object to do that you can do it like this:
$.ajax({
url: '/index.php/api/userLogin',
data: userInfo,
datatype: 'json',
async: 'false',
type: 'POST',
success: function(response)
{
var data = jQuery.parseJSON(response); // <---- Here parse it as JSON
alert(data.error);
// Todo with data
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
//alert("Please Try Again, we had an internal error!");
alert(err.message);
}
});
After reading various examples on stackoverflow I wrote this function :
function showGetResult(crossDomainUrl) {
$.ajax({
url: crossDomainUrl,
type : 'GET',
crossDomain: true,
success: function (data) {
debug(data);
return data;
}
});
}
and called it using this
alert(showGetResult(crossDomainUrl));
But all I get is 'undefined', this is being used in a web-browser extension inside a content-script.
This is because the Ajax request runs asynchronously. The return data doesn't do anything. You could change it to (updated to reflect the request in the comments to be able to download a script):
function showGetResult(crossDomainUrl) {
return $.ajax({
url: crossDomainUrl,
type : 'GET',
dataType: 'script',
crossDomain: true
});
}
showGetResult('http://code.jquery.com/ui/1.10.3/jquery-ui.js')
.done(function(data) {
alert("success: " + data);
})
.fail(function(jqXHR, textStatus, ex) {
alert("failed: " + textStatus);
});
For the call actually to work cross-domain, you will need to use jsonp or script. Read this wiki for more information about Same-origin policy. Refer to this answer for more information about using jsonp.
The code above will inject the downloaded jscript in the dom and execute it.
The $.ajax() set up the query, and return immediately, so the function returns before the request is completed. Specify a function to call on completion of the query using success.
function showGetResult(crossDomainUrl) {
$.ajax({
url: crossDomainUrl,
type : 'GET',
crossDomain: true,
success: showData
});
}
function showData(data){
debug(data);
return data;
}
showGetResult(crossDomainUrl);
see http://jsfiddle.net/5J66u/8/ - (updated to specify jsonp and a better URL for it)