How can i put json result into an input value using jQuery? - javascript

I am trying to put json result into a input the value.
I have this code:
$.ajax({
type:"POST",
url: '{% url "url_searchTour"%}',
data: data1,
success: function(jsonAjaxResult){
console.log(JSON.stringify(jsonAjaxResult));
$('#txt_nombre').val(jsonAjaxResult);
},
error: function(data){
alert("Got an error, Pleas conctact the Administrator");
}
});
The view returns single json object.
View:
dataSer1 = serializers.serialize("json",dataT1)
dataSer2 = serializers.serialize("json",dataT2)
data0 = json.dumps({'dataEsp':dataSer1,'dataEng':dataSer2})
return HttpResponse(data0, content_type='application/json')
How can I put the information returned into a inputy value. For example like this:
$('#txt_nombre').val(jsonAjaxResult['dataEsp.name']); //from obj1
$('#txt2_nombre').val(jsonAjaxResult['dataEng.name']); //from obj2
What i have so far is this:
console.log(jsonAjaxResult['dataEsp']);
It retuns the next code:
[{
"fields":
{
"Monday": true,
"restrictions": "No kids",
"name": "Yate Mar",
},
"model": "appMain.touresp",
"pk": 1
}]

JSON.stringify() it's the way to do it, check how it's working with your data.
var jsonData = [{
"fields":
{
"Monday": true,
"restrictions": "No kids",
"name": "Yate Mar",
},
"model": "appMain.touresp",
"pk": 1
}]
console.log(jsonData)
var txt = document.getElementById("myTxt");
txt.innerHTML = JSON.stringify(jsonData)
<textarea id="myTxt"></textarea>

Related

Nested JSON data source with DataTables

I have JSON data source with nested obvar
jsonData = {
"block":[
{"name": "Block 1. Social Work",
"subblock": [{
"name": "Block 1.1. Student Org (SO)",
"paragraph": [
{
"name": "Head of SO",
"score": "10,00"
}, {
"name": "Head of Group" ,
"score": "9, 00 "
}]
}]
}]
};
Wher block.name = table caption, subblock.name =
var subbl_content=document.createElement("th");
subbl_content.colSpan=4;
subbl_content.innerHTML=jsonData[0].block[0].subblock[0].name;
paragraph = table content. I try to place it to DataTable in the following way
$(document).ready(function() {
.....
$('#example').DataTable(
{
data: jsonData,
columns: [
{ data: 'block[0].subblock[0].paragraph[0].name' },
{ data: 'block[0].subblock[0].paragraph[0].score' }
]
});
}) ;
It would seem that must work but as a result i have in one Cell next value Head of SOiHead of Group. But when i some change data like
$('#example').DataTable(
{
data: jsonData.block[0].subblock[0].paragraph,
columns: [
{ data: 'name' },
{ data: 'score' }
]
});
All works. Is it normal or are there other methods of solution?

Return JSON results as JS array with AJAX?

Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data

Populate HTML with JSON array in Javascript

