jQuery, ajax multiple checkboxes into $_POST array - php

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

Related

Multi select filter option for MySQL data using AJAX

I am learning JSON and AJAX and need help on this tutorial.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){ // create table get data from database
var tbl_body = ""; // table body
$.each(data, function() { // table data
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>"; // table row
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getEmployeeFilterOptions(){ // get filter options value
var opts = [];
$checkboxes.each(function(){ // this function select when radiobutton is clicked
if(this.checked){
opts.push(this.value); // get check box values
}
});
return opts;
}
function updateEmployees(opts){ // update the filter value using ajax
$.ajax({
type: "POST", // POST method
url: "search.php", // search. page send data using json
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:radio"); // check radio button is clicked
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions(); // update the database
updateEmployees(opts);
});
updateEmployees();
</script>
Here the results (from search.php) are showing in a table but I want all the data in a div. Please help me on this issue.

Form loaded via ajax wont append data to parent window

So I am basically creating a Restaurant Menu editor for their website. The issue I am having is when the click a category named Brunch, I load the file edit_cat.php via ajax onto the page. All data is passed correctly, but on success of the form being filled out I would like to post a success message on the parent window and am having no luck. Coincidentally, upon success the alert(data) does popup with the response.
edit_cat.php both handles the form submission and is the form
$(document).ready(function(){
$('.editBtn').on('click', function(e) {
e.preventDefault();
var $this = $(this),
id = $this.data('id'),
type = $this.data('type');
if (type == 'cat') {
data = "&cat=" + id;
$.ajax({
data: data,
type: 'POST',
url: 'edit_cat.php',
success: function(data) {
$('#contentLeft').html(data);
}
});
}
});
$('#contentLeft').on('click', 'input[type="submit"]', function(e) {
e.preventDefault();
var $this = $(this),
frm = $('#edit-cat-frm'),
id = $('form').data('id'),
name = $(frm).find('input[name="name"]').val(),
desc = $(frm).find('textarea[name="desc"]').val(),
send = $(frm).find('input[name="submit"]').val();
data = "&cat=" + id + "&name=" + name + "&desc=" + desc + "&submit=" + send;
$.ajax({
data: data,
type: 'POST',
url: 'edit_cat.php',
success: function(data) {
window.parent.$('.left-container-head').innerHtml(data);
}
});
});
});
Can you please try this as simply,
$('.left-container-head').html(data);
Try this:
$(".left-container-head", window.parent.document).html(data);

Ajax call returns nothing

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

How to give the value in data jquery?

I now am working with my project. I have the problem with the data. I have knowledge on jquery
$(document).ready(function(){
$("input[type='radio']").click(function(){
var price = $(this).val();
add_payment_value(price);
});
});
function add_payment_value(price){
// here you can use $.ajax function to add your 'price value' to your cart
$.ajax({
type: "POST",
url: "add_payment.php",
// file where you can add price to your database
data: "",
success: function(){} // return something on success
});
}
I have 4 values which is stored in radio buttons ordered 4, 6.5, 8, 11. My question is how to write the values in data and var price = $(this).val();? Can anyone fill this? I gave some value but that is not working.
Change the add_payment_value function to accept a name and then uaw the code below:
$(document).ready(function(){
$("input[type='radio']").click(function(){
var price = $(this).attr("value");
var name = $(this).attr("name");
add_payment_value(price, name);
});
});
function add_payment_value(price, name){
// here you can use $.ajax function to add your 'price value' to your cart
$.ajax({
type: "POST",
url: "add_payment.php", // file where you can add price to your database
data: name + "=" + price,
success: function(){} // return something on success
});
}
Another alternative is to format the data string in the click handler and send it to add_payment_value function
$(document).ready(function(){
$("input[type='radio']").click(function(){
var price = $(this).attr("value");
var name = $(this).attr("name");
add_payment_value(name + "=" + price);
});
});
function add_payment_value(priceData){
// here you can use $.ajax function to add your 'price value' to your cart
$.ajax({
type: "POST",
url: "add_payment.php", // file where you can add price to your database
data: priceData,
success: function(){} // return something on success
});
}
use radio button id like ("#rb1").value instead of this.

Rebind dymanically created forms after jQuery ajax response

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??

Categories