How to send multiple checkbox group values through ajax? - php

I am having three group of check boxes as follows:
echo '<input type="checkbox" name="metal[]" value="'.$value.'" id="'.$value.'" onclick="return submitForm()" ><label for="'.$value.'"></label>';
echo '<input type="checkbox" name="shape[]" value="'.$value.'" id="'.$value.'" onclick="return submitForm()"><label for="'.$value.'" ></label>';
echo '<input type="checkbox" name="type[]" value="'.$value.'" id="'.$value.'" onclick="return submitForm()"><label for="'.$value.'" ></label>';
All coming from database.
I want to send these values through ajax. My current code is:
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'carousel.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}</script>
This function is sending only single value to carousel.php. I further want to process data and show result according to the checked values. Also on clicking another checkbox, previous checkbox values is lost. I found above code on google and very new to ajax. Please help.

Related

how to check if a checkbox is checked when sending data via ajax to php

I have a foreach loop which creates tr's with inside a checkbox and some input fields.
Each row has a checkbox with the id as value.
Each row has also a hidden input field with the id as value.
I want to distinguish whether a request is send via the own delete button in each row, or via the checkbox what is checked for (these) rows. (when multiple checkboxes are checked, i can delete them all at once)
<tr>
<input type="hidden" name="file_id" value="<?php echo $file_id; ?>" /> <!-- file id which belongs to each row -->
<td><input type="checkbox" class="checkbox" value="<?php echo $file_id; ?>" /></td>
...
<button class="btn btn-sm btn-danger submit" type="submit" name="delete_file">Delete</button>
</tr>
i send the data via jquery ajax to the php file:
// checkboxes value
$(document).on('click' , '.submit' , function() {
var checkbox_value = [];
var file_id = $(this).closest("tr").find("input[name='file_id']").val();
$('.checkbox').each(function() {
if ($(this).is(":checked")) {
checkbox_value.push($(this).val());
}
});
checkbox_value = checkbox_value.toString();
$.ajax({
url: "admin.php",
method: "POST",
data: {
checkbox_value: checkbox_value,
file_id : file_id
},
success: function(data) {
$('.result').html(data);
}
});
});
The php:
if(isset($_POST["checkbox_value"])) {
$checkboxfiles[] = $_POST["checkbox_value"];
$category = $_POST["category"];
// checkbox loop
foreach ($checkboxfiles as $checkboxfile) {
foreach(explode(',', $checkboxfile) as $id) {
echo $id.'<br />';
echo 'delete via checkbox is choosen';
}
}
exit;
}
if(isset($_POST["file_id"])) {
...
echo 'delete via single row is choosen';
}
Problem:
When i choose to delete via single row (no checkbox is checked), it still sends the echo delete via checkbox is choosen
try this code
if (this.checked) {
checkbox_value.push($(this).val());
}

Ajax - Send PHP value via ajax to another page

i have a form with a switch toggle and a input field named userid.
When i switch the toggle all works fine and the active.php save the new status in the database.
But now i want to have also the userid value to the active.php.
The var mode can i get in the active.php via
$mode=$_POST['mode'];
How can i send the userid also to active.php?
Any idea?
Thank you
<input type="checkbox" name="<?php echo 'toggle'.$c;?>" id="<?php echo 'toggle'.$c;?>" data-toggle="toggle" data-off="OFF" data-on="ON" checked>
<input id="userid" name="userid" type="hidden" value="<?php echo $userid;?>">
This is the js code
$('#<?php echo 'toggle'.$c;?>').change(function(){
var mode= $(this).prop('checked'),
$.ajax({
type:'POST',
dataType:'JSON',
url:'active.php',
data:'mode='+mode,
success:function(data)
{
var data=eval(data);
message=data.message;
success=data.success;
$("#heading").html(success);
$("#body").html(message);
}
});
});
Use the & to separate the two keys.
First of all, retrieve the userid value
var userid = $('#userid').val();
data:'mode=' +mode+'&userid='+userid,
In your ajax parameter, change the data attribute to look as follows:
data: 'mode='+mode + '&userid=' + $('#userid').val ()

onclick function using ajax