This question has been asked a couple of time here, but I haven't seen any of the responses work for me.
I have this piece of code built with cakePHP which successfully returns the data in JSON format, but I haven't been able to insert this JSON data into HTML div using Javascript.
$('.book-click').click(function (e) {
e.preventDefault();
var getHotel = $(this).attr('hotel-id');
$.ajax({
type: "POST",
url: "<?php echo $this->Html->URL(array('action' => 'postBook')); ?>",
data: {
hotel: getHotel
},
cache: false,
dataTye: "json",
success: function (JSONObject) {
var myData = "";
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
myData += JSONObject[key];
}
}
/*console.log(myData);*/
alert(myData[key]["hotelname"]); //Giving undifined in alert
}
});
});
And this is the JSON data I get when I log the data on browser console:
[
{
"id": "11",
"hotelname": "Sheraton hotel",
"hoteladdress": "Abule Ikeja",
"state": "Lagos State",
"lga": "Ikeja",
"hotelphone": "65645545454",
"hotelwebsite": "",
"adminphone": "6565656565",
"adminemail": "mail#hotel.com",
"hotelemail": "",
"facilities": ",,",
"roomscategory": "Diplomatic",
"standardrate": "150000",
"leanrate": "",
"aboutHotel": "",
"requestStatus": "0",
"createdOn": "1424360902",
"updatedOn": "1424360902"
}
]
How do I successfully, get this JSON data into HTML. Something like this:
$('#myDiv').html(myData[key]["hotelname"]);
I tried this, but it's just giving me Undefined.
Any help is appreciated.
Use $.each() to iterate:
success: function (JSONObject) {
$.each(JSONObject, function(k,item){
$('#myDiv').html(item.hotelname);
});
}
var json = [
{
"id": "11",
"hotelname": "Sheraton hotel",
"hoteladdress": "Abule Ikeja",
"state": "Lagos State",
"lga": "Ikeja",
"hotelphone": "65645545454",
"hotelwebsite": "",
"adminphone": "6565656565",
"adminemail": "mail#hotel.com",
"hotelemail": "",
"facilities": ",,",
"roomscategory": "Diplomatic",
"standardrate": "150000",
"leanrate": "",
"aboutHotel": "",
"requestStatus": "0",
"createdOn": "1424360902",
"updatedOn": "1424360902"
}
]
$.each(json, function(i, item){
$('body').append(item.hotelname);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As per your error, it seems that you either you don't have a valid json or that is a json string. So before loopin you have to parse it:
success: function (JSONObject) {
var data = $.parseJSON(JSONObject); // parse it
$.each(data, function(k,item){
$('#myDiv').html(item.hotelname);
});
}
var myData = "";
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {
myData += JSONObject[key];
}
}
myData here is simply just a string. Hence the call myData[key]["hotelname"] will return undefined, because you're trying to access something that does not exist.
Why not just use the result as-is from the Ajax call?

parse a result from AJAX request

I have this ajax request:
var rootURL = "http://localhost/myapp/api/api.php";
$.ajax({
type: 'GET',
url: rootURL + '/favourites',
dataType: "json",
success: function(list) {
},
error: function(list) {
}
});
and the api.php makes a query to DB and the encoded result
echo '{"result": ' . json_encode($result) . '}';
is like this:
{
"result": [
{
"ID": "1",
"username": "username1",
"name": "name1",
"year": "year1"
},
{
"ID": "2",
"username": "username2",
"name": "name2",
"year": "year2"
}
]
}
Now how can I get and print the two rows of the JSON result list in success callback in Javascript?
I tried this:
var decoded = JSON.parse( lista );
but I receive an error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Thanks
You dont't need to parse, just you need to iterate the array inside the result.
do like this:
success: function(list) {
$.each(list.result,function(index,item){
console.log(item);
});
}
FIDDLE DEMO
Don't call JSON.parse. jQuery does that for you when you say dataType: "json". list is an object. So just access list.result, which contains the result array.
Also, your PHP shouldn't build the JSON by hand like that. It should do:
echo json_encode(array('result' => $result));

Parse JSON YQL Output with jQuery append to IDs

I have a YQL output JSON string at this URL: YQL JSON
I found some other
I am trying to understand why I cannot get certain items out of the JSON return. For example, using jQuery, if I want the first DIVs H1 I use:
$.ajax({
url:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.missoulaavalanche.org%2Fcurrent-advisory%2F%22%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22content%22%5D%2Fdiv%5B1%5D'&format=json",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc'
});
function cbfunc(data){
var id = data.query.results.div;
$('#table').append('<li>'+id.h1+'</li>');
$('#table').listview('refresh');
}
I have tried to get some info, say the img alt or img src, from the second div... div1 like so:
function cbfunc(data){
var id = data.query.results.div[1];
$('#table').append('<li>'+id.img.alt+'</li>');
$('#table').listview('refresh');
}
I keep getting Undefined or no results... What I am missing or not understanding about getting results from the yql JSON list?
EDIT: I read a post on the YQL Blog about Cache busting... So I am using their suggestion there.
EDIT 2: here is the JSON from the yql. I would like to get div img src for example, but am not getting a return or I get an object. I think it would be data.query.results.div1.img.src
I get data.query.results.div.h1 no problem:
cbfunc({
"query": {
"count": 1,
"created": "2012-03-28T15:36:28Z",
"lang": "en-US",
"results": {
"div": {
"id": "content",
"div": [
{
"class": "post-2491 post type-post status-publish format-standard hentry category-advisories",
"id": "post-2491",
"h1": "March 26, 2012 Avalanche Advisory",
"p": {
"class": "postmetadata alt",
"small": {
"br": [
null,
null
],
"a": {
"href": "http://www.missoulaavalanche.org/category/advisories/",
"rel": "category tag",
"title": "View all posts in Advisories",
"content": "Advisories"
},
"content": "This entry was posted on Monday, March 26th, 2012 at 6:55 am\n Categories: \n"
}
},
"div": [
{
"id": "danger_rating",
"a": {
"href": "http://www.missoulaavalanche.org/wp-content/themes/missoula-avalanche/images/ratings/avalanche_danger_scale.jpg",
"img": {
"alt": "Current Danger Rating is MODERATE",
"src": "http://www.missoulaavalanche.org/wp-content/themes/missoula-avalanche/images/ratings/moderate.gif"
}
}
},
{
The jsonp function option is just define the function name server uses for the wrapper for jsonp.
To access your data you need to do it in success callback of $.ajax. Your code above is missing the $ before .ajax
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.missoulaavalanche.org%2Fcurrent-advisory%2F%22%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22content%22%5D%2Fdiv%5B1%5D'&format=json",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc',
success: function(data) {
var results=data.query.results;
/* work with results object here*/
}
});
It's easier than you think if you use jQuery.getJSON.
Try this:
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.missoulaavalanche.org%2Fcurrent-advisory%2F%22%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22content%22%5D%2Fdiv%5B1%5D'&format=json",
function(data) {
var id = data.query.results.div;
$('#table').append('<li>'+id.h1+'</li>');
$('#table').listview('refresh');
}
);

Categories