Ajax get function with endpoints - javascript

I have an endpoint on the server:
app.get('/A/:A_Id/B/:B_Id/C?', callbackFunction);
After I type "http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00" the server responds with data in callbackFunction, I can see the data in address http://xx.xx.xx.xx:3000/A/1/B/1/C?startTimeUtc=03:00:00&endTimeUtc=05:00:00 (the startTimeUtc and endTimeUtc can change depending on the user inputs),
but I am not able to get data with an ajax get function:
$.ajax({
type: 'GET',
url: '/A/:A_ID/B/:B_ID/C?', success: function(result){
// result is NaN
}
What should be the correct endpoint in this case?

First off, you're not actually providing any data to the ajax call.
API_URL = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C"
$.ajax({
type:'GET', //mostly here for readability; is default for ajax
url:API_URL,
data:{
startTimeUtc:user_input_for_start_time
endTimeUtc:user_input_for_end_time
}
}).done(function(result){
console.log(result);
}).always(function(result, status){
console.log(result);
console.log(status);
});
Not sure whether the always will help you at all, but thought it might be worth a shot. You also need to include the full URL. As a wikipedia api example, it'd be : "https://en.wikipedia.org/w/api.php". i.e. you just need to go to the ?, and then the ? is optional for GET calls (regardless of whether or not the type is supplied, see jQuery ajax documentation).
An alternative approach is pasting the entire URL:
url:API_URL + "?startTimeUtc=03:00:00&endTimeUtc=05:00:00". I personally prefer using data, but it's totally up to you.

You can do something like:
var url = "http://xx.xx.xx.xx:3000/A/" + A_ID + "/B/" + B_ID + "/C?startTimeUtc=" + startTime + "&endTimeUtc=" + endTime;
$.get( url, function( data ) {
console.log(data);
});
Where A_ID, B_ID, startTime and endTime are the variables containing the respective values.

Related

jquery Autocomplete - not filtering

I am trying to user JQuery autocomplete function with an ajax call in it, which will return the list of Strings..when i am trying to type, it is showing all the list of strings and not filtering out based on the input..Not sure where i am going wrong..Below is my autocomplete function..
$("#domainNameId").autocomplete({
source : function(request, response) {
console.log("in ajax ");
$.ajax({
url : "getAllDomains",
type : "GET",
contentType : "application/json",
data : {
env : $("#environment").val()
},
dataType : "json",
success : function(data) {
response(data); // list of strings..
},
error : function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t + m);
}
console.log(" At the end");
}
});
},
});
appreciate the help..
Your backend seems to always return the entire data and not do any filtering ( The service name itself is getAllDomains). In that case there is no need to use the function form of source option to make ajax calls.
What you're doing is sending multiple AJAX requests to the server as the user types. If your backend always returns the same data, there is no point in sending multiple requests to it. You can simply fetch the data once and then initialize the autocomplete with the response as source, then the widget will do the filtering as user types.
The docs says:
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term.
So if your server doesn't do the filtering, don't use the function form to make AJAX requests.
do something like:
$(function() {
// make a one-time request
$.ajax({
url: "getAllDomains",
type: "GET",
contentType: "application/json",
dataType: "json",
success: function(data) {
// init the widget with response data and let it do the filtering
$("#domainNameId").autocomplete({
source: data
});
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t + m);
}
console.log(" At the end");
}
});
});
In the success callback, you will need to filter the data yourself using the request.term passed to the source function.
There is more information on the jQuery Autocomplete source here: https://api.jqueryui.com/autocomplete/#option-source.

AJAX response text for success

Right now I'm modifying my AJAX request to be asynchronous but I wanted to know if there was something similar to var reponse = $.ajax({ in success. Before I had my code as:
var response = $.ajax({
type : "GET",
url : url,
data : parameters,
cache : false,
async : false
}).responseText;
return response;
I tried doing using the first data argument but that just returns the parameters. Is there something similar I can use in success?
success : function(response) {
callBack(response);
}
Because the request is asynchronous you cannot just return the response.
jQuery uses something called "promises", which you can return instead:
function getUser(id) {
return $.ajax({
url: "/user",
data: { id:id },
});
}
So, whenever you want to get a user you just call the function:
var userRequest = getUser(123);
The userRequest variable now contains a "future promise". In other words, sometime in the future it will be ready for you to use it.
You cannot use it straight away but you can create a function that will run when it finally is ready. That is done using the .done() method:
userRequest.done(function (user) {
console.log("The user " + user.name + " has been loaded!");
});
If you, for example, also want to load the user's profile alongside the user then you can create two requests and then use the $.when() method:
var userRequest = getUser(123).
profileRequest = getProfileForUser(123);
$.when(userRequest, profileRequest).done(function (user, profile) {
console.log(user.name + " is " + profile.age + " years old");
});
Read more about promises over at jQuery.

