post checkbox value using ajax - php

how can i post the value of checked checkbox in php script, using ajax call i.e when the user click on checkbox the value is post to php script.

put on checkbox onclick event:
<input type='ceheckbox' onclick='postwithajax(this)' />
and make a function like:
function postwithajax(e){
//and here send with ajax e.checked
}

use jquery to get values from html
$("#submit").click(function(){
var myarray = [];
$("#div input:checked").each(function() {
myarray.push($(this).val()); //push each val into the array
});
// here post Array with ajax
});
Html
<html>
<head>
</head>
<body>
<div id="div">
<input type="checkbox" value="one_name" checked>
<input type="checkbox" value="one_name1">
<input type="checkbox" value="one_name2">
<input type="button" value="submit" id="submit">
</div>
<textarea id="t"></textarea>
</body>
</html>

Related

posing an array from jQuery to php

I posted a smaller to this yesterday and was shown how to do this but it doesn't work and the user never got back to me and I have been working on the same problem for hours.
I am trying to post a checkbox array from jQuery to php, when I run my code nothing seems to happen and when I try var_dump($_POST) this is all I get
Using this question as a reference, it seems that jQuery doesn't handle arrays too well. You can use to snippet from the accepted answer and it should work just fine.
serialize().replace(/%5B%5D/g, '[]')
Change the submit to a button or better use the form's submit event
why data-type html?
Your php does not seem to react to the serialised data but returns a button...
try my code here: http://plungjan.name/SO/sport.php
I am not unravelling the check box array - that is up to you
<?PHP
if (isset($_POST['saved'])) {
echo "saved"; exit(0);
}
else if (isset($_POST['Submit'])) {
echo var_dump($_POST["sport"]); exit(0);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Sports quiz</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('#myForm').on("submit", function(ev) {
ev.preventDefault(); // cancel submit
var $form = $(this);
if ($("[type=checkbox]:checked").length ==0) {
alert("Please check one or more");
return false;
}
var formData = $form.serializeArray();
formData.push({name:"Submit",value:"submit"}); // note I changed the name from submit to Submit
$.post('sport.php',formData, function(data) {
console.log("Data",data);
if (confirm('You want to save \n' + data + ' as your sport?')) {
formData = $form.serializeArray();
formData.push({name:"saved",value:"saved"});
$.post('sport.php',formData,function(data) {
console.log("Saved Data",data);
});
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
<input type="checkbox" name="sport[]" value="Football">Football<br>
<input type="checkbox" name="sport[]" value="Rugby">Rugby<br>
<input type="checkbox" name="sport[]" value="Golf">Golf<br>
<input type="checkbox" name="sport[]" value="Basketball">Basketball<br>
<br> <input type="submit" class="btn btn-info" name="Submit" value="submit">
</form>
</body>
</html>

Save Jquery var sum in DB MySQL

I'm using jquery to sum values of input checkbox and i need to save the sum into DB MySQL but how can i put the value in a php var? I don't know how can i do this.
Can someone help me out? I'm newbie in jquery :/
Here's the code i'm using:
<script type="text/javascript">
$(document).ready(function () {
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
var val = $(this).attr("preco").replace(',', '.');
sum += parseFloat(val);
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
</script>
<?php
if (isset($_POST['submit'])){
$transporte = $_POST['metodoenvio'];
(... save into DB)
}
?>
<span id="output"></span> // the sum in html shows up here
<form class="cmxform" id="pedidoForm" method="post" action="">
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
Take a hidden type variable with some id in form tag and put value in hidden variable by jquery like:
$("#hidden_var").val(sum);
Then at the end submit the form
add new hidden input field to the form to hold the sum
<form class="cmxform" id="pedidoForm" method="post" action="">
//add new hidden input field to have the sum
<input id="sum_input" name="sum" type="hidden"/>
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
//Then use the jquery to put the sum to input id sum
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
var val = $(this).attr("preco").replace(',', '.');
sum += parseFloat(val);
});
$("#output").html(sum);
//jquery to put sum into form
$("#sum_input").val(sum);
}
You should split your php server side scripts out of your html/js client side pages. create a separate php page so process the data and call it through an ajax call.
change your submit button to just be a button and attach an onclick event to call a function that will sum the checkboxes and then initiate the and ajax request.
<script>
function sumChecked(){
i = 0;
$.each($('#pedidoForm:ckecked), function({
i++;
});
$.ajax({
url:"yourPHPpage.php",
type:"POST",
data:{"sumVar":i},
success: function(data){
alert ("Process Complete");
}
})
}
...
</script>
...
<form class="cmxform" id="pedidoForm">
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="20" />
<input type="checkbox" name="metodoenvio" class="metodoenvio" preco="10" />
(...)
<input type="button" name="submit" id="submit" value="submit" onClick="sumChecked()"/>
</form>
then on your php page catch the $_POST['sumVar'] variable sent through from the form and do whatever you want to server-side with that info.

AJAX - Getting value of radio button and sending it to PHP

I've been having this issue for a while now and I guess I'm stuck. I've been reading on how to use AJAX to send data to a PHP file.
The thing is, I don't really get how to take the value of a radio button in a HTML page and then send that value through AJAX to a PHP file which will then process that value.
So for example:
If I had 2 radio buttons
<input type="radio" name="radio" value="yes">
<input type="radio" name="radio" value="no">
And I would like to take the value of those radio buttons and send it to my PHP file using AJAX.
Next I would be able to process those values in PHP.
How would I make it so that AJAX sends the value of the selected radio button to PHP?
Thanks, in advance!
EDIT:
Full code:
HTML File
<script type="text/javascript">
function updatePremium() {
var input1= $("#premium-yes").val();
var input2= $("#premium-no").val();
$.post( "upd_premium.php", { input1: input1, input2: input2 } );
}
</script>
<div class="usersRow2">
<form action="" method="POST"><label>Premium:</label> <p class="text-info-premium"><?php echo ucwords($premium_check) ?><i class="icon-star"></i></p> <div class="controls-premium"><i class="fa fa-pencil"></i> Edit</div></form>
</div>
<script>
$('#edit-premium').click(function() {
var text = $('.text-info-premium').text();
var input = $('<input type="radio" name="premium" id="premium-yes" value="yes">Yes <input type="radio" name="premium" id="premium-no" value="no">No <div id="premium"></div>')
$('.text-info-premium').text('').append(input);
$('#edit-premium').remove();
$('Update').insertAfter('#premium');
$('<i class="fa fa-times" title="Cancel Edit"></i> <br /><br /><br />').insertAfter('#update-premium');
$('.fa-times').click(function() {
location.reload();
});
});
</script>
PHP File
if($_POST['input1'] == 'yes') {
print_r($_POST);
}
Use jQuery. From the docs, a post is easy:
$.post( "test.php", { name: "John", time: "2pm" } );
Now, you need to get the values of the inputs and pass them to the post:
<input type="radio" name="radio" value="yes" id="input1">
<input type="radio" name="radio" value="no" id="input2">
<script>
var input1= $( "#input1" ).val();
var input2= $( "#input2" ).val();
$.post( "yourphpfile.php", { input1: input1, input2: input2 } );
</script>

Doesn't get value with jQuery

<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".

php output display on a greybox

I have a form that calls a php script on submit to insert data into a MySQL database. I would like the output of the php script return to a greybox. I haven't been able to make it work so I appreciate any help you guys can provide.
I have the greybox call on the form definition see below but is not doing the trick.
Here is a subset of the code:
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJX_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<div id="content">
<form id="contact_us" name="contact_us" action="contact-greybox.php" method="POST" onSubmit="return GB_showCenter('Testing', this.action, 500, 500)">
<fieldset>
<label for="employee_id">Employee ID:</label>
<input id="employee_id" name="employee_id" type="number" size="10" /><P />
<label for="employee_name">Employee Name:<strong><br /> (as it should appear on
email) </strong></label>
<input id="employee_name" name="employee_name" type="text" /><P />
</fieldlist>
<p class="submit"><input type="image" name="submit" value="Submit Form" src="icons/ambas_submit.jpg" boder="0">
</form>
</div>
The php is a simple insert statement into MySQL.
Appreciate any help
greybox doesn't support POST submits, but the general pattern is to use ajax to submit the form- otherwise your page will refresh.
You need to set an onclick( $.submit ) to the form input then return false at the end of your ajax call:
$('#contact_us').submit(function(){
//get your inputs here
var e_id = $.('#employee_id').val();
//...etc....
$.post( ...
//set your data/input fields here:
data: { id: e_id },
success: function(response){
//display the response: this is what you get back from: contact-greybox.php
}
})
return false;
});
fancybox is an overlay box that supports being called with pure html as a parameter, so that you can just put this in your success function:
$.fancybox(response);
...or
$.fancybox(response.html)... etc.

Categories