ajax post success parse json - php

sorry for the long question. I am trying to ajax post to collect a contacts position history and then add the markers to the map.
The ajax post returns the positions data json encoded like:
[{"name":"Chris","data":{"user":"447967048843","data":[{"timestamp":1332840872,"longitude":-1.549517,"latitude":53.973174},{"timestamp":1332841510,"longitude":-1.444133,"latitude":53.997148}]},"contacts":null},{"name":"Jason","data":{"user":"447879896697","data":[{"timestamp":1332839836,"longitude":-1.566667,"latitude":53.978533},{"timestamp":1332840447,"longitude":-1.567654,"latitude":53.977927}]},"contacts":null}]
Here is the getHistory function which is called on form submit after the contact has been selected.
function getHistory() {
var contact = $("#contact").val()
var days = $("#days").val()
$.ajax({
type: 'post',
url: 'temp_history.php',
data: {contact: contact, days: days},
context: document.body,
beforeSend: function() {
},
success: function(succ){
var obj = jQuery.parseJSON(succ);
var divs="",tabs="",counts=0;
jQuery("#gMap").gmap3({
action: 'clear'});
jQuery(".marker").remove();
jQuery.each(obj,function(i,item){
tabs +=item.contacts;
if(item.data.latitude != null && item.data.longitude!=null)
{
addMarker(item.name, item.data.timestamp,item.data.latitude,item.data.longitude,item.data.user_id);
}
});
}
});
}
I think the problem is i need to nest the jQuery.each function but not sure how?
The addMarker function is:
function addMarker(name, timestamp, lati, longi, user_id) {
jQuery("#gMap").gmap3({
action: 'addMarkers',
markers:[
{lat:lati, lng:longi, data:name}
]
});
}
Thank you

You're right - your traversal of your JSON was incorrect, try this in your success handler:
success: function(data){
var json = jQuery.parseJSON(data); // If you're returing json, this shouldn't be required
var divs = "", tabs = "", counts = 0;
jQuery("#gMap").gmap3({ action: 'clear' });
jQuery(".marker").remove();
jQuery.each(json, function(i, item) {
var name = item.name;
var userId = item.data.user;
jQuery.each(item.data.data, function(i, nav) {
var ts = nav.timestamp;
var lat = nav.latitude;
var long = nav.longitude;
if (lat != null && long != null) {
addMarker(name, ts, lat, long, userId);
}
});
})
}
Also, it would be worth making the object names in your JSON more semantic, especially as you have data listed in multiple levels.

Related

External filter form with Datatable

I have a form that I want to send all fields to serverside using Datatables and filter the data.
I found how to send individual parameters using:
url: './demo2/contents/orden/get.php',
type: 'POST',
data: function(d) {
d.comercial = $("#comercial").val();
}
but how can I send the complete form, I assume it can be done using something similar:
url: './demo2/contents/orden/get.php',
type: 'POST',
data: function(d) {
var frm_data = $('#searchFrom').serializeArray();
$.each(frm_data, function(key, val) {
d[val.name] = val.value;
});
}
To get the parameters in get.php I am using
$comercial = $_REQUEST["comercial"];
If anybody needs help with this. I found the solution. You can get the forms post values using the same datatable get file without have to post again.. I wasnt aware of this.
here is the code:
$('#kt_search').on('click', function(e) {
e.preventDefault();
var frm_data = $('#searchFrom').serializeArray();
console.log(frm_data);
$.each(frm_data, function(key, val) {
myData[val.name] = val.value;
});
table.table().draw();
});
If you need to send an array because you have a field with multiple selection, you can use the following. Hope it helps somebody.
$('#kt_search').on('click', function(e) {
e.preventDefault();
var frm_data = $('#searchFrom').serializeArray();
//POST VALUES ARE SENT USING SAME GET FILE NO NEED TO POST AGAIN
var multiple = {};
var i = 0;
$.each(frm_data, function(key, val) {
var str = val.name;
//CHECK IF FIELD NAME FINISHES WITH MULTIPLE
if (str.match("_multiple")){
if (typeof multiple[str] == "undefined") {
multiple[str] = new Array();
i = 0;
}
multiple[str][i] = val.value;
i++;
myData[val.name] = multiple[str];
}else{
myData[val.name] = val.value;
}
});
table.table().draw();
});

Content fetch in main page from another page from database through ajax

