Bing Maps REST - Javascript - 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.

Related

Issues with make jQuery ajax call to a rest api

I am trying to use jquery ajax to make a post request that returns some response but it does not seem to work properly. Sometimes it works after a long wait, other times it does not work at all.This is my code.
<script type="text/javascript">
const id = $('#auth').val();
$("#set").click(function(){
$('.spinner-grow').show();
$.post("https://ravesandboxapi.flutterwave.com/v2/gpx/transactions/escrow/settle",
{
id: id,
secret_key: "FLWSECK-25*******************0628-X"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$('.spinner-grow').hide();
});
});
</script>
what might be the issue here?
The following is a complete example of a AJAX post is handled via jQuery. Just sharing it for reference.
var url = "api/path/to/your/controller";
var data = {};
data.id = id;
data.secret = 'your-secret';
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (resultObject) {
console.log(resultObject);
},
error: function (err) {
console.log('An error occured');
}
});
If you are getting a 404 error, better check the path to the API. You can use a tool like Postman to validate your requests and then try implementing the same in code.
Also make sure that there is no CORS issue as from your code we cannot understand if your post is triggered from the same domain.

Ajax GET request, why does success function not print?

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.

Why isn't this jquery.get function working?

I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".

check if ajaxcall has been made in ie7

I have an ajax call in my document ready function. But in about 1 out of 10 times in ie7, the ajax function doesnt get called at all.
Is there a way to check if the ajax call has been made, otherwise run it again until it either runs in to the error or success functions? The problem only occurs when i run the page in ietester -> ie7 mode. Thanks
code: http://jsfiddle.net/jxEj5/
You could setup a variable as a monitor, and a timer to issue an ajax call every 5 seconds until the ajaxCall is finished.
The monitor is set through var gotAjax = false and when the Ajax is succeeded, it is set to true gotAjax = true.
Instead of call the $ajax directly, you set a time clock through setTimeout(ajaxCall, 5000). With in the timer, if the ajaxCall is set, you clear the timer through clearTimeout(ajaxCall)
$(function() {
var gotAjax = false;
var ajaxCall = function () {
if (!gotAjax) {
$.ajax({
url: '../SentinelOperationsUI/GenericHandler.ashx',
dataType: 'json',
data: {
'FunctionName': 'GetActivity',
'SearchType': 'Single',
'postedData': JSON.stringify($('#content').data('postedData'))
},
success: function(data) {
gotAjax = true;
$('#content').data('activityKey', data.SENTINEL_OPERATION_ACTIVITY_KEY);
$.ajax({
url: '../SentinelOperationsUI/ajax/activityviews/' + data.ACTIVITY_VIEW,
dataType: 'html',
success: function(data) {
$('#content').hide().html(data).fadeIn(200);
$('#parenttabs, #tabs, #tabs2, #parenttab-1, #parenttab-2').tabs();
}
});
}
});
}
else {
clearTimeout(ajaxCall);
}
};
setTimeout(ajaxCall, 5000);
});
This is an example in jQuery that should help you debug it
If you're not using jQuery, i will need to see your code :)
The error function will occur in case a 404 or similar error occurred, and in case the ajax DID occur but some unexpected response was returned and your javascript bugged, the try .. catch will help you detect the error more easily :)
$.ajax({
url: "file.php",
type : "POST",
contentType : "application/x-www-form-urlencoded",
success: function(response){
try{
// Success code
}catch(e){
// Possibly you have an error in your JS, this should alert it to you
alert(e.message);
}
},
error : function(jqXHR, textStatus, errorThrown){
// Error occured, lets see what's wrong
alert("error " + textStatus + ": " + errorThrown);
}
});

getJSON is not calling the controller action

I don't know why this is happening since there are other functions in this page that use also getJSON and they do work. I have the following JavaScript Code
function openSOPNotesDialog() {
var url = '<%: Url.Action("GetSOPNote", "SalesOrder") %>';
var id = <%: Model.SodID %>;
$.getJSON(url, { sodId : id }, function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
});
}
and then I have this method on the SalesOrderController class
public JsonResult GetSOPNote(int sodId)
{
var service = new SodSrv();
var note = service.GetSOPNotes(sodId);
return Json(note, JsonRequestBehavior.AllowGet);
}
However, the method is never called in the debugger and data is returned as null (which is what I'd expect). As I said before there are other calls in this page and they are also doing GET requests so I don't know what may be the cause.
Sounds like the browser is pulling the data from the cache since it is a get request. Make sure to set no cache headers on the server if it is not meant to be cached.
Try adding an error handler to try to track down what the issue is:
$.ajax({
dataType: 'json',
url: url,
data: { sodId : id },
success: function(data) {
alert("data: " + data);
$("#hidSOPSODId").val(data.SodID);
$("#hidNoteId").val(data.NoteID);
$("#txtSOPNotes").val(data.Description);
$("#sopNotesDialog").dialog("open");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("oops: " + textStatus + ": " + jqXHR.responseText);
}
});
I suspect that the reason is that getJSON uses get method and controllers normally allowed to accept only post methods. It's ease to check using any browser firebug for example.

Categories

Resources