How to pass jquery values to php without page loading - php

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>

Related

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

How to display the AJAX response in input field and pass that value to PHP?

I am getting Id value from my AJAX and I am also able to display it. I set the Id value input text in the AJAX and displaying it on HTML like this <input value="4864" id="compare_id" type="hidden"> Now I have to pass that value to PHP to get the result from database.
Is there any idea how to do it?
AJAX
$(document).ready(function() {
arr = [];
$("[type=checkbox]").click(function() {
$.ajax({
type: "POST",
url: "includes/compare_process.php", //
data: 'users=' + arr,
dataType: 'json',
success: function(msg) {
$("#pics_name,#pics_Id").empty();
$.each(msg, function() {
$("#pics_Id").append("<input type=hidden value=" + this.Id + " id=compare_id name=compare_id>");
//alert(msg.id);
});
},
error: function() {
alert("failure");
}
});
});
});
//tried AJAX
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: "GET",
url: 'includes/compare_process.php?key=compare_details',
data: $('#search-form').serialize(),
success: function(response) {
//$('#response').html(response);
alert(response);
}
} );
});
});
PHP
<div class="bg-popup" style="display: none;" id="open_compare_popup">
//popup code here
<?php
$val2=htmlentities($_GET['compare_id']);
echo $val2;
$sql = "SELECT * FROM `request` WHERE Id IN($val2)";
?>
//end popup code here
This output I am getting from AJAX
<form action="#" method="get" id="search-form">
<span id="pics_Id">
<input value="4869" id="compare_id" name="compare_id" type="hidden">//output
<input value="4884" id="compare_id" name="compare_id" type="hidden">//output
<input value="5010" id="compare_id" name="compare_id" type="hidden">//output
</span>
<button class="action action--button action--compare" type="button" id="search-button" name="search-button"><span class="action__text">Compare</span></button>
</form>
I have to pass the input value to PHP after clicking on a button.

how to checked the checkbox after fetching the data from database using jquery and php

when user click on a button it displays the dynamic data fetched from the database along with the appropriate check box ..so user has select or check the checkbox of some data and submit the result then those data are stored in database.
again that user clicked the same button then again those data are displayed but this time the data which are selected buy the user previously should be checked. I am trying to do that but enable to write code for it in jquery.
below is my code...
javascript
$(document).ready( function() {
$('#location_choose').click(function(e){
branch();
document.getElementById('brn_light').style.display='block';
document.getElementById('fade').style.display='block';
});
function branch()
{
//alert(user_id);
$.ajax({
url: "<?php echo base_url(); ?>/login/branch",
data: {},
type: "post",
cache: false,
success: function (data)
{
//alert(data);
var obj = $.parseJSON(data);
var result = "";
<?php foreach($resultsb as $rows){?>
for ( var i = 0; i < obj.length; i++ )
{
result+="<table id='branchtable'><tr height='25px' ><td>&nbsp&nbsp</td><td ><input class='test' type='checkbox' name='branch_name' value="+obj[i].id+"<?php echo ($rows['branch_id']=="+obj[i].id+"? 'checked' : '');?>></td><td width='15px'></td><td width='630px'><b>"+obj[i].branch_name+
"</b></td></tr><tr><table id='branch_address' style='background-color:#EBF5FB'><tr><td>&nbsp&nbsp</td></tr><tr><td width='60px'></td><td width='440px'>"+obj[i].address+"</td><td width='40px'></td></tr><td>&nbsp</td></table></tr><tr></tr></table>";
}
<?php }?>
//alert(result);
document.getElementById("branch_table").innerHTML=result;
},
error: function (xhr, ajaxOptions, thrownError)
{
//alert(thrownError);
}
});
}
});
i tried using
<?php echo ($rows['branch_id']=="+obj[i].id+"? 'checked' : '');?>
in above code but still it doesnt checked the previous selected one.
Give The Same Class of Checkbox and Write Jquery Code
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
$( '.select_all_text').click(function() {
var is_check = $(".select_type").prop('checked');
if(is_check == false)
{
$(".select_type").prop('checked', true);
$(''.select_all_text").text('De-select All');
}
else
{
$(".select_type").prop('checked', false);
$('.select_all_text").text('Select All');
}
});
});
</script>
</head>
<body>
<p style="position: sticky; z-index: 100; width: 50%;"><a id="select_all" onclick="check_uncheck" style="margin-right: 2%;" href="javascript:void(0)">Select all</a>
<?php
foreach($data_list as $data)
{
?>
<input type="checkbox" name="select_type[]" value="<?php echo $item_id; ?>" class="select_type" id="select_type"/>
<?php
}
?>
</body>
</html>

Ajax call to same page is not working

I am getting records from database in WordPress then creating and adding value in select tag(HTML) dynamically.
<?php
global $wpdb;
$registeredUsers = $wpdb->get_results('SELECT * FROM wp_users where user_login != "Admin"',ARRAY_A);
$select='<select name="users" class="form-control" id="users">';
$select.= '<option value="Select User"> Select User</option>';
foreach($registeredUsers as $user)
{
$select.='<option value="'.$user['user_email'].'">'.$user['user_login'].'</option>';
}
$select.='</select>';
?>
I am using $select variable in Html and drop down is being displayed properly.
<form id="a" action="" method="post">
<div style="margin: 0 auto;width:500px;">
<?php echo $select ?>
</div>
</form>
I have written code to get selected drop down onchange event in jquery. It return success but I am not able to get selected value of dropdown.
<script type="text/javascript">
$(document).ready(function(){
$("select[name='users']").change(function () {
jQuery.ajax({
type: "POST",
data: $("form#a").serialize(),
success: function(data){
alert("SUCCESS");
}
});
});
});
</script>
Below code return nothing
if(isset($_POST['users'])) {
echo $_POST['users'];
}
Set url option to your page in your ajax function:)
<script type="text/javascript">
$(document).ready(function(){
$("select[name='users']").change(function () {
jQuery.ajax({
type: "POST",
url:"yourpage.php"
data: $("form#a").serialize(),
success: function(data){
alert("SUCCESS");
}
});
});
});
</script>
replace yourpage.php

AJAX checkboxes with Jquery and 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>

Categories