I have written this code but it didn't work. I have searched so much but those code are not properly work. what should I do? I want to fetch data without refreshing whole page.
I have looked at this other question.
$(document).ready(function() {
$("#pair_form").submit(function(e) {
e.preventDefault();
var devicename = $("#devicename").val();
var id = $("#id").val();
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var ignition = $("#ignition").val();
var Arming = $("#Arming").val();
function showData() {
$.ajax({
url: 'http://example.com/ddd/cfg.php',
method: 'get',
dataType: 'text',
success: function(response) {
$('#result').html(response)
}
});
}
});
});

I want to send form and some text to another file with ajax or json or whatever. Currently it is not working

So I have an onclick function which sends a message to another php file which sends the message to the database. I want to send to the php file, the whole form and a specific chat_index value. So far I have:
$(".comin").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var item_id = this.id;
alert(item_id);
if($.get('sendcom.php?q=' + item_id, $('#comform').serialize())) {
var a = $(".comin").val();
alert(a);
document.getElementById(item_id).value = "";
//sent and cleared
}
}
});
post your data in json format,
$(".comin").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var chatData = {
q: item_id,
formData:$('#comform').serialize()
}
$.ajax({
url: 'sendcom.php',
type: 'post',
dataType: 'json',
data: chatData,
success: function (data) {
$('#target').html(data.msg);
}
});
}
});

Can't get values i need from json with ajax callback

From a datapicker i send 2 dates to a php.
I'm trying to print a group of value from json to use in a statistic.
$.ajax({
url: 'calctimestat.php',
method: 'POST',
data: {dateone:dateOne,datetwo:dateTwo},
success: function(data)
{
var obj = jQuery.parseJSON(data);
console.log(JSON.stringify(obj));
}
});
Ajax callback returns into log:
[{"dt":"2014-06-04","qt":"0"},{"dt":"2014-06-05","qt":"0"},{"dt":"2014-06-06","qt":"0"},{"dt":"2014-06-07","qt":"0"},{"dt":"2014-06-08","qt":"0"}]
I tried with:
var date = "dt"
console.log(JSON.stringify(obj.date));
var quantity = "qt"
console.log(JSON.stringify(obj.quantity));
But always returns undefined. I need to have something like this:
[0,0,0,0...]
and
[2014-06-04,2014-06-05,2014-06-06,2014-06-07...]
the author of the question clearly does not need an answer, but maybe the direction of its solution will help others.with this return, to get two arrays, as described in the requirement, it is enough to iterate through the values of objects in the array and get their values by key, decomposing them into the corresponding arrays.
/* IF Ajax callback data = [{"dt":"2014-06-04","qt":"0"},{"dt":"2014-06-05","qt":"0"},{"dt":"2014-06-06","qt":"0"},{"dt":"2014-06-07","qt":"0"},{"dt":"2014-06-08","qt":"0"}]
*/
$.ajax({
url: 'calctimestat.php',
method: 'POST',
data: {dateone:dateOne,datetwo:dateTwo},
success: function(data)
{
var obj = jQuery.parseJSON(data);
var result = [];
var result1 = [];
for(var i in obj)
{
result.push(obj[i]['qt']);
result1.push(obj[i]['dt']);
}
console.log(JSON.stringify(result));
console.log(JSON.stringify(result1));
}
});

JQuery ajax function works but can't return the variable correctly

