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

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

Related

Eror 500 with ajax and codeigniter

I have a problem with calling ajax on my view on codeigniter website. Ajax is calling method in controller on same project.
I have ajax search, which is work correctly. When I chose one of results, he open a new tab and show me a detail information from database. In some cases when I click on some results(I didn't find rule when it will be happening), ajax return me a 500 error, without go into controller method, but when I refresh the page (F5) he shows me a correct result. Did someone have a same problem, or can help me to fix it?
Here is my ajax call:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '<?=site_url('index/ajax_read_details')?>',
dataType: 'json',
cache: false,
async:true,
data: {'param':'<?=$selected?>'},
beforeSend: function (xhr) {
$('#loading').show();
},
success: function (data) {
$('#loading').hide();
var details = '<tr>' +
'<td>'+data['title']+'</td> '+
'<td>'+data['code']+'</td>' +
'</tr>';
$('#data >tbody').append(details);
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
});
</script>
I know now that he didn't go into controller method "ajax_read_details" in index controller in case when it give me an 500 error.But when I refresh, he go into that method and do it correctly job. In both cases, he send a same values but in first he didn't return values, after refresh page he give me a values :(
Short controller method is:
public function ajax_read_details()
{
$param = $this->input->post('param');
echo json_encode(array('title' => $param, 'code'=>param));
}

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);
}

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

JSON Processing - Sending JSON text string to JSP, how to process in JSP

sendng json data to another jsp page - for testing really.
You enter a JSON formatted string in a text field on my jsp. I submit this through a form request, handled by jquery processing. It is sent to a receiver JSP. I am using the following code to do this.
$.ajax({
type: "POST",
url: "receiver.jsp",
data: term, // This is a formatted JSON string
success: function(data, textStatus, jqXHR) {
alert('Success : ' + data);
alert('textStatus : ' + textStatus);
alert('jqXHR : ' + jqXHR);
var jsonJqXHR = JSON.stringify(jqXHR);
alert('jsonJqXHR : ' + jsonJqXHR);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
},
//complete: alert('complete'),
dataType: "text" // xml, json, script, text, html
});
My question is, how do I pick this POST up in the receiver JSP and do something with it? I have seen somethings with getParameter etc but I am not sure.
I think it will be easy to send it as parameter:
data: "jsonData=" + term,
Also you can put it in form input with name="jsonData" and serialize your form:
data: jQuery("form").serialize(),
Then you can read it in receiver.jsp:
<%
String jsonData = request.getParameter("jsonData");
%>

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