JS: Ajax issue with json? - javascript

I have an API that returns the following JSON content.
{"server_online":"0"}
I'm trying to update a div's content to say "Online" or "Offline" depending on the 0 or 1 value.
$.ajax({
url: "http://api.dev.net/get/server/status",
success: function(result) {
$('#server-status').html(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
My issue is, the content of the div updates to an empty string?

You need to access the property of the object:
$('#server-status').html(result.server_online ? "Online" : "Offline");
You should also use dataType: "json" in the $.ajax options to ensure that it gets parsed as JSON.

In the ajax success you need to use result object and then add if statement. In the if statement you need to use jquery append() function which will add offline or onilne text to div#server-status
success: function(result) {
if(result.server_online == 0){
$('#server-status').append("<span>Offline</span>");
}
if(result.server_online == 1){
$('#server-status').append("<span>online</span>");
}
},

That's because you're not accessing the object property server_online.
Simply do the following:
$('#server-status').html(result.server_online ? "Online" : "Offline");

Related

Error appears when post value to php by using ajax

I get an error while posting datas to php file. Codes below
$.ajax({
type: "POST",
url: url,
data: "{'konuid='" + $('#step2-id').val() + "','kategoriid='" +$('#step3-id').val() +"'}",
success: function(data){
$('#form-sorular').html(data);
},
error: function(data)
{
alert(data.d);
}
});
I checked the value in php file which is coming from ajax, and values were empty.. What is wrong with this ajax.
You are passing a JSON formatted string for the data value, but I am guessing your server code is expecting values as if you posted a form. So instead of a string that looks like this:
{'konuid='step2-id-val','kategoriid='step3-id-val'}
You should pass a string that looks like this:
konuid=step2-id-val&kategoriid=step3-id-val
But rather than concatenate the string yourself, you should set the data value to an object, and then JQuery will format the string for you:
data: {
konuid: $('#step2-id').val(),
kategoriid: $('#step3-id').val()
},
Note: JQuery will properly encode the values when it builds the string.
And since your ajax call apparently returns html, I suggest you include the dataType setting:
dataType: 'html',
Also, the signature of the error callback is:
function(jqXHR, textStatus, errorThrown)
Change the error setting to:
error: function(jqXHR, textStatus, errorThrown) {
alert('Error: ' + textStatus + ', ' + errorThrown);
alert('Response: ' + jqXHR.responseText);
}

how to make two dependent ajax requests on one buttonclick

I want insert two forms as two table rows in db using a button click event.I have used ajax request to insert in database and done for one form, while making another ajax request depending on first form it is not working
here is my java script using jquery.
var transportid = 2;
$.ajax({
url : '/TransportJob/create',
type : 'POST',
data : $('form[action="/TransportJob/Create"]').serialize(),
success : function sfn(data, textStatus, jqXHR) { // **success spelling mistake**
transportid = parseInt(data);
alert('inserted id :' + data);
$('#TransportJobId').val((transportid));
$.ajax({
url : '/TransportJobAddress/create',
type : 'POST',
//beforeSend: function myintserver(xhr){
// $('#addAddress').html('<div id="temp_load" style="text-align:center">please wait ...</div>');
//},
data : $('form[action="/TransportJobAddress/Create"]').serialize(),
success : function poste(data, textStatus, jqXHR) {
$('#addAddress').html(data);
},
error : function err(jqXHR, textStatus, errorThrown) {
alert('error at address :' + errorThrown);
}
});
},
error : function myfunction(jqXHR, textStatus, errorThrown) {
alert("error at transport :" + jqXHR.textStatus);
},
complete : function completefunc() {
alert('ajax completed all requests');
}
});
return false;
});
The first ajax sucess spelling problem make correction success then it will work
In your first ajax call, changesucess to success ?
I have modify your code first ajax request success portion spelling mistake.
sucess : function sfn(data, textStatus, jqXHR) {
Change to
success : function sfn(data, textStatus, jqXHR) {
Second error at end of request is
Remove extra code
return false;
});
and Put return false; after closing complete method.
e.g.
complete : function completefunc() {
alert('ajax completed all requests');
}
return false;
});

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

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

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