In my code having two radio buttons in form like
<input type="radio" required="required" id="bt" name="bt" value="1" checked="checked" onclick="window.location='<?php echo $_SERVER['REQUEST_URI']; ?>';" /> <span>Test1</span>
<input type="radio" required="required" id="bt" name="bt" onclick="Clear()" value="2" /> <span>Test2</span>
when i click on Test2 radio button the form having value will clear, for that i wrote code its working fine
<script>
function Clear() {
document.getElementsByName("one")[0].value = "";
document.getElementsByName("two")[0].value = "";
document.getElementsByName("three")[0].value = "";
}
</script>
with this form with values cleared.But when i click on "Test1" radio button the form values will come automatically.right now iam sessions using
onclick="window.location='<?php echo $_SERVER['REQUEST_URI']; ?>';"
for this it is coming but page is refreshing how to take it this code to ajax, i mean need to get values when i click on radio button without refreshing the page
Yes you can use window.location.href in ajax as:
$.ajax({
type: 'POST',
async: false,
url: '/users',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(payload),
success: function(data, textStatus, jqXHR){
console.log(jqXHR.status);
window.location.href= "/someUrl.html";
}
});
Note that: window.location.href will not reload the page if there's an anchor (#) in the URL
Here i wrote code for getting values of radio button without page refresh:
html code:
<input type="radio" name="bt" id="bt" onclick = "MyAlert()" value="blue"/>Blue <br/>
<input type="radio" name="bt" id="bt" onclick = "MyAlert()" value="red"/>Red
ajax script:
function MyAlert() {
var radio =$('input[type="radio"]:checked').val();
var pass_data = {
'radio' : radio,
};
$.ajax({
url : "radio-value.php",
type : "POST",
data: pass_data,
success : function(data) {
// alert radio value here
alert(data);
}
});
return false;
}
radio-value.php file:
<?php echo $bt =$_POST['radio']; ?>
Hope this helps.

what makes isset null/empty

I have several places that's returning empty and I am not sure why.
One place is using ajax. When an user clicks on the radio button, the value Y or N is sent upon clicking the radio button. When I go to my controller and do echo $_POST['vote']; it is always returning an empty value.
var value = $(this).val();
$.ajax( {
type: "POST",
url: url,
data: {'vote':value},
success: function(data){
alert(data);
}
})
Another place is when i do an ajax upload on a file using a form. On change of the upload field, it always return empty as well. So when I tried isset$_POST[Image] I am always getting a blank. It sees that all my file upload instance is blank.
So what would be the cause of these blanks? I also tried $_GET doesn't help much.
*****[EDIT]*********
<form id="vote-form" action="/some/path?r=shop/vote" method="post">
<input id="ytvote" type="hidden" value="" name="vote[hot_not]">
<span id="vote_hot_not">
<input class="fire-toggle" value="Y" type="radio" name="Vote[hot_not]" data-radio-fx="Vote[hot_not]" style="display: none;"><a title=" " data-radio-fx="Vote[hot_not]" class="radio-fx" href="#"><span class="radio"></span></a>
<label style="display:inline" for="Vote_hot_not_0"><img src=" /images/site/red-hot-not.png" id="hot-i"> </label>
<!--input class… fire-toggle-->
<input class="fire-toggle" value="N" type="radio" name="Vote[hot_not]" data-radio-fx="Vote[hot_not]" style="display: none;"><a data-radio-fx="Vote[hot_not]" class="radio-fx" href="#"><span class="radio"></span></a> <label style="display:inline" for="Vote_hot_not_1"><img src=” /images/site/hot-not.png" id="not-i"></label></span>
</form>
Now in my fire-toggle I have:
$(".fire-toggle").click(function() {
var value = $(this).val();
var url = "<?php echo Yii::app()->createUrl('shop/vote');?>";
$.ajax( {
type: "POST",
url: url,
data: {'vote':value},
success: function(data){
alert(data)
}
})
});
So value actually gives me the expected value..
and here in the controller... I simplified everything down to this:
$pid =Yii::app()->request->getQuery('id');
$uid = yii::app()->user->user_id;
$model = PrototypeReview::model()->getUserVote($uid, $pid);//also tried hard code numbers
$response = $_POST['vote']; //there's nothing in here!
echo $_POST['vote'];

How to separate php generated buttons

I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });

Categories