Ajax GET request, why does success function not print? - javascript

I have this function that performs a GET request for a given id:
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: "json",
success: function(data){
console.log('findById success: ' + data.name);
currentRaceEntry = data;
renderList(currentRaceEntry);
}
});
};
When I enter sitename/rest/entries/8 it returns a page with the xml for the object requested(as expected). (I can show this code but I dont think the problem is there). When I preform this request the console shows:
findById 8
My question is why doesn't it show console.log('findById success: ' + data.name);? The xml displays in the browser which looks to me like it was successful. So why doesn't the success function appear to be called? Thanks!
EDIT
this is what it looks like:
The console in the browser is blank

If you ajax request returns XML data, you need to set dataType as "xml".
At that point, the data object in the success function is an XML fragment, not a javascript objet, and you need to process it as such. The data.name property doesn't exist.

Related

How to run php function after js append

I append a value from my .js file like so
elemscore.append("You Scored: " + score);
I then need to access database records based on the score. How can I achieve this after the append
You can perform an ajax request something like this.
var url = 'http://localhost/phalcon3/blog?month='+pmonth+'&
$.ajax({
type:"POST",
url: url
data: {postVar1:"value",postVar2:"second value"},
success: function(result){
// either do something with whats returned or call another jquery function
console.log(result);
},
error: function(){
// error reporting/handling
}
});

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

jquery $.ajax automatically evaluates javascript file

I have a file list, when the user double clicks a file, it is displayed in an editor,
The problem is, after opening a javascript file, all bootstrap functions get undefined.
UPDATE:
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
After calling this function, bootstrap functions get undefined. I'm calling it from the console, not via events now.
function openFile(file){
var filename = file.getPath();
$.ajax({
url: "${fileStorageServiceBaseUrl}" + applicationId + "/files/"+ resType + filename,
type: "GET",
dataType: "text", // THIS LINE SOLVED IT!
success: function(response) {
editor.setFile(filename, response);
}
});
openResType = resType;
$("#saveButton").prop("disabled",false);
}
From the jquery documentation:
dataType: (default: Intelligent? Guess (xml, json, script, or html)) Type: String.
The type of data that you're expecting back from the server.
"script" (this was getting selected by default): Evaluates the response as JavaScript and returns it as plain text.

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

Categories

Resources