I have a function runAjax that functions correctly. Unfortunately I am struggling to return the value I get from the ajax query.
The ajax function assigns the returned value inside "contents" or "error" xml tags to the variable "result".
If I alert the result variable inside the ajax function it alerts the correct value (i.e if the xml value inside contents is "published" it alerts published).
However if I alert the returned value from the runAjax function it alerts an object instead of the value of the internal variable "result" which in the above example is "published".
function runAjax (data_obj){
return $.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [
$("contents", xml).text()
];
}
alert(result); //alerts the correct string for example "published"
return result;
}
});
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
var result = runAjax({method: method_set, id: id_set});
alert(result); //alerts an object not published
});
Im sure it has something to do with the way I am returning the variable but I can't figure it out. Any input would be much appreciated.
Regards
Luke
UPDATE:
This is the revised code that works thanks to all the input from people below:
function runAjax (data_obj,callback){
$.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [
$("contents", xml).text()
];
}
if ( typeof(callback) == "function") {
callback(result);
}
}
});
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
runAjax({
method: method_set,
id: id_set
},
function(result){
$(user).html(result.join('')); //this is instead of alert(result);
}
);
});
According to the docs
The $.ajax() function returns the XMLHttpRequest object that it creates.
Any return value that you return from the success callback function is ignored.
You need to put the value in a variable defined in a wider scope than inside the callback function (global, or preferably inside an outer function).
var result;
$.ajax({
....
success : function(data) {
...
result = ...;
}
});
Or better yet: do whatever you want to do with the return value inside the success callback function, this will keep the asynchronous nature of the ajax call and means you don't need to wait for the call to come back.
Doing your processing in the success callback function means you know you have the results, if you put the value in a variable the variable may not be assigned a value yet by the time you want to use it.
In a comment to another answer on this page you say:
however I am calling the runAjax function from multiple other functions not just the one in my code example above, so I need the value returned rather than the runAjax function doing the html replacing
I would add an extra parameter to your runAjax function, which is another callback function that you can pass in different processing functions from the various functions.
function runAjax(data_obj, callback) {
$.ajax({
...
success : function(data) {
...
result = ...
...
if ( typeof(callback) == "function") {
callback(result);
}
}
});
}
Then you can call it like
runAjax({method: method_set, id: id_set},
function(result){
alert(result);
}
);
Then you can do your generic processing of the data in the success function, but the custom processing for each call in the callback function.
If you really need to wait for the call, you can create a synchronous ajax call by passing the async option:
$.ajax({
async:false,
....
Luke,
Basically, create a wrapper function for your $.ajax() call with a parameter for the callback portion (you could of course have parameters for any valid paramter in the ajax call. here's a quickie to demonstrate:
function runAjax (data_obj, callback){
$.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
if (data != null && callback !== null ) {
callback(data);
}
}
});
}
function callbackFunction (data) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [
$("contents", xml).text()
];
}
alert(result); //alerts the correct string for example "published"
// do your DOM updates etc here
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
runAjax({method: method_set, id: id_set}, callbackFunction);
});
hope this helps..
Luke,
I think you're assigning the retrun value at the wrong point in the function, you should really have a single exit point before the final curly brace. you're returning the result technically as a return value of the $.ajax() function (an XMHTTP object), NOT the parent method.
try this instead:
function runAjax (data_obj){
var returnValue;
$.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [
$("contents", xml).text()
];
}
alert(result); //alerts the correct string for example "published"
returnValue = result;
}
});
return returnValue;
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
var result = runAjax({method: method_set, id: id_set});
alert(result); //alerts an object not published
});
The reason that you can't get the result returned correctly is because of the asynchronous nature of AJAX (that's what the first 'A' stands for).
The call to runAjax() probably returns long before the AJAX operation completes and the 'success' handler is invoked. The runAjax() call returns a referenc to the XMLHttpRequest object that was used to invoke the AJAX communication. The return value from the success handler cannot be used by you directly, as it returned to the internal working of the $.ajax() code.
A suitable solution would depend on what you want to do with 'result' - I'm guessing that 'alert(result)' is only for illustration purposes.
Luke,
To further refine the answers provided by myself and Jim, considering that the result parsing bit is likely to be consistent for each of the different calls...
function runAjax (data_obj, callback){
$.ajax({
url:"/ajax.php",
dataType: "xml",
data: data_obj,
success: function(data) {
if (data != null && callback !== null ) {
// format result
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
var result;
if($("error",xml).text()){
result = [$("error",xml).text()];
} else{
result = [$("contents", xml).text()];
}
callback(result);
}
}
});
}
function callbackFunction (result) {
alert(result); //alerts the correct string for example "published"
// do your DOM updates etc here
}
$('ul.content li span.changeable').click(function(e){
e.preventDefault();
var method_set = $(this).parent().attr("class");
var id_set = $(this).parent().parent().find('li.id span').html();
var user = $(this);
runAjax({method: method_set, id: id_set}, callbackFunction);
});
You can handle the success of the ajax call as an event which keeps the good stuff of the async call including stuff based on the url you called.
$('ul.content li span.changeable').ajaxSuccess(function(e, xhr, settings) {
if (settings.url == '/ajax.php') {
$(this).text('Triggered ajaxSuccess handler.');
someglobalresultvariable = xhr.responseXML; // the xml of the response
$(this).text(someglobalresultvariable);
}
});
Here I make the wild assumption that you want to change the span content text based on the clicked item.
NOTE: I replaced the "triggered" text message and only show that as an example. You can decide how you wish to handle the result.
try removing [ and ]
if($("error",xml).text()){
result = $("error",xml).text();
} else{
result = $("contents", xml).text();
}

Categories