passing array value from jquery ajax to php function call - php

I have a 10 checkboxes, when i want to delete the appropriate record I use to select one or more checkbox. All the checkbox nams are array. I'm properly getting the values from the html page to jquery function. After that i pushed all the checked boxes into the array created in the jQuery function. But i'm not able to sent the values from this jquery function to the ajax php function. May be the way i'm trying will be wrong. Please check out my code below.
function BulkDelete()// jQuery Function
{
var Selected = new Array();
jQuery("input[name='chec[]']:checked").each(function(){
Selected.push(jQuery(this).val());
});
jQuery.ajax({
url:"<?php echo admin_url( 'admin-ajax.php' ); ?>",
type:"POST",
data:"action=doctor_management_add_dept&id="+ Selected +"&task=bulkdelete",
success:function(data){
jQuery("#msg").html("<div id='message'>"+data+"</div>");
}
});
}
function doctor_management_add_dept() // PHP function
{
if($_POST['task']=="bulkdelete") {
$ars[] = $_POST['id'];
echo count($ars);
}
}
I'm not getting any error. But the same time it's always returning 1.

You may want to serialize your form data, then pass a whole one to your PHP script. In this case, you'll be able to tell how many rows affected.

Related

How to access jQuery variable in PHP and PHP variable in jQuery?

What I want to do:
I want to get a value from a select element
And then I want the specific record from the database on the basis of that value.
Finally, gets the record and displays it in an input field
This is my code:
You can't pass jQuery variable to PHP as such, however you can do same thing through ajax, where just pass selected value through ajax to PHP file and get returned result display in input field
<script>
$("#chooseRoles").change(function(e){
e.preventDefault();
$.ajax({
url: 'getValue.php',
data: 'selectedRole='+$(this).val(),
type: 'POST',
success: function(result){
$("#userRoles").val(result);
}
});
});
PHP CODE (getValue.php);
$roles = Roles::find($_POST['selectedRole']);
echo $capabilities = $roles->capabilities;

how to use jquery variable in php to insert into database

hello in the following code variable checked_num contains the integer value like 1,2,.
now i want this value in database using php code using mysql insert query..
the jquery code i have is:
<script type="text/javascript">
// function for counting check boxes
$(document).ready(function (){
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
});
});
now i want that variable "checked_num" is accessed in php code so i can insert this variable value into database
Have you readed the jQuery ajax/post/get ?
You can use ajax to update your database.
EG:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.ajax({
type: 'POST',
url: 'yourpage.php', //this page inserts your data in database
data: {'checked_num': checked_num},
success: function(response){
//do whatever you want on success
},
error: function(xhr, status, errorThrown){
//handle ajax error
}
});
});
You can also use $.get() or $.post() instead of $.ajax().
You can use jQuery's $.post() method:
$('.do').on('click',function(){
var checked_num =$('input[type="checkbox"]:checked').length;
$.post('myPHPScript.php', { checked : checked_num }, function(data) {
/* data is the response you receive from the server. */
});
});
Here "checked" is the name of the post variable you're sending over. If you wanted to post a string named "myString" containing the text "Hello, world!", for example, you'd use { myString : "Hello, world!" }. This is an object, meaning multiple variables can be sent over by separating each with a comma.
In PHP you'd then retrieve this using $_POST:
<?php
$checked = $_POST['checked'];
?>
You'd probably want to encode this post data however before inserting it into your database.
As for how to insert the data into your database, check out PDO or mysqli.
You are using javascript to set a flag if one or more of the HTML checkboxs in your form are checked.
So you already have a <form> on the page.
When you submit the form you can access that information directly using PHP
All you have to remember is that checkboxes are only submitted back to the server PHP code if they ARE checked. So all you need to do is test for their existance.
if ( array_key_exists( 'checkbox_name', $_POST ) ) {
// this check box is checked
} else {
// this checkbox is not checked
}

Get Session value based on ajax success

I have a PHP page that uses a jQuery ajax call.
After I execute my AJAX and return a value on success, I need to use this value to pull an item from a PHP array, stored in session and update my SPAN with the new set.
Here's what I've got so far. I tested and I do return correct data value. I guess my syntax in jQuery is off, because my original span fades out, but nothing comes back.
JS:
$.ajax({
...
},
success: function(data){
var nextItem = <?php echo $_SESSION['items'][data]->desc; ?>
$('.x').fadeOut();
$('.x').attr(id, data);
$('.x').text(nextItem).fadeIn();
});
HTML:
<span id="'.$_SESSION['items'][0]->id.'" class="x">'.$_SESSION['items'][0]->desc.'</span>
You should return the session variable in the AJAX call. Execute the PHP code to get the session variable on the URL your AJAX call is hitting. The response of the AJAX call (in this case the 'data' variable in your success function) will be the result of:
<?php echo $_SESSION['items'][data]->desc; ?>
So no PHP code will be in your JS.
If you need to return multiple values, then you might consider using JSON. Your AJAX processing page might be like:
$result = array('id' => $id, 'session' => $_SESSION['items'][$id]->desc);
echo json_encode($result);
Your JS might look like this:
$("#getJSON").click(function() {
$.ajax({
...
success: function(data) {
$obj = $.parseJSON(data);
console.log($obj[0].id, $obj[0].session);
}
});
});​

Creating a 2-dimensional jQuery array from a 2-dimensional PHP array with AJAX

I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.

How to pass multiple checkboxes to PHP through JQUERY

I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3
I think php gets the array if THATS what an array in php supposed to be like.
SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.
JQUERY CODE:
$('#res-button').click(function (){
var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');
alert(room_id);
$.ajax({
type: "POST",
url: "reservation-valid.php",
data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
success: function(data) {
console.log(data);
}
});
});
<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>" />
PHP CODE:
$c_array=$_POST['cvalue'];
echo $c_array;
//foreach($c_array as $ch)
//{
//$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
//}
I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.
room_id is an array, so if you want to get the value for each, you need to get all value together first.
var room_id_string = '';
for(i=0;i<room_id.length;i++){
room_id_string += room_id.eq(i).val() + ',';
}
your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id
Instead of this you will have to create a array and push values in it like this
var room_id = Array();
$('[name=rescheck[]]:checked').each(function(){
room_id.push($(this).val());
});
In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array.
If you get any error here you should debug the js array with firebug for be sure that is formed correctly.
js script:
var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
if ($(this).is(":checked")){
valuesCheck[this.value] = 1;
}else{
valuesCheck[this.value] = 0;
}
and the PHP script:
$checkTab = $_POST['cvalue'];
foreach ($checkTab as $idChkTab => $checkedOrNot){
if ($checkedOrNot== "0"){
//do something if isn't checked
}

Categories