Array of Objects via JSON and jQuery to Selectbox - javascript

I have problems transferring a dataset (array of objects) from a servlet to a jsp/jquery.
This is the dataset sent by the servlet (Json):
[
{aktion:"ac1", id:"26"},
{aktion:"ac2", id:"1"},
{aktion:"ac3", id:"16"},
{aktion:"ac4", id:"2"}
]
The jsp:
function getSelectContent($selectID) {
alert('test');
$.ajax({
url:'ShowOverviewDOC',
type:'GET',
data: 'q=getAktionenAsDropdown',
dataType: 'json',
error: function() {
alert('Error loading json data!');
},
success: function(json){
var output = '';
for (p in json) {
$('#'+$selectID).append($('<option>').text(json[p].aktion).attr('value', json[p].aktion));
}
}});
};
If I try to run this the Error ('Error loading json data') is alerted.
Has someone an idea where the mistake may be?
Thanks!

If the error function is running, then your server is returning an error response (HTTP response code >= 400).

To see exactly what is going on, check the textStatus and errorThrown information that is provided by the error callback. That might help narrow it down.
http://api.jquery.com/jQuery.ajax/

The way you are setting the data parameter looks a bit suspect (notice JSON encoding in my example below). Here is how it would look calling a .Net asmx
$.ajax({
url: "/_layouts/DashboardService.asmx/MinimizeWidgetState",
data: "{'widgetType':'" + widgetType + "', 'isMinimized':'" + collapsed + "'}"
});
Also the return data is by default placed in the .d property of the return variable. You can change this default behavior by adding some ajax setup script.
//Global AJAX Setup, sets default properties for ajax calls. Allows browsers to make use of native JSON parsing (if present)
//and resolves issues with certain ASP.NET AJAX services pulling data from the ".d" attribute.
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
},
dataFilter: function(data) {
var msg;
//If there's native JSON parsing then use it.
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
//If the data is stuck in the "."d" property then go find it.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, textStatus, errorThrown);
}
});

Related

jquery Autocomplete - not filtering

I am trying to user JQuery autocomplete function with an ajax call in it, which will return the list of Strings..when i am trying to type, it is showing all the list of strings and not filtering out based on the input..Not sure where i am going wrong..Below is my autocomplete function..
$("#domainNameId").autocomplete({
source : function(request, response) {
console.log("in ajax ");
$.ajax({
url : "getAllDomains",
type : "GET",
contentType : "application/json",
data : {
env : $("#environment").val()
},
dataType : "json",
success : function(data) {
response(data); // list of strings..
},
error : function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t + m);
}
console.log(" At the end");
}
});
},
});
appreciate the help..
Your backend seems to always return the entire data and not do any filtering ( The service name itself is getAllDomains). In that case there is no need to use the function form of source option to make ajax calls.
What you're doing is sending multiple AJAX requests to the server as the user types. If your backend always returns the same data, there is no point in sending multiple requests to it. You can simply fetch the data once and then initialize the autocomplete with the response as source, then the widget will do the filtering as user types.
The docs says:
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term.
So if your server doesn't do the filtering, don't use the function form to make AJAX requests.
do something like:
$(function() {
// make a one-time request
$.ajax({
url: "getAllDomains",
type: "GET",
contentType: "application/json",
dataType: "json",
success: function(data) {
// init the widget with response data and let it do the filtering
$("#domainNameId").autocomplete({
source: data
});
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t + m);
}
console.log(" At the end");
}
});
});
In the success callback, you will need to filter the data yourself using the request.term passed to the source function.
There is more information on the jQuery Autocomplete source here: https://api.jqueryui.com/autocomplete/#option-source.

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

How do I alert my json results?

I get these results via php to alert in my ajax alert
[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
How do I do $('#divid').html(message); ?
I want only specified value from the json array.
Here is the code
function showMessage(id){
var dataString = 'id=' + id;
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
success: function(results)
{
if(results == "error")
{
alert('An error occurred, please try again later. Email us with the issue if it persists.');
}
if(results != "notallowed" && results != "error" && results != "login")
{
alert(results);
alert(results[0].message);
}
}
});
}
data = [{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
$('#divid').html(data[0].message);
DEMO
You might have to parse a JSON string using jQuery.parseJSON.
// results is your JSON string from the request
data = jQuery.parseJSON(results);
$('#divid').html(data[0].message);
If you ajax you should include:
dataType: 'json'
code
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
dataType: 'json', // here
success: function(results) {
}
.........
Including this jQuery will parse the returned data as JSON for you automatically (don't need any manual parsing effort) and you'll get your result that you're trying now.
use JSON.stringify() function
var data=[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] ;
alert(JSON.stringify(data));
Here's your data broken down by levels:
[
{
"message_id":"3",
"box":"0",
"from_id":"3",
"to_id":"1",
"title":"Hello sir!",
"message":"how are you?",
"sender_ip":"",
"date_sent":"",
"status":"0"
}
]
You would use data[0].message because the first level indicates an array, hence the need of [0] to reference the first and only element, and the second is an object, which properties can be accessed by the object.member syntax.
for debugging purposes
console.log(data, data.message, "whatever")
You need to open firebug or safari's inspector and look in the "console"

Jquery JSON response handling

I have an ajax query written in jQuery that is returning valid JSON in this format
$.ajax({
type : 'POST',
url : 'ajax/job/getActiveJobs.php',
success : function(data){
if(data[''] === true){
alert('json decoded');
}
$('#waiting').hide(500);
$('#tableData').html(data['content']);
$('#message').removeClass().addClass((data.error === true)
?'error':'success').text(data.msg);
if(data.error === true)
$('#message')
},
error : function(XMLHttpRequest, textStatus, errorThrown){
$('#waiting').hide(500);
$('#message').removeClass().addClass('error').html(data.msg);
} })
I take it this is not correct as it is not displaying the data, if I use
$('#mydiv').html(data);
I get all of the data back and displayed.
any help is really appreciated
Set the dataType to be json so jQuery will convert the JSON to a JavaScript Object.
Alternatively, use getJSON() or send the application/json mime type.
Either set dataType to json or use var json = JSON.parse(data) to do it manually.
EDIT:
I'm adding this because somebody else suggested eval, don't do this because it gets passed straight into a JSON object without any sanitation first, allowing scripts to get passed leading straight into an XSS vulnerability.
The data is the Json so you will want to do this:
success: function (data) {
var newobject = eval(data);
alert(newobject.msg);
}
or do this:
$ajax({
url: url,
data: {},
dataType: "json",
success: function (newObject) {
alert(newobject.msg);
}
});

how to know if the result of an ajax request is json?

I'm doing an ajax request using $.get and as result I could get a simple string or JSON, how to know if the result is JSON (object) or not ?
EDIT:
can I return a string and somehow transform it into object/JSON ?
Its not 100% but server probably set responce header: Content-Type: application/json. So you can try to check it:
$.ajax({
url: 'url',
success: function(data, textStatus, xhr){
var spoiler = xhr.getResponseHeader('Content-Type');
spoiler == 'application/json' ? alert('JSON received') : alert('Not JSON received');
}
});
Sure, it worked only if your server sets its headers in correct way.
One more way - is try to create a function and catch errors you may have.
try {
x = ( new Function('return ' + received_data) )();
}
catch (e) {
console.log('Its not a JSON data... or its invalid.');
}
Use the typeof method to determine if it's an object or a String. If you want to convert a String to a JSON object, and if you trust the source you can use eval. Otherwise use a JSON parser, such as http://www.json.org/json_parse.js
Usually you would expect to know what the data type is, but if for some reason you don't, how about checking the 'Content-Type' header. In theory it should be 'application/json':
function responseHandler() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if(http_request.getResponseHeader("Content-Type") == 'application/json') {
// JSON
}
else {
// Not JSON
}
}
}
}
Of course, you'll have to check that the server is setting the Content-Type header correctly. Also, not sure if this will work in IE- probably not.
You can use getJSON() instead
http://api.jquery.com/jQuery.getJSON/
For the edit:
You can use
$.ajax({
type: 'get',
cache: false,
url: service,
error: function(XMLHttpRequest, textStatus, errorThrown){
failureFunction(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data){
successFunction(data);
},
dataType: 'text'
});
With dataType Text, and parse for JSON from there.
jQuery.parseJSON( json ) - http://api.jquery.com/jQuery.parseJSON/
You should know. Each url should only return one type of data.
You know how the data is coming and you can do a null check to
Like
if it is a string constructed json , do a Eval of result
IF(EmployeeDetails.SalaryDetails.lenght)
{
forloop()
}

Categories

Resources