The question I am asking is a basic question because I am new in json and ajax.
so I have a json data of name , task , date and status I am getting data through ajax but it is not showing in on my page.
my ajax code is this:
$(document).ready(function(e) {
// Using the core $.ajax() method
$.ajax({
url: "getdata.php",
type: "GET",
dataType : "json",
success: function( json ) {
$( "<h1/>" ).text( json.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( json.task ).appendTo( "body" );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
this is my json data:
[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
I don't know why It is not appending html data but it is showing complete alert.
I have added fiddle even if it is not working.
Fiddle
Ok, i see you actually getting results so i guess you do have a success. You do have a flaw though. You are trying to access properties directly, but your json is an array of objects and not an object.
You need to do a foreach itteration.
json.forEach(function (entry) {
$( "<h1/>" ).text( entry.name ).appendTo( "body" );
$( "<div class=\"content\"/>").html( entry.task ).appendTo( "body" );
});
Edit Your Json like
{
"jsontext":[
{"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
{"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
{"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
{"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]
}
and the ajax code should be as
$.ajax({
url: '/getdata.txt',
complete: function (data) {
if (data.responseText != "") {
var NewTxt = data.responseText;
NewTxt = NewTxt.replace(/\n/g, "");
NewTxt = NewTxt.replace(/\s/g, "");
obj = JSON.parse(NewTxt);
var NewStr = "";
for (var i = 0; i < obj.jsontext.length; i++) {
NewStr += obj.jsontext[i].name + "<br/>" + obj.jsontext[i].task + "<br/>" + obj.jsontext[i].date + "<br/>" + obj.jsontext[i].status + "<br/><br/>";
}
document.getElementById("demo").innerHTML = NewStr;
}
}
});
and the HTML as:
<div id="demo"></div>
Related
I'm trying to loop through some JSON but once it gets to the values that are url's, they are returning as undefined. Here's a simplified example of my JS
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data){
$("ul.mapList").append(
'<li id="store-' + data.restaurant + '">'+
'<div class="singleLocation">' +
'<button class="directions">DIRECTIONS</button>' +
'Restaurant Details' +
'</div>' +
'</div></li>'
)
})
});
And my JSON:
{ "restaurant":31, "restaurantName":"Shenandoah", "address":"19075 IH 45 S Suite 480", "city":"Shenandoah", "state":"TX", "zip":77385, "phone":"(936) 271-9217", "directions":"https://www.google.com/maps/dir//Pei+Wei,+19075+I-45+%23480,+Shenandoah,+TX+77385/#30.1826863,-95.4533763,17z/", "url":"/texas/31-shenandoah"}
The two keys at the end, "directions" and "url" are the only ones that return as undefined. What am I doing wrong?
Problem is here:
$.getJSON("https:../houston-locations.js", function(data){
$.each(data, function(i, data) {
You are overwriting variable data in function(i, data), consider to change it to value or something else.
Use this code:
$.getJSON( "ajax/ejemplo.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "" + val + "" );
});
$( "", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
$.getJSON("https:../houston-locations.js",function(data){
console.log(data);
$.each(data, function( key, value ){
console.log(data.directions);
console.log(data.url);
});
});
the right use of $.getSOn is as above
I found the solution to be something so simple.. It was a cache issue so the new JSON data wasn't being loaded. I did however change the overwriting 'data' values. Thanks everyone!
I've created some sample code below. You can delete items simply by clicking the text you want to delete (or the li element).
When you look at the network tab when you delete, you get back both a 204 and 200 response. Why are there two? I'm only making 1 call.
Where the heck is the request method "OPTIONS" coming from?
//Cache DOM
var $content = $( 'ul' );
var $name = $( '#name' );
var $bike = $( '#bike' );
var $addButton = $( '#add-item' );
var $liElems = $( 'li' );
//Functions
$( function () {
function addItem( data ) {
$content.append( '<li id="' + data.id + '">' + data.name + ' likes ' + data.bike + '</li>' );
}
$.ajax( {
type: 'GET',
url: 'http://rest.learncode.academy/api/sjm/bikes',
success: function( response ) {
$.each( response, function( index, bikes ) {
addItem( bikes );
});
},
error: function( ) {
console.log ( 'error loading orders' );
}
});
$addButton.on( 'click', function(){
var data = {
name: $name.val(),
bike: $bike.val()
};
$.ajax( {
type: 'POST',
url: 'http://rest.learncode.academy/api/sjm/bikes',
data: data,
success: function( response ) {
addItem( response );
},
error: function( ) {
console.log( 'error while saving' );
}
});
});
$content.delegate( 'li', 'click', function ( ) {
var id = $( this ).attr( 'id' );
var $this = $( this );
console.log ( 'delete ' + id);
$.ajax({
type: 'DELETE',
url: 'http://rest.learncode.academy/api/sjm/bikes/' + id,
success: function( response ){
$this.fadeOut( 300, function ( ) {
remove( );
});
},
error: function( ){
console.log( 'error deleting data' );
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<section>
name <input type="text" id="name">
bike <input type="text" id="bike">
<button id="add-item">add data</button>
</section>
<ul></ul>
</div>
When you try to send a XMLHttpRequest to a different domain than the page is hosted, you are violating the same-origin policy. However, this situation became somewhat common, many technics are introduced.
CORS is one of them.
In short, server that you are sending the DELETE request allows cross domain requests. In the process, there should be a preflight call and that is the HTTP OPTION call.
So, you are having two responses for the OPTION and DELETE call.
see MDN page for CORS.
I'm trying to execute the remote code completion example in Jquery Mobile using the following url: http://demos.jquerymobile.com/1.4.0/listview-autocomplete-remote/
I use latest PhoneGap with jquery mobile version 1.4.3
the auto complete javascript code:
$(function() {
$( "#drink_brand_autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://myalcoholist.com/drink-management/drink/drink-brand-autocomplete",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
console.log("response");
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
console.log(html);
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
in chrome developer console i can see that the ajax call is being executed fine and the server returns a json array.
the .then() is not being executed, no ideas why.
i tried .done() instead but i got the same results.
i don't get any javascript errors.
any ideas?
I am working on Dynamic Web Project in Eclipse and using HTML 5 and Javascript as well.
I could manage to parse JSON file that is saved locally in my system though the code below:
$.getJSON( "/Users/Documents/workspace2/sample.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Let's suppose this is the JSON file:
{"resource":"A","literals":["B","C","D"]}
My question is: Is there any possibility to have an array of strings to store these elements that are inside the JSON file after parsing. I am quite new to jQuery and couldn't really manage to see these elements stored in an array of strings, for example. Could anyone help me with this issue please.
Try this way :
jsonFile.json
{
"resource":"A",
"literals":["B","C","D"]
}
myFile.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$.getJSON( "jsonFile.json", function( data ) {
var items = [];
$.each( data, function( key, val1 ) {
items.push( "<li><a href=#'" + key + "'>" + val1 +"</a></li>");
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
</script>
</head>
<body>
//result will be displayed here
</body>
</html>
Output :
var abc = JSON.stringify({"resource":"A","literals":["B","C","D"]});
var ab = JSON.parse(abc);
var arr=$.map(ab, function(value, index) {
return [value];
});
Hope it helps.
I have a web page which fill's form data based on some json data sent from a web service. Once the form is ready to be submitted a function is called which takes all the form data turns it into a xml-formatted string then parses the xml so it becomes a valid xml object. This is where the problem happens, once this data is turned into an xml I would like to post this data back to the web service so the database can be updated. However using the $.ajax() function to post this data, neither the success nor error function within are ever called. This lead's me to believe the ajax function is never being called or run. Below are the code snippets:
submit button for form:
<input type="submit" name="submitbutton" id="submitbutton" value="Submit" onclick="postData()"/>
postData function:
function postData()
{
//gathering all inputs
var cb = document.getElementById('paymentList');
var selected_cb = cb.options[cb.selectedIndex].text;
var pguid = getParameterByName('guid');
var xmlString = '<string>' +
addField('approver', $('#approver').val()) +
addField('companyName', $('#companyName').val()) +
addField('emailAddress', $('#emailaddress').val()) +
addField('address1', $('#address1').val()) +
addField('address2', $('#address2').val()) +
addField('city', $('#city').val()) +
addField('province', $('#province').val()) +
addField('country', $('#country').val()) +
addField('postalCode', $('#postalcode').val()) +
addField('phoneNumber', $('#phone').val()) +
addField('paymentMethod', selected_cb);
//gathering all table data now
xmlString+='<contractData>';
$('#table tbody tr:has(img[src="images/checkmark.png"])').each(function() {
xmlString += '<contract>' + addField('vendorPart', $('td:eq(1)', this).text()) +
addField('description', $('td:eq(2)', this).text()) +
addField('price', $('td:eq(3)', this).text()) +
addField('quantity', $('td:eq(4) input', this).val()) + '</contract>';
});
xmlString += '</contractData></string>';
//hard coded var for purpose of this example, as web service name will be
var properid = 'somedata';
xmlDoc = $.parseXML( xmlString );
$xml = $( xmlDoc );
//this function I believe is never run as neither alerts below are posted
$.ajax({
type: "POST",
url: "http://www.webservice.com/service.asmx/sendMeMyData",
data: {properdata:properid, xml: $xml},
dataType: "text",
success: function() {
alert("posted");
},
error: function ()
{
alert("error");
}
});
}
addField function (just so you know what it does when it's called in postData()):
function addField(name, value) { // Add a single element and value
value = value.replace(/&/g, '&').replace(/</g,'<').replace(/>/g,'>');
return '<' + name + '>' + value + '</' + name + '>';
}