Pass checkbox values with Jquery to PHP and display result in div - php

I want to filter realtime results with jQuery (just like on this site http://shop.www.hi.nl/hi/mcsmambo.p?M5NextUrl=RSRCH). So when someones checks a checkbox the results should update realtime (in a div). Now I'm a newbie with jQuery and I've tried lots of examples but I can't get it to work. Here's my code, could anyone tell what I'm doing wrong? Thank you very much!
HTML
<div id="c_b">
Kleur:<br />
<input type="checkbox" name="kleur[1]" value="Blauw"> Blauw <br />
<input type="checkbox" name="kleur[2]" value="Wit"> Wit <br />
<input type="checkbox" name="kleur[3]" value="Zwart"> Zwart <br />
<br />
Operating System:<br />
<input type="checkbox" name="os[1]" value="Android"> Android <br />
<input type="checkbox" name="os[2]" value="Apple iOS"> Apple iOS <br />
</div>
<div id="myResponse">Here should be the result</div>
jQuery
function updateTextArea() {
var allVals = [];
$('#c_b :checked').each(function() {
allVals.push($(this).val());
});
var dataString = $(allVals).serialize();
$.ajax({
type:'POST',
url:'/wp-content/themes/u-design/filteropties.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
}
$(document).ready(function() {
$('#c_b input').click(updateTextArea);
updateTextArea();
});
PHP
//Just to see if the var passing works
echo var_export($_POST);

You are using .serialize() incorrectly, it works only with form elements.
With this code i think you'll get what you need.
Javascript / JQuery
function updateTextArea() {
var allVals = "";
$('#c_b input[type=checkbox]:checked').each(function() {
currentName = $(this).attr("name");
currentVal = $(this).val();
allVals = allVals.concat( (allVals == "") ? currentName + "=" + currentVal : "&" + currentName + "=" + currentVal );
});
$.ajax({
type:'POST',
url:'/wp-content/themes/u-design/filteropties.php',
data: allVals,
dataType: "html",
success: function(data){
$('#myResponse').html(data);
}
});
}
$(document).ready(function() {
$('#c_b input[type=checkbox]').click(updateTextArea);
updateTextArea();
});

Related

AJAX Function jQuery to PHP Access Response Variables

I am trying to send an AJAX function from jQuery to PHP. I can get it to the right page fine, but when I get there, how do I access the data from the AJAX call? It's probably something silly I'm missing.
jQuery:
$(document).ready(function() {
$("#assessform_page").on("submit", "#assessform", function(e) {
e.preventDefault();
var assessrows = {};
var url = $(this).attr("action");
$("div[data-test-num]").attr("data-test-num", function(index, value) {
assessrows[value] = {};
$(this).children("input[data-tab-row], select[data-tab-row]").attr("data-tab-row", function(i, v) {
assessrows[value][v] = $(this).val();
});
$(this).children("label[data-tab-row]").attr("data-tab-row", function(i, v) {
assessrows[value][v] = $(this).text();
});
});
$.ajax({
url: url,
data: assessrows,
type: "POST",
success: function() {
window.location.href = url;
},
});
});
});
HTML:
<form id="assessform" action="assessment.php" method="post" enctype="application/x-www-form-urlencoded" name="assessform">
<div data-test-num="1">
<label data-tab-row="objname">First Value: </label>
<select autofocus="autofocus" data-tab-row="status">
<option value="not_started">Not started</option>
<option value="in progress">In Progress</option>
<option value="obstacles">Obstacles</option>
<option value="excluded">Excluded</option>
<option value="done">Done</option>
</select>
<input type="text" data-tab-row="numer" value="" />
<input type="text" data-tab-row="denom" value="" />
<br />
<br />
</div>
<button type="submit" name="submit-button" id="submit-button">Submit</button><br />
<button type="button">Save</button><br />
</form>
PHP:
<?php ?> (I can't really do anything until I get this variable.)
What variable do I call to get the data from the AJAX, and what function, if any, do I need to call before I can do that?
EDIT:
If your assessment.php make a response as follows:
<?php
echo 'successfully_completed';
?>
The response data from PHP will be passed as follows:
$.ajax({
url: url, // assessment.php
data: assessrows,
type: "POST",
success: function(data) {
alert("The response is [" + data + "]");
// "The response is [successfully_completed]"
// If you want to pass this data to the next page
window.location.href = "/foo/success.php?data="+data;
}
});
$.ajax({
url: "url",
data: assessrows,
type: "POST",
success: function(data) {
console.log(data); //do something with data
window.location.href = url;
},
});

PHP post variable and array to Jquery

i've this two fields:
<input type="text" name="smsText" value="text sms to send to all">
<input type="text" name="recipients[]" value="3471234567">
<input type="text" name="recipients[]" value="3359876543">
<input type="text" name="recipients[]" value="3201472583">
And I need to send to a php page with an ajax call.
I've this function that i use in many scripts
$("#sendSms").click(function(){
var text = $("input[name=smsText]").val();
var recipients = $("input[name=recipients]").val();
var datastr ='text=' + text +'&recipients=' + recipients;
$(over).appendTo('#box');
$.ajax({
type: "POST",
url: "send-result.php",
data: datastr,
cache: false,
success: function(data){
$('#box').html(data);
}
});
return false;
});
Please, i need help to modify my function to send both "smsText" and array recipients[] to other php page via Ajax...
Thank you very much!
Replace your following code:
var recipients = $("input[name=recipients]").val();
var datastr ='text=' + text +'&recipients=' + recipients;
for this one:
var datastr = '';
$("input[name='recipients[]']").each(function() {
datastr += '&recipients[]=' + $(this).val();
});
datastr ='text=' + text + datastr;
that should do what you want and cause PHP to create the array variable $_POST['recipients'] with all your values in it.
Have a look at jQuerys functions .serializeArray() and .serialize()
Try:
var datastr = '&recipients[]=';
var arr = [];
$("input[name='recipients[]']").each(function() {
arr[] = $(this).val();
});
datastr ='text=' + text + datastr + arr;
If the fields are contained within a form, you can use jQuery's serialize() method to convert the fields into a string to send via Ajax
<form id="sms-form">
<input type="text" name="smsText" value="text sms to send to all">
<input type="text" name="recipients[]" value="3471234567">
<input type="text" name="recipients[]" value="3359876543">
<input type="text" name="recipients[]" value="3201472583">
</form>
$("#sendSms").click(function(){
var datastr = $("form#sms-form").serialize();
$(over).appendTo('#box');
$.ajax({
type: "POST",
url: "send-result.php",
data: datastr,
cache: false,
success: function(data){
$('#box').html(data);
}
});
return false;
});
Try
html
<form name='ohForm' action="#">
<input type="text" name="smsText" value="text sms to send to all">
<input type="text" name="recipients[]" value="3471234567">
<input type="text" name="recipients[]" value="3359876543">
<input type="text" name="recipients[]" value="3201472583">
// and others components
</form>
javascript
$("#sendSms").click(function(){
var form = $("form[name='ohForm']");
var datastr = form.serialize();
$(over).appendTo('#box');
$.ajax({
type: "POST",
url: "send-result.php",
data: datastr,
cache: false,
success: function(data){
$('#box').html(data);
}
});
return false;
});
php
print_r($_POST['data']);

jQuery send message from form

How to send some message to other php file? I should to see "Loading" or result from my imput. I try to find some answer even this code is from this place, but still dosn't work.
I have:
<form>
something<input name="sthis" type="text" />
<input type="submit" value="submit" id="submit" />
</form>
<script type="text/javascript">
$(function(){
$('submit').click(function(){
$('#container').append('loading');
var sthis = $('#sthis').val();
$.ajax({
url: 'form1.php' ,
type: 'POST',
data: 'sthis: ' + sthis,
success: function(result){
$('#container').append('<p>' + result + '</p>')
}
});
return false;
});
});
});
</script>
Form1.php
<?php
$str = $_POST['sthis'];
echo $str;
}
?>
Any ideas?
Try this, I think should be like
data: {"sthis": sthis},
<form id="form1">
<input name="sthis" type="text" />
<input type="button" value="submit" id="submit" />
</form>
<script type="text/javascript">
$('#submit').click(function(){
$('#container').append('loading');
var data = $('#form1').serialize();
$.ajax({
url: 'form1.php' ,
type: 'POST',
data: data,
success: function(result){
$('#container').append('<p>' + result + '</p>')
}
});
return false;
});
</script>
This will send all data from your form to php file
So there are some things you have to change in your script:
$(function(){
$(':submit').click(function(event){
event.stopPropagation();
$('#container').append('loading');
var sthis = $('#sthis').val();
$.ajax({
url: 'form1.php' ,
type: 'POST',
data: {'sthis': sthis},
success: function(result){
$('#container').append('<p>' + result + '</p>');
}
});
return false;
});
});
First there is an extra }); at the end you can remove.
Your input field must have an id with the name sthis, not just a name, so you can access it with $("#sthis"), like this:
<input name="sthis" type="text" id="sthis" />
3rd, change your the data line so it look like this:
data: {'sthis': sthis},
Also, to capture the event of the button you have to use $(':submit'), watch for the :

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