AJAX success function called successfully but does not update page properly

I have the code section below which is a simple AJAX call to retrieve a JSON string from a .ASMX VB .NET Web Method. On success, it calls the createList function below, which should take the values in the JSON string (now parsed and formatted) and add them as new list items.
My issue is that the page does not update with the new list items, even though the callback function is successful. The loop executes, data is received and I have already tested with alerts just to make sure I'm not going crazy.
When I use the exact same line (substituting test data for the JSON string) to append my new list items, everything works fine.
As a side note for anyone that might be wondering why I believe I have to use this methodology:
It is important that I call the AJAX function the way I do, so I may pass multiple parameters to the function when I build the list. The other parameters allow me to specifically find which element is active in my user control.
I am relatively new to using AJAX as well. I hope I was able to explain everything clearly.
Thanks!
function getPcList(activeRow, activeTd) {
var row = $(activeRow).attr("id");
$.ajax({
url: "AJAXWebService.asmx/getPartnerColleges",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
createList(data, activeRow, activeTd);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function createList(data, activeRow, td) {
var obj = JSON.stringify(eval("(" + data.d + ")"));
var json = $.parseJSON(obj);
var row = $(activeRow).attr("id");
var newtd = $(td).attr("id");
for (i = 0; i < json.length - 1; i++) {
$("#"+row+ "#" + newtd + " > #list > #thelist")
.append("<li id='listitem'" + i +
"' style='width:100%; z-index:300; position:relative' onclick='txtAppend($(this).parents().eq(2))'>" +
json[i] + "</li>");
}
}
If the string returned from the server is a JSON, as indicated by the dataType field of the $.ajax() call, you shouldn't need to use JSON.stringify() and eval(). You should be able to parse the string directly with $.parseJSON().

Request for JSON from externel source using $.getjson. 200 success but where is it?

I'm trying to get weather data from openweathermap. This url works with coordinates I put in, and I can download the JSON when I input the url the in the browser bar. I'm trying to get this working in my page. When I run this code, in Firebug I can see the HTTP request got the 200 success code, but it's not printing the response for some reason. Am I not using getJSON properly?
var url = "http://api.openweathermap.org/data/2.5/forecast?lat="+ position.coords.latitude +"&lon=" + position.coords.longitude;
$.getJSON(url, function(res) {
console.log(res);
});
You are trying to read cross domain JSON in a function which reads JSONP.
Cross domain JSON reading is not possible.
Try a JSONP request instead;, by appending a callback
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=" +
position.coords.latitude +"&lon=" + position.coords.longitude + "&callback=?" ;
$.getJSON(url, function(res) {
console.log(res);
});
JSON response is like this :
{ 'a':22 }
JSONP response is like :
myFunction({'a':22} ) , where myFunction was the value passed as callback
jQuery does not need the name of the callback function, however needs callback to be mentioned in the URL so that it can indentify it as a JSONP request.
JSONP
If the URL includes the string "callback=?" (or similar, as defined by
the server-side API), the request is treated as JSONP instead. See the
discussion of the jsonp data type in $.ajax() for more details.
Append this ?callback=? to the url and try again like:
$.getJSON(url + '?callback=?', function(res) {
console.log(res);
});
Try this
function buildQuery() {
var str = "http://api.openweathermap.org/data/2.5/forecast?lat=27.175009&lon=78.041849";
return "select * from json where url ='" + str + "' ";
}
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
data: {
q: buildQuery(),
format: "json"
},
dataType: "jsonp",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
consol.log(data);
}
});
working Demo :-
http://jsfiddle.net/HWuDk/1/

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources