I have a table TableElements and a Javascript valiable jsonData.
I want to reload TableElements' dataTable using the reload() method but without success.
The goal is to add a row to the table, inserting it into the database. This is the code I used so far
$.ajax({
url: 'AddRow.php',
type: 'POST',
data: {
CatProg: catProg,
CatUser: catUser,
CatPass: catPass,
CatInUso: catInUso,
CatDesc: catDesc,
CatUltimo: catUltimo,
CatDat: catDat
},
dataType: "text",
success: function(result){
// draw table again
var table = document.getElementById('TableElements');
table.remove();
var tableContainer = document.getElementById('tableContainer');
tableContainer.innerHTML = result;
jsonData = GetJsonFromTable(); // it works
$('#TableElements').DataTable({ ajax: 'data.json' }).reload(); //?? how to put 'jsonData' here?
},
error: function(){
alert("Request did not succeed. Reload and try again.");
}
});
}
This is what jsonData is holding:
[
{
"Aggiungi": "Modifica Elimina",
"CatProg": "1",
"CatUser": "user1",
"CatPass": "user1pass1",
"CatInUso": "Y",
"CatDesc": "desc",
"CatUltimo": "1",
"CatDat": "12-12-2001"
},
{
"Aggiungi": "Modifica Elimina",
"CatProg": "2",
"CatUser": "admin",
"CatPass": "admin",
"CatInUso": "N",
"CatDesc": "aaa",
"CatUltimo": "1",
"CatDat": "01-01-1999"
}
]
Related
I am trying to write some JSON data to a div with JQuery:
var obj = JSON.parse(data);
$('#container').html(obj.services.service[0].code);
But I get an error saying there is a Syntax error in my DOCTYPE:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
I read in other posts that this could be because of quotation marks around the JSON object. I have tried to add different quotes around the JSON object but with no luck, eg: var obj = JSON.parse("'" + data + "'");
I am not sure how to tackle this one. Can anyone point me in the right direction?
Thanks
The JSON data looks 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": [
{
AJAX call:
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'AusPostDomestic.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
//console.log(data);
var obj = JSON.parse(data);
$('#auspostresult').html(obj.services.service[0].code);
}
You have alreadyb added datatype as json , no need to parse it again. So remove line var obj = JSON.parse(data); from your success callback function.
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'AusPostDomestic.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function(obj) {
//console.log(data);
$('#auspostresult').html(obj.services.service[0].code);
}
});
Api Doc : http://api.jquery.com/jquery.ajax/
I am trying to build a single page app that uses $.ajax.
Here is the json data:
{
"restaurants": [
{
"id": 1,
"name": "Denny's",
"location": "Los Angeles",
"cuisine": "American",
"image_url": "http://www.coupons4utah.com/wp-content/uploads/2012/06/dennys-breakfast.jpg"
}
],
"items": [
{
"id": 1,
"restaurantId": 1,
"name": "hamburger",
"price": 10,
"order_count": 0,
"image_url": "http://kleberly.com/data_images/wallpapers/7/277047-hamburger.jpg"
}
],
"public": []
}
I have three buttons on my welcome screen and on of them is "Los Angeles". When I click "Los Angeles", I want it to take me to a page with only results with restaurants from that location. Every time I click it gets me nowhere. I'm stuck and been trying to code my way to make it work for a awhile. I am looking for a solution that will lead me into the right direction. Thanks!
var $body = $("body")
var $losAngeles = $('#los_angeles')
$losAngeles.on('click',function(e){
e.preventDefault();
for (i = 0; i < data.length; i++){
var location = data[i].location;
$.ajax({
url: "/restaurants/:location",
type: "GET",
dataType: 'json',
data:[{location: location}],
success: function(data) {
$.each(data[i].location, function(i, location){
console.log(data[i].location)
})
}
})
}
})
})
I have also tried coming up with this:
$.ajax({
url: '/restaurants/:location',
type: 'GET',
data: [{location: location}],
dataType: 'json',
}).done(function(data){
for ( var i = 0; i < data.length; i++){
var location = data[i].location
if (location === "Los Angeles"){
var name = data[i].name;
var $LA = $('#LA');
$LA.append('<li>' + name + '</li>' )
}
}
})
})
})
Still nothing.
$.ajax({
url: "/restaurants/location", //changed
type: "GET",
dataType: 'json',
data:[{location: location}],
success: function(data) {
$.each(data.restaurants, function(i, location){ //changed
console.log(data.restaurants[i].location); //changed
})
}
})
Also remember not to use ajax calls in loop. If multiple ajax calls are needed use .then jQuery API.
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?
I have a set of JSON data that are displayed using datatables. In one of the columns, I add a button and a text box only if the value in that column and another column meets a certain condition. this is the bit of code I used to do this:
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<form><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert" onclick="<get all items for that row and POST to a URL>"></form>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
});
This works fine by adding a button and text in the cell. What I am looking to achieve is, when any of the button is been clicked, it should POST all the values for that row including what is typed in the text box to a URL which has another function that would extract those details and update the database and send back the refreshed data. I am new to datatables and jquery, any guide would be highly appreciated.
Have made some changes to the code, instead of form you can use div.
$(document).ready(function (){
var alertTable = $('#alert-table').DataTable({
"jQueryUI": true,
"order": [ 3, 'desc' ],
"columns": [
{ "data": "source", "visible": false },
{ "data": "host" },
{ "data": "priority" },
{ "data": "ack", "render": function( data, type, row ) {
if (row.ack == "0" && row.priority > "2") {
return '<div><input class="ackname" type="text" value="Enter your name"><input class="ackbutton" type="button" value="Ack Alert"></div>';
}
return data;
}
},
],
"language": {
"emptyTable": "No Alerts Available in Table"
}
});
$(document).on("click",".ackbutton",function() {
var currentIndex = $(this).parent().parent().index();
var rowData = alertTable.row( index ).data();
//extract the textbox value
var TextboxValue = $(this).siblings(".ackname").val();
var objToSave = {}; //Create the object as per the requirement
//Add the textbox value also to same object and send to server
objToSave["TextValue"] = TextboxValue;
$.ajax({
url: "url to another page"
data: JSON.stringify({dataForSave : objToSave}),
type: "POST",dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(datas) {
//Your success Code
},
error: function(error) {
alert(error.responseText);
}
});
});
});
Since both the pages are in same project, you can also do it using single ajax, passing all the values to server at once and then calling the other page internally from server and passing in the values using query string.
This is not a running code, rather to give you a basic idea on how to proceed.
Hope this helps :)
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));