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();
});
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)
}
});
}
});
});
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);
}
});
}
});
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));
}
});
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();
}