How to Pass Multiple CheckBox values through AJAX and process them?| - php

Good evening guys,
I'm trying to pass multiple checkbox values through AJAX and process them with a external .php script. Goal: delete multiple rows using checkboxes without refreshing the page.
Please assist me with passing the selected checkboxes into the datastring and putting them in the mysql command in the external .php file. This is the code so far:
The checkboxes:
<form name="frmMain" id="myForm" method="post" OnSubmit="return onDelete();">
<input class="checkbox_button_del" type="submit" id="buttondel" value="Delete" /> // submit to ajax
<input type="checkbox" class="cb-element" name="chkDel[]" id="chkDel<?=$i;?>" value="' .($id). '">
<input type="hidden" name="hdnCount" value="<?=$i;?>">
</form>
The AJAX:
$(function () {
$(".checkbox_button_del").click(function () {
var id = $(this).attr("id");
var dataString = 'id=' + id; //pass checkbox ids somehow
var parent = $(this).parents('tr:first');
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: dataString,
cache: false,
success: function () {
parent.fadeOut('300', function () {
$(this).remove();
});
$("#display").load("display.php")
}
});
return false;
});
});
The delete script:
// receive checkbox ids from ajax and delete rows
for($i=0;$i<count($_POST["chkDel"]);$i++)
{
if($_POST["chkDel"][$i] != "")
{
$strSQL = "DELETE FROM players ";
$strSQL .="WHERE id = '".$_POST["chkDel"][$i]."' ";
$objQuery = mysql_query($strSQL);
}
}

You can do this by putting all the checkboxes in a form. And then add the following line in your function:
datastring = $('#myform').serialize();

jQuery has this functionality built-in.
See: http://api.jquery.com/serialize/

Related

I need to save the state of the toggle in database

I am using jquery to get the state of the toggle, I want to send that variable to my controller using twig, this is what I had done
<form method="post" enctype="multipart/form-data">
Sync: <br><div class="toggle-switch toggle-switch--green">
<input type="checkbox" class="toggle-switch__checkbox" id="togBtn" value='{{switchstatus}}' name = "sync">
<i class="toggle-switch__helper"></i></div><br>
<input type="submit" value="Update">
In Jquery
var switchStatus = false;
$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
switchStatus = $(this).is(':checked');
}
else {
switchStatus = $(this).is(':checked');
}
console.log(switchStatus);
$.ajax({
type: "POST",
url: 'name.html.twig',
data: switchStatus
});
});
I am getting value as empty
How do I pass my value of switchStatus in jquery to value option in twig HTML?
You need to send information to the PHP script via jQuery AJAX, the PHP script to sanitize user input/ do user check ups and then save the information into the database.

How to get value from checkbox and pass to PHP Page with AJAX

i am newbie in jquery and ajax programming. I have searched the answer about getting value from checkbox and pass it to PHP Page with AJAX, but it didn't work for me. Maybe someone can help me to get value from checkbox and pass to PHP Page so i can insert it to database.
This is my checkbox code in HTML
<fieldset data-role="controlgroup" id="pilihtambahan" style="margin-top: 5px;">
</fieldset>
$.ajax({
url: host+'/skripsi3/phpmobile/kategori.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
$("#pilihkategori").append('<input type="radio" name="radiokategori" class="required" id="'+item.kategori+'" value="'+item.kategori+'" required><label for="'+item.kategori+'">'+item.kategori+'</label>').trigger("create");
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
and this my html code to pass checkbox and other value to PHP Page
$("#simpansewa").click(function() {
var checkValues = $('input[name=cektambah]:checked').map(function()
{
return $(this).val();
}).get();
var k = $("input[name=radiokategori]:checked").val();
var u = user;
var g = getacara;
var b = $('#brandorder').val();
var d = $('#deskorder').val();
var s = $('#sosmedorder').val();
var t = $('#tambahcat').val();
dt = {user:u,acara:g,brand:b,desk:d,sosmed:s,kat:k,tambah:t,barangsewa:checkValues};
$.ajax({
type: "GET",
url: host+'/skripsi3/phpmobile/preorder.php',
data: dt,
success: function (data){
alert('Data Pemesanan Anda Telah Masuk');
window.location="statustransaksi.html";
},
error: function (e) {
alert('Fail');
}
});
});
this is my preorder.php
<?php
session_start();
include "config.php";
$idtenant = $_GET["user"];
$idacara = $_GET["acara"];
$namabrand = $_GET["brand"];
$deskbrand = $_GET["desk"];
$sosmed = $_GET["sosmed"];
$tambahcat = $_GET["tambah"];
$kategori = $_GET["kat"];
date_default_timezone_set('Asia/Jakarta');
$tanggal = date("d M Y G:i");
$statusbayar = "belumbayar";
$sewa=$_GET['barangsewa'];
$query="INSERT INTO `preorder`(`namaorder`, `sosorder`, `deskorder`, `catatan`, `kategori`, `id_tenant`, `id_acara`, `statuspesanan`, `tanggal`,`statusbayar`,`tambahanbarang`) VALUES ('$namabrand','$sosmed','$deskbrand','$tambahcat','$kategori','$idtenant','$idacara','Waiting','$tanggal','$statusbayar','$sewa')";
$result = mysql_query($query);
?>
Have a nice day!!
create one form and passed it with the use of jQuery serialize() function. This function is get all the data related with the form.
HTML Code
<form id="test">
<input type="radio" class="required" id="item1" name="item" value="1"> One
<input type="radio" class="required" id="item2" name="item" value="2"> Two
<button type="button" id="btn" > Click Me </button>
</button>
</button>
</form>
Javascript
$('#btn').click(function(){
var data = $( "#test" ).serialize()
});
All the data of the test form is assigned to the data variable. Now you can able to pass data variable to the php page with the ajax.

Processing Jquery Post with PHP

I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.

JQuery's ajax post request does not work as it's supposed to be

The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/

Send multiple checkbox data to PHP via jQuery ajax()

I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;

Categories