Why isn't this jquery.get function working? - javascript

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".

Related

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.

XML is not well-formed in jquery

I have called an ajax function that gather data from an xml file formatted like this
<?xml version="1.0" encoding="utf-8"?>
<values>
<value date="2015-07-12">37.170</value>
<value date="2015-07-13">7.190</value>
<value date="2015-07-12">37.170</value>
<value date="2015-07-12">3.210</value>
<value date="2015-07-12">37.20</value>
</values>
When I get the response from the console it says
not well-formed :1:80
Not sure what this means since when I use xml validator they all tell me that there are no errors. Any help would be awesome to have.
var data = [];
$.ajax({
url: 'test.xml', // name of file you want to parse
dataType: "xml", // type of file you are trying to read
success: parse, // name of the function to call upon success
async: false,
error: function(xhr, status, error) {
alert(xhr.responseText);
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
function parse(xml) {
var items = jQuery(xml).find("values");
var data = [];
var values = $(items).text();
$(document).find("Values").each(function () {
$(this).find("value").each(function () { data.push($this.text);});
});
console.log(data.length);
}
Not sure ethier how to get all of the values into the array.
You may be trying to parse it twice, per the documentation:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Thus I'm imagining that this is what you are looking for:
function parse(xml) {
//var items = jQuery(xml).find("values");
var items = xml.find("values");
var data = [];
var values = $(items).text();
$(document).find("Values").each(function () {
$(this).find("value").each(function () { data.push($this.text);});
});
console.log(data.length);
}
EDIT!
Fiddle is updated.
http://jsfiddle.net/b62tx8Ln/1/
No need to parse data with parseXML.
Erik Phillips is probably right about the double parsing. Anyways, this should work.
Note the use of ECHO in fiddle..... just to simulate a local xml-file.
$.ajax({
url: 'test.xml', // name of file you want to parse
dataType: "xml", // type of file you are trying to read
success: parse, // name of the function to call upon success
async: false,
error: function(xhr, status, error) {
alert("error");
}
});
function parse(xmldata) {
$(xmldata).find("value").each(function(){
alert($(this).text());
});
}
For anybody else having a problem parsing non-well-formed (self-closing tags) xml in IE, $(xmlthing).find('nodename').each... works, whereas IE will parse $(xmlthing).children('nodename').each... (which is fine in FF and Chrome), as nested.
That is:
<thing />
<thing />
<thing />
will be 3 things in FF/Chrome, but one in IE if you use $(node).children(thing)
$(node).find(thing) will give you 3 things in all browsers. Thanks #Steen

How to retrieve JSON array of item sent from servlet in jQuery

I'm trying to retrieve all images in database and display in webpage. The servlet sends an array of items. When I run my servlet program it displays
{"success":true,"imageInfo":[]}
But in web page the jQuery returns undefined.
I'm newbie in jQuery - please anyone help me solve this.
Javascript :
$(window).load(function()
{
$.ajax({
type: "GET",
url: "RetriveIm",
dataType: "json",
success: function( data, textStatus, jqXHR)
{
if(data.success)
{
alert(console.log(data.imageInfo.name));
var items = [];
$.each(data, function(i, item)
{
items.push('<li><img src=data:image/png;base64,'+ item.thumbarray +' data-large=data:image/png;base64,' + item.imageInfo.fullarray + ' data-description=' + item.imageInfo.disc + ' alt=' + item.imageInfo.name + ' data-id='+ item.imageInfo.imageid +'/></li>'); // close each()
$('ul.es-carousel').append( items.join('') );
});
};
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error");
console.log("Something really bad happened " + textStatus);
},
});
});
My server side program is in this question.
I don't what error in data please help me.....Thanks...
$.getJSON("url",function(json){
console.log(json)
//your set of images check object structure
$.each(json.imageInfo, function(i, item) {//... if i understood well the json you are sending
});
shall be enough for your needs.
& make sure you are sending an header('Content-Type: application/json'); before echoing your response.
you also need to move $('ul.es-carousel').append( items.join('') ); out of the $.each

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