AJAX checkboxes with Jquery and PHP - php

I have two rows of check-boxes. When a user clicks on any individual check-box (in a certain row) I want to add a number to my sum in PHP. If he deselects an individual check-box I want to subtract from the total in real time without page refresh. My question what goes in the data field on my AJAX call?
and is this the correct way to do it ?
HTML
<input type="checkbox" name="standard_form[]" value="A" onclick="processForm()">
<input type="checkbox" name="premium_form[]" value="B" onclick="processForm()">
JQUERY
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'submit_form.php',
data: '',
success: function(data) {
$('#message').html(data);
}
} );
}
</script>
PHP
if(IsChecked('standard_form','A'))
{
$price += IsChecked('standard_form','A') ? 10 : 0;
}
return $price ;

Try:
<script type="text/javascript">
function processForm() {
$.ajax( {
type: 'POST',
url: 'submit_form.php',
data: { checked_box : $('input:checkbox:checked').val()},
success: function(data) {
$('#message').html(data);
}
} );
}
</script>

You have to serialize the form into a JS object, that's what goes into the data field. Here's a simple serialize function, that could be improved, but will give you an idea
function serializeForm(form) {
var obj = {};
for (var i = 0; i < form.elements.length; i++) {
var el = form.elements[i];
if (el.name) {
if (obj[el.name] && obj[el.name].constructor == Array ) {
obj[el.name].push(el.value);
} else if (obj[el.name]) {
obj[el.name] = [obj[el.name], el.value];
} else {
obj[el.name] = el.value;
}
}
}
return obj;
}
There is a plugin that lets you submit forms with AJAX easily http://jquery.malsup.com/form/ See jQuery AJAX submit form
Assuming the following HTML
<form id="myForm" action="submit_form.php" method="post">
<input type="checkbox" name="standard_form[]" value="A" onclick="processForm()">
<input type="checkbox" name="premium_form[]" value="B" onclick="processForm()">
</form>
You can just do the following to have the form posted with AJAX
// attach handler to form's submit event
$('#myForm').submit(function() {
// submit the form
$(this).ajaxSubmit();
// return false to prevent normal browser submit and page navigation
return false;
});

In checkboxes try onclick="processForm(this)", then, in JavaScript:
<script type="text/javascript">
function processForm(elm) {
$.ajax( {
type: 'POST',
url: 'submit_form.php',
data: elm.name+'='+elm.value,
success: function(data) {
$('#message').html(data);
}
} );
}
</script>

Related

Ajax POST and php query

Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});

Input validation through AJAX

I have the following AJAX in my index.php:
$(document).ready(function() {
$('.buttono').click(load);
});
function load() {
$.ajax({
url: 'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data) {
$('#content').append(data);
});
}
HTML (part of index.php):
<form method="POST" action="">
<input type="text" name="input">
<input type="submit" name="submit" class="buttono" value="Convert">
</form>
<div id='content'></div>
And in my ajaxRequest.php I have the following PHP snippet:
if ($_POST['input'] == 'dog') {
echo 'Status 1';
} else if ($_POST['input'] == 'cat') {
echo 'Status 2';
}
How can I perform the PHP check through AJAX? So that if I click the submit button and have typed 'dog', to return the string Status 1?
Well what I see in your code is that:
first you have not specified your request method,
second you have not set $_POST['dog']
I would have gone with this ajax:
$.ajax({
type : "POST",
url : 'to/url',
data : { input : $("input[name='input']").val() },
success : function(data){
// do whatever you like
}
});
What you have to do is make the user fill out the form and then instead of clicking a type="submit" button just make them click a regular button. Then when that person clicks the regular button submit. You can do this by:
<!-- HTML -->
<form method="POST">
<input type="text" id="type"/>
<button id="submit">Sumbit</button>
</form>
<!-- JS -->
$(document).ready(function(){
$('#submit').click(onSubmitClicked);
});
function onSubmitClicked(){
var data = {
"input": $('#type').val()
};
$.ajax({
type: "POST",
url: "url/To/Your/Form/Action",
data: data,
success: success
});
function success(data){
if(data == 'status 1'){
//Do something
}
}
}
Try this:
in you php file:
$res = array();
if ($_POST['input'] == 'dog') {
$res['status'] = '1';
} elseif ($_POST['input'] == 'cat') {
$res['status'] = '2';
}
echo json_encode($res);
Then in your jquery:
function load(){
$.ajax({
type : "POST",
data : { input : $("input[name='input']").val() },
url:'http://localhost/Generator/js/ajaxRequest.php'
}).done(function(data){
$('#content').append(data.status);
});
}

How to pass jquery values to php without page loading

I want to pass the jquery value "selected" to fetchdata.php without reloading the page.
How can I do this?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript">
</script>
<script>
$(document).ready(function() {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass() {
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if (selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" + selected, //The data your sending to some-page.php
success: function()
{
console.log("AJAX request was successfull");
},
error: function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
} else
{
alert("Please at least one of the checkbox");
}
}
</script>
</head>
<body>
<div id="checkboxlist">
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>
<div>
<input type="button" value="Get Value Using Class" id="buttonClass">
</div>
</html>
fetchdata.php
<?php
foreach($_GET['val'] as $r)
{
print_r($r);
}
?>
I am using the GET method to receive the data and the for-each loop to print the array, but I am not getting any values in the PHP file.
change the ajax function like below and make sure about the fectdata.php in the same folder or give the correct path.
$.ajax({
url: 'fetchdata.php',
type:'GET',
data: {val:selected},
success: function(data) {
console.log("AJAX request was successfull");
}
});
Check if the path to your script is correct:
url: 'fetchdata.php',
Is this script in your doc root?
change the following in your code,
in fetchdata.php
<?php
$valArray = explode('#',$_GET['val']);
foreach($valArray as $val){
echo $val."<br/>";
}
?>
In html File,
$(document).ready(function () {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass(){
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if(selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" +selected.toString(), //The data your sending to some-page.php
success: function(data1) {
$("#resultDiv").html(data1);
console.log("AJAX request was successfull");
},
error:function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
}else
{
alert("Please at least one of the checkbox");
}
}
include the div after a button like
<div id="resultDiv"></div>

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;

Values from javascript to PHP

I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)

Categories