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();
});
Related
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 am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery
I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
$("#records").on('click', ".update", function() {
var data = '?'+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data: data,
success: function(response) {
console.log(response);
}
});
});
Thanks in advance.
For reference below is the code that generates the table.
// Function to make datagrid
function getRecords() {
$.getJSON("viewcustomers.php", function(data) {
var items = [];
var xTd = '';
var xTr = '';
$.each(data, function(key, val) {
var c = 0;
var id = 0;
$.each(val, function(key1, val1) {
if (c == 0)
{
id = val1;
}
c++;
xTd += '<td>' + val1 + '</td>';
});
xTd += '<td>Edit</td>';
xTd += '<td>Delete</td>';
xTr = '<tr>' + xTd + '</tr>';
items.push(xTr);
xTd = '';
xTr = '';
});
$("#records").append(items);
});
}
Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
* Fetch single row for the purpose of update / delete.
*/
if(isset($_GET['update'])){
$customer = new Customers;
$Id = $_GET['update'];
$customer_single = $customer->View_Single_Customer($Id);
echo json_encode($customer_single);
unset($customer);
}
This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
var my_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php",
data : {id : my_id},
success: function(response) {
console.log(response);
}
});
});
Or do it like this:
$("#records").on('click', ".update", function() {
var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
$.ajax({
type: "GET",
url: "viewcustomers.php" + param,
/* remove the data attribute */
success: function(response) {
console.log(response);
}
});
});
Modify it as
$("#records").on('click', ".update", function() {
var request = '?id='+ $(this).attr('id');
$.ajax({
type: "GET",
url: "viewcustomers.php" + request,
success: function(response) {
console.log(response);
}
});
});
I'm trying to send $_POST data to another page to add sessions for a simple shopping cart.
I have a multiple forms within a PHP while loop each with multiple checkboxes, everything works apart from the checkboxes.
My question is how do I change this piece of code to change "item_extras" into an array?
if(this.checked) item_extras = $(this).val();
I have tried the following but, this just creates one line with all the values instead of another row within the array. If this is too confusing I could create a sample if it helps.
if(this.checked) item_extras += $(this).val();
$('form[id^="add_item_form"]').on('submit', function(){
//alert("On Click Works");
event.preventDefault();
addItem($(this));
});
function addItem(ele) {
//alert("I'm in the addItem Function");
var item_id = ele.parent().parent().find("input[name=item_id]").val(); // get item id
var item_name = ele.parent().parent().find("input[name=item_name]").val(); // get item name
var item_options = ele.parent().parent().find('#options').val(); // get selected option
var item_extras = "";
$item_extras = ele.parent().parent().find('input[name^="extra"]'); // find all extras
$item_extras.each(function() {
if(this.checked) item_extras = $(this).val(); // how do i make this into an array???
});
alert("BEFORE AJAX");
var dataString = 'item_id=' + item_id + '&item_name=' + item_name + '&item_options=' + item_options + '&item_extras[]=' + item_extras;
alert(dataString);
$.ajax({
type: "POST",
cache: false,
url: "includes/cart.php",
data: dataString,
success: function () {
$.ajax({
url: 'includes/cart.php',
success: function(data) {
$('#cart').html(data);
alert("AJAX SUCCESS");
}
});
}
});
return false;
}
you can use serialize method. Form.serialize()
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var data = $(this).serialize();
});
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.