Send multiple checkbox data to PHP via jQuery ajax() - php

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;

Related

Multiple AJAX forms on the same page?

I am struggling to have multiple AJAX submitted forms on the same php page. I can get it to work with one, but when I add more, it just uses the first form all the time.
I have tried to make it unique but not sure exactly how to do this.
My code is below, if someone could please assist that would be fantastic.
I have looked at similar questions and answers on this site but can't seem to fathom how to make it work for mine.
The form should submit when the checkbox is checked or unchecked.
Thanks very much in advance for all your help.
Martyn.
HTML form
<form id="search_form" method="post">
<input readonly type="text" name="id" value=<?php echo $row1[0];?>>
<input readonly type="text" name="student" value=<?php echo $row1[1];?>>
<input readonly type="text" name="addedby" value=<?php echo $_SESSION['username'];?>>
<input readonly type="text" name="register" value="monday_morning">
<input <?php if($row1[4] == "Yes"){echo "checked";}?> type="checkbox" name="box" value="Yes">
</form>
Script
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function () {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $("#search_form").serialize(),
success: function (data) {
}
});
return false;
});
</script>
Try this
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function (event) {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $($(event.target).parent()).serialize(),
success: function (data) {
}
});
return false;
});
</script>
event.target returns the clicked checkbox.
parent() function returns the form you need to submit. This way you don't need to have unique form id.

How to pass the array value to PHP using AJAX?

I am trying to submit data to the database using AJAX. I have one array and I have to pass the value of the array to PHP using AJAX to display all the related records.
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
AJAX
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
//alert(response);
}
});
});
});
</script>
PHP
$sql='SELECT Name, Email FROM request WHERE Id IN (' .( is_array( $_POST['compare_id'] ) ? implode( ',', $_POST['compare_id']) : $_POST['compare_id'] ).')';
$records = array();
$query=$conn->query($sql);
if ($query->num_rows > 0) {
while($row=$query->fetch_assoc()){
$records[]=$row;
}
}
echo json_encode($records);exit();
HTML
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
JS
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
}
});
});
});
</script>
PHP
var_dump($_POST['compare_id']);
// it is already an array of ids. You can do whatever you want with it.
change your script as below. Your output is in array so you cant add it in div directly
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'action.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html();
for(data in response) //loop over your data
{
$('#response').append(response[data].Email); //add email
}
//alert(response);
}
});
});
});
</script>
There are errors in your code. A good way to debug this is to print_r your POST value in your php script.
First $_POST["All"] does not exist. It is all. (php)
Second, you send a GET request not a POST one. (jQuery)
Third, format your date into json. A good way to do this is to create a variable right after compare_id.push, it's more readable, as so :
var json_data = {"my_array" : [1,2, "bonjour", 4]};
Your problem is mostly related to "how to debug". I think you should print what's happening along the way to figure out what's happening.

how to checkbox value stored array when click checkbox using ajax

HTML
<input type="checkbox" name=options[cid]" value='1'
onChange="chkdeptCount(this.value)" class="test">
<input type="checkbox" name=options[cid]" value='2'
onChange="chkdeptCount(this.value)" class="test">
jquery:
function chkdeptCount(val){
$.ajax({ url: '../ajax/AjaxCall.php',
data: {Action:'IMPLODEARRAY',arrVal: val},
type: 'post',
success: function(output) {
alert(output);
$('.result').html(output);
}
});
}
PHP:
if($_POST['Action']=='IMPLODEARRAY'){
$arr_val[] = $_POST['arrVal'];
print_r($arr_val);
}
When I run this code does not return array value. It returns a single value WHY?
Note that, you are missing the quote here name=options[cid]".
And you are using onChange="chkdeptCount(this.value)" event with current value this, this will only return one value at once.
This is very basic Example:
HTML:
<form method="post" id="formID" action="">
<input type="hidden" name="Action" value="IMPLODEARRAY">
<input type="checkbox" name="options[cid]" value='1' class="test">
<input type="checkbox" name="options[cid]" value='2' class="test">
<input type="submit" name="submit" value="Submit" id="SubmitButton">
</form>
AJAX:
<script type="text/javascript">
$(document).ready(function(){
$("#SubmitButton").click(function(){ // when submit button press
var data = $("#formID").serialize(); // get all form input in serialize()
$.ajax({
url: YourURL, // add your url here
type: "POST", // your method
data: data, // your form data
dataType: "json", // you can use json/html type
success: function(response) {
console.log(response); // your response
},
beforeSend: function()
{
// if you want to display any loading message
}
}); // JQUERY Native Ajax End
return false;
});
});
</script>
PHP:
<?php
if(count($_POST) > 0){ // if you have some value in AJAX request
if($_POST['Action'] == 'IMPLODEARRAY'){ // your condition
print_r($_POST['options']); // get all checkbox value.
}
}
?>
Few more example will help you to understand, you can you use: Submitting HTML form using Jquery AJAX |
jQuery AJAX submit form

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.

onclick form send via ajax no page refresh

I've been racking my brains for days looking at examples and trying out different things to try and get my form to submit with Ajax without a page refresh. And Its not even sending the data now.. I don't know what I'm doing wrong..Can someone run through my ajax and form please.
Toid is the users id and newmsg is the text in which the user submits. The two values get sent to the insert.php page.
I would really appreate the help. I'm new to Ajax, and I look at some of it and don't have a clue. If I finally got it working, It may help me realize what I've done wrong. I am looking up tutorials and watching videos..but it can be very time consuming for something that would be simple to someone in the know on here. It maybe that I've got the wrong idea on the ajax and it makes no sense at all, sorry about that.
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
homestatus()
event.preventDefault();
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
});
return false;
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
</div>
</form>
INSERT.PHP
$user1_id=$_SESSION['id'];
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&isset($_POST['toid'])){
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
}else{
rawfeeds_user_core::create_streamitem("3",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
Try using firebug to identify bugs in your code. It's a really good companion for developing javascript. Nearly all of your bugs led to error messages in the firebug console.
You had several errors in your code, here is the corrected version:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){alert('success');}
});
});
});
And here the corrected html:
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
Actually onsubmit event has to be used with form so instead of
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
it could be
<form id="myform" method="POST" class="form_statusinput" onsubmit="homestatus();">
and return the true or false from the function/handler, i.e.
function homestatus()
{
//...
if(condition==true) return true;
else return false;
}
Since you are using jQuery it's better to use as follows
$("form#myform").on('submit', function(event){
event.preventDefault();
var toid = $("#toid").val(); // get value
var content = $("#newmsg").val(); // get value
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + toid + "&newmsg=" + content,
success: function(data){
// do something with data
}
});
});
In this case your form should be as follows
<form id="myform" method="POST" class="form_statusinput">
...
</form>
and input fields should have a valid type and value attribute, Html form and Input.
I think you should read more about jQuery.
Reference : jQuery val and jQuery Ajax.
change the form to this
<form id="myform" ... onsubmit="homestatus(); return false">
you don't need the onsubmit attribute on the submit button, but on the form element instead
homestatus might be out of scope
function homestatus () {
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
}
This isn't tested, but try this (I annotated some stuff using comments)
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
// not sure what this does, so let's take it out of the equation for now, it may be causing errors
//homestatus()
// needed to declare event as a param to the callback function
event.preventDefault();
// I think you want the value of these fields
var toid = $("#toid").val();
var content = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+toid +"&newmsg="+ content,
success: function(){
}
});
return false;
});
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" / >
</div>
</form>
It's a lot easier to let .serialize() do the work of serializing the form data.
The submit handler also needs event as a formal parameter, otherwise an error will be thrown (event will be undefined).
With a few other changes, here is the whole thing:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
homestatus();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: formData,
success: function(data) {
//...
}
});
});
});
</script>
<form id="myform" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" >
</div>
</form>
Unless you are omitting some of your code, the problem is this line:
homestatus()
You never defined this function, so the submit throws an error.
You may want to take a look at jQuery (www.jquery.com) or another js framework.
Such frameworks do most of the stuff you normally have to do by hand.
There are also a bunch of nice helper functions for sending form data or modifying html elements

Categories