i want to load one value from a json into a var in an extjs app. The json output looks like this
{"rechten":[{"name":"baas"}]}
If i want to use it in a store i know what to do but i use that only for grids before. I want a var like this
var rechten = "baas";
so i can check this into something else:
if(rechten == "baas") { alert('je bent de baas') }
else { alert('helaas je bent arbeider')};
so my question is how can i check the name value from that json in this if else statement?
You can load your data into a store (eg. store.load()) and then check for the value via standard store methods (eg. store.getAt()).
Or you can use Ext.Ajax and Ext.JSON it will look like this
Ext.Ajax.request({
url: 'someurl',
success: function(response){
var decoded = Ext.JSON.decode(response.responseText);
console.log(decoded.rechten.name);
}
});
Second method will skip required model/store declaration and will be out of EXTJS MVC data concept, but for quick and easy data processing should be fine to use.
Ext.Ajax.request({
url: 'your_url_here',
success: function(response, opts) {
var o = Ext.decode(response.responseText);
alert(o.rechten[0].name); // alerts "baas"
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
If your json string were to come from a file named page-with-rechten.xyz this snippet could call that file and then decode the text creating a JavaScript object you could then use properties of.
You can inspect the rechten object in the console and then add the additional logic you
Ext.Ajax.request({
url: './page-with-rechten.xyz',
success: function(response){
var text,
rechten;
text = response.responseText;
console.log('response text: ', text);
rechten = Ext.decode(text);
console.log('rechten object: ', rechten);
}
});
Related
function getvalue1(){
debugger
var str=document.getElementById("SystemName").value;
var str1=document.getElementById("IP").value;
var str2=document.getElementById("SystemLevel").value;
var str3=document.getElementById("Ownera").value;
var str4=document.getElementById("Ownerb").value;
var str5=document.getElementById("SystemDesc").value;
var str6=document.getElementById("SystemDate").value;
var str7=document.getElementById("Recorder").value;
$.ajax({
type:"post",
url:"../AddServlet",
data: {
str:str,
str1:str1,
str2:str2,
str3:str3,
str4:str4,
str5:str5,
str6:str6,
str7:str7
},
async:false,
dataType:"json",
contentType:"application/json;charset=utf-8",
success:function (data) {
$.message.alert('successful');
},
error:function () {
alert("failedjump");
}
});
}
The previous is my js code, I wanna to take these "strs" into the servlet, I programmed servlet part to get the data is
enter image description here
But these strings are null in the servlet. How can I get the JSON data? thx!
getParameter will read standard form encoded data, not JSON data.
This wouldn't normally be a problem because you are sending standard form encoded data, not JSON.
However, since you have said contentType:"application/json;charset=utf-8", you are claiming to be sending JSON, so it isn't being parsed.
Remove that line.
I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}
first time using json. I currently send a postcode to a php page, and try to store the result as json:
$("#make_ajax_call").click(function()
{
var form_postcode = $("#postcode").val();
$.ajax({
type: "POST",
url: 'mapping-ajax.php',
data: { postcode: form_postcode},
success: function(data)
{
var jsonObject = data;
var trimmedpostcode = jsonObject.trimmedpostcode;
alert(jsonObject);
alert(jsonObject.trimmedpostcode);
$('#result').html(data);
//alert('Load was performed.');
}
});
});
On the other end I use a php function echo json_encode($return_array);
The two alerts give me:
{"trimmedpostcode":"CO125WL","success":true,"outputstring":"CO125WL<br\/>"}
and
Undefined
How come the second one doesn't return "CO125WL"? Do I need to tell javascript its a json object somehow?
Have you tried:
dataType: 'json'
This is how I pull in my json information in Javascript with an ajax call.
You got it. You need to call:
var obj = JSON.parse(jsonstr);
That will parse the JSON into a JavaScript Object.
Do I need to tell javascript its a json object somehow?
Yes, you will need to tell it that it's a json string. Set the mimetype of your response to the appropriate "application/json", and jQuery's intelligence will parse the text automatically and call your success function with an object instead of a string.
Or you can set the dataType of your jQuery call to "json", see the jQuery.ajax() documentation.
I have been killing myself over this for some time. I am looking to use the causes API to fetch some data from some of our causes we have active and display that via html.
I have created a facebook app and i'm trying to use jquery ajax. This is what I have:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'&format=json&callback=cbfunc",
dataType: "json",
success: function(cbfunc) {
$(cbfunc).find('count').each(function(){
var total = $(this).find('total-raised').text();
$(this).html('<p>'+total+'</p>').appendTo('#listTotalDollor');
});
}
});
});
Problem is that I am not getting anything to display. Is this a crossdomain issue or is there something I missed.
Thanks!
Updated code:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.json%22&format=json",
dataType: "json",
success: function(data) {
$.each(data.query.results, function(i, key) {
var total = key['total_raised'];
$("#listTotalDollar").html('<span>' + total + '</span>');
});
}
});
});
One last question to ask:
If I wanted to format one of the returning values as currency.
In my updated code I get a return of 5000 I would like it to read $5,000. Is there a good tut you can point me to?
You are mixing DOM and JSON access in you cbfunc. Assuming, that you want that total-raised number for each of the elements returned by that query, you can simple request JSON (as you do) and iterate over it accordingly.
$.ajax({
// !wrapped only for readability!
url: "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20xml%20where%20url%3D'\
http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'\
&format=json",
dataType: "json",
success: function(data) {
// `data` is actually a json structure (as requested)
// if you want to see it as a whole, just use
// console.log(data);
// now iterate over the json structure
// (see also: http://stackoverflow.com/q/1078118/89391)
// and set your target dom element as you like
// (this is just a dummy ...)
$.each(data.query.results, function(i, key) {
var total = key['total-raised'].content;
$("target").html('<p>' + total + '</p>');
});
}
});
Here's the code I used for debugging: https://gist.github.com/850148.
For reference, here's a sketch of the response:
Object
query: Object
count: 1
created: "2011-03-01T23:24:18Z"
lang: "en-US"
results: Object
beneficiary: Object
id: Object
name: "INTERNATIONAL FELLOWSHIP OF CHRISTIANS & JEWS"
recent-facebook-donors: "time1297716630facebook_id0nameRobert \
Alan Schoonoveramount200time1297372019facebook_id0nameCurtis En…"
total-causes: Object
total-donors: Object
total-members: Object
total-raised: Object
__proto__: Object
__proto__: Object
__proto__: Object
__proto__: Object
I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});