On click I am trying to get data from JSON via an URL into a <div>.
My JSON returns a single id and content I am trying to get content into div #west-container.
Can someone tell me what I am doing wrong?
My JSON Found at the url = [{"id":"2","title":"Generic Overview","content":"This is content here"}]
$('#jqxTree').bind('select', function (event) {
var loadPages = jQuery.parseJSON(
jQuery.ajax({
url: 'university/article/3',
async: false,
dataType: 'json'
}).responseText
);
for(i=0; i < loadPages.length ; i++){
var current = loadPages;
$("#west-container").load(current.content);
}
});
You can try this one:
$('#jqxTree').bind('select', function (event) {
jQuery.ajax({
url: 'university/article/3',
async: false,
dataType: 'json',
success:function(data){
$.each(data, function(i, item){
$("#west-container").html(item.content);
}); //-----------------^^^^^^^^^^^^---This will fetch you the
} //--------------------------------content from json
}); //-------------------------"content":"This is content here"
});
use
$.ajax({
url: "url",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:json,
dataType:'text',
async: false,
}).done(function( data1 ) {
data=jq.parseJSON(data1);
});
in order to use the data, use "data.id, data.title" etc.
in order to push data to a div, use
$('#DivId').test(data.id);
$.getJSON( 'university/article/3', function(data) {
// Do stuff here
var oDiv = $( 'west-container' ).html( '' );
for( var i in data ) {
oDiv.append( data[i].content );
}
} );
Related
post and get works fine but json returns wrong value , or something is wrong with my php code.
$(function () {
$('#username').on('keypress',function () {
var input = $('#username').val();
if(input.length>=4){
$.ajax({
url:'registration_php.php',
type: 'POST',
data:{username:input},
success:function () {
$.getJSON('registration_php.php',function (text) {
alert(text.user);
});
}
});
}
});
});
success:function(result) {
var items = JSON.parse(result);
alert(items['user']);
}
pass the result directly to your reponse as an argument like this
you should specify a dataType: "json" in your ajax call
var postData = JSON.stringify({
username: 'value'
});
var request = $.ajax({
url: "registration_php.php",
method: "POST",
dataType: "json",
data: postData,
});
request.success(function( results ) {
console.log(results)
});
I have the following jQuery setInterval function to reload data at 30 second intervals using ajax from a php file. I am running 3 different ajax calls in order to get 3 bits of information. Is there a way to consolidate the 3 seperate ajax calls into one call? 2 of the calls have the php file return back json data from session, and the other call just returns a number to display the quantity of unread messages.
Here is the jQuery code I currently have:
setInterval(function(){
jQuery.ajax({ url: '/ajax-msgs.php?check=1', type: 'POST', dataType: 'json', cache: 'false', success: function(data) {
var msghtml = '';
jQuery.each(data, function() {
msghtml += '<li>' + this.msg_subject + '</li>';
});
jQuery("#msg-menu").html(msghtml);
}
});
jQuery.ajax({ url: '/ajax-msgs.php?check=2', type: 'POST', dataType: 'json', cache: 'false', success: function(data) {
jQuery.each(data, function() {
jQuery.jGrowl(this.msg_title, { life: 12000});
});
}
});
jQuery.ajax({ url: '/ajax-msgs.php?check=3', type: 'POST', dataType: 'json', cache: 'false', success: function(data) {
jQuery("#msg-count").text('87');
}
});
}, 30000);
And here is what the php file does:
if ($_GET['check']==1){
iMapFunction();
print_r(json_encode($_SESSION['message_overviews']));
} elseif ($_GET['check']==2){
iMapFunction();
print_r(json_encode($_SESSION['messages_new_notifications']));
unset($_SESSION['auth_messages_new_notifications']);
} elseif ($_GET['check']==3){
iMapFunction();
echo $_SESSION['messages_unread_count'];
}
our PHP could return all the thata in one call like this:
<?php
iMapFunction();
$response = array(
'message_overviews' => $_SESSION['message_overviews'],
'messages_new_notifications' => $_SESSION['messages_new_notifications'],
'messages_unread_count' => $_SESSION['messages_unread_count']
);
print_r(json_encode($response));
?>
And you can iterate on each data the same way you did before like this:
setInterval(function(){
jQuery.ajax({ url: '/ajax-msgs.php', dataType: 'json', cache: 'false', success: function(data) {
var message_overviews = data.message_overviews;
var messages_new_notifications = data.messages_new_notifications;
var messages_unread_count = data.messages_unread_count;
var msghtml = '';
jQuery.each(message_overviews, function() {
msghtml += '<li>' + this.msg_subject + '</li>';
});
jQuery("#msg-menu").html(msghtml);
jQuery.each(messages_new_notifications, function() {
jQuery.jGrowl(this.msg_title, { life: 12000});
});
jQuery("#msg-count").text(messages_unread_count);
}});
}, 30000);
Just make an endpoint that does all the actions in one call:
I don't know php but create an associative array and assign your data to that.
x = {};
x['message_overviews'] = $_SESSION['message_overviews'];
x['auth_messages'] = $_SESSION['auth_messages_new_notifications'];
x['messages_unread_count'] = $_SESSION['messages_unread_count'];
print_r(json_encode(x));
Then in your jquery response function you can access your data and do your actions:
function(data){
console.log(data.message_overviews);
console.log(data.auth_messages);
console.log(data.messages_unread_count);
}
This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??
Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try
As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.
Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code
I am trying to send multiple data arrays in my ajax save function.
I can do each array individually like data:hardwarePayload and it will work. If I do {hardware: hardwarePayload, service:servicePayload} I get very weird JSON output. that looks like:
hardware=%5B%7B%22hardwareName%22%3A%221%22%2C%22hardwareQuantity%22%3A%22%22%2C%22hardwareBYOD%22%3A%22%22%7D%5D&service=%5B%7B%22serviceName%22%3A%223%22%2C%22serviceQuantity%22%3A%22%22%7D%5D
I really need two arrays one hardware and one service so I can grab each one individually.
My code looks like this..
self.save = function (form) {
var hardwareModel = [];
var serviceModel = [];
ko.utils.arrayForEach(self.services(), function (service) {
serviceModel.push(ko.toJS(service));
});
ko.utils.arrayForEach(self.hardwares(), function (hardware) {
hardwareModel.push(ko.toJS(hardware));
});
//allModel.push({accountId: ko.toJS(account)});
var hardwarePayload = JSON.stringify(hardwareModel);
var servicePayload = JSON.stringify(serviceModel);
//alert(JSON.stringify(serviceModel) +JSON.stringify(allModel));
$.ajax({
url: '/orders/add',
type: 'post',
data: {hardware: hardwarePayload, service:servicePayload}, // data:hardwarePayload,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
};
You should try this
var hardwarePayload = hardwareModel;
var servicePayload = serviceModel;
var postData = {'hardware': hardwarePayload, 'service':servicePayload};
var postData = JSON.stringify(postData);
alert(postData);
$.ajax({
url: '/orders/add',
type: 'post',
data: postData,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
I think you'll be better off if you do NOT stringify your data:
$.ajax({
url: '/orders/add',
type: 'post',
data: {hardware: hardwareModel, service:serviceModel}, // data:hardwarePayload,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
(Note that I'm using the not stringified hardwareModel and serviceModel)
This way you can have jQuery handle the (json) data for the request.
I have a php program where I just test some sample data. I am getting error as missing ] after element list. How can I read this?
$dataDetailsList = array();
array_push($dataDetailsList, array('a' =>'1','b' =>'2','c' =>'3','d' =>'4','e' =>'5'));
echo json_encode(array("DataDetailsList"=>$dataDetailsList));
Then in my jQuery processor I am doing like this.
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = eval(" (" + data + ") ");
},
cache: false
});
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = data;
},
cache: false,
dataType: 'json' //data type that it will return
});
}
Don't use eval is evil.
Instead of this use:
JSON.parse(data); // not supported in IE7 and below
I think you need to try
dataType: 'json'
That is,
$.ajax({
url: 'live-server-data.php',
dataType: 'json',
success: function(data) {
var jsonData = data;
console.log(jsonData);
$.each(jsonData.DataDetailsList, function(key, val) {
var key = Object.keys(val)[0],
value = val[key];
console.log(key); // output: a, b, c ...
console.log(value); // output: 1, 2, 3,...
// alternative
for(var key in val) {
console.log(key);
console.log(val[key]);
}
});
},
cache: false
})
You should just set the dataType to json and jQuery will do the trick for you..
$.ajax({
url: 'live-server-data.php',
dataType: 'json', //Added dataType json
success: function(data) {
//Now data is a javascript object (JSON)
},
cache: false
});