how to checkbox value stored array when click checkbox using ajax - php

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

Related

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.

Send POST when checkbox is ticket - without submit button

I want to send POST data without submit button, when one of the checkboxes are ticked - USING AJAX.
I have this code, but I think, that when I tick checkbox, I should get an alert with posted data (to know, that its working), but I dont get any reaction at all. I've added jquery so it's some kind of error in code function..
<form method="post" name="form1">
<input type="checkbox" name="checkboxList[]" value="1">value1</input>
<input type="checkbox" name="checkboxList[]" value="2">value2</input>
<input type="checkbox" name="checkboxList[]" value="3">value3</input>
</form>
<script>
jQuery(document).ready(function($){
// jQuery code is in here
$("input[type=checkbox]").on("click", function() {
var data = $(this).val();
console.log(data); // 1, 2 or 3 (value)
$.ajax({
url: "<?php echo JURI::getInstance(); ?>", // URL should be correct!
type: "POST",
async: true,
cache: false,
data: {data: data},
dataType: 'text',
success: function(data){
alert(data);
}
});
});
});
</script>
PROBLEM: Getting HTML content of page, not value on success method
Change your Html as below 1. remove </input> and change 2. change form name to id
<form method="post" id="form1">
<input type="checkbox" name="checkboxList[]" value="1">value1
<input type="checkbox" name="checkboxList[]" value="2">value2
<input type="checkbox" name="checkboxList[]" value="3">value3
</form>
Change in JS
var data = $("#form1").serialize();
Your form was not selecting and in post there was blank data
Try below code.
<form method="post" name="form1">
<input type="checkbox" name="checkboxList[]" value="1">value1</input>
<input type="checkbox" name="checkboxList[]" value="2">value2</input>
<input type="checkbox" name="checkboxList[]" value="3">value3</input>
</form>
<script>
$("input[type=checkbox]").on("click", function() {
var data = $("form").serialize();
$.ajax({
url: "../../x.php", // URL should be correct!
type: "POST",
async: true,
cache: false,
data: {data: data},
dataType: 'json',
success: function(response_data){
alert(response_data);
}
});
});
</script>

Sending Multiple data to PHP page without reloading page

Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});

Wordpress Ajax Form with two submit buttons

I am working in wordpress and I have one form and two submit buttons. I am using ajax and it is wordpress.
When first submit button is pressed I want statement 1 to be echoed and when submit button number 2 is pressed I want state 2 be echoed. I have followed the code tutorials but when I press submit from the control returns empty or no result and in inspect there is no error in the browser. Below is my code.
HTML Form
<form id="voteform" action="" method="post">
<input name='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
<input name='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'>
</form>
I am not copying the enqueue code but just the actual php function that executes
function articlevote ()
{
if ($_POST['vote'] == 'one') {
echo json_encode("1 vote button is pressed");
die();
}
else if ($_POST['vote'] == 'two') {
echo json_encode("2 vote button is pressed");
die();
}
}
Ajax and jquery
jQuery(function ($) {
$(document).on("click","input[name=vote]", function() {
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});
Again kindly note that I am using wordpress so kindly guide me in this thanks
This should get you what you need:
Html:
<form id="voteform" action="" method="post">
<input type="text" name="field1" value="field one value"/>
<input type="text" name="field2" value="field two value"/>
<input class='vote' value='two' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
<input class='vote' value='one' src='http://localhost:8080/test/wp-content/uploads/2015/04/up.jpg' type='submit' type='image'/>
</form>
jQuery
jQuery(function($) {
var yes = {ajaxurl:"mypage.php"}; // created for demo
$('.vote').click(function(e) {
e.preventDefault(); // stop the normal submit
var _data = $('#voteform').serialize()+'&vote=' + $(this).val();
//alert(_data)
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data: _data,
success: function(html) {
$("#myresult").html(html); // you had `res` here
}
});
});
});
$(document).ready(function(){
$('input[value=\'one\'], input[value=\'two\']').on('click', function(){
var _data= $('#voteform').serialize() + '&vote=' + $(this).val();
$.ajax({
type: 'POST',
url: yes.ajaxurl,
data:_data,
success: function(html){
$("#myresult").html(res);
}
});
return false;
});
});

How to separate php generated buttons

I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });

Categories