Pass checkbox values into an array using ajax to php - php

I am needing some help passing checkbox values into an array using ajax and retrieving the values in my controller. The following code is not working. I receive the error: "Invalid argument supplied for foreach()". Var_dump gives string(42) "Educator_Classes[]=1&Educator_Classes;[]=3
Thanks for any help you can provide.
My html form input:
<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>
My jquery:
$("#Send_Invite").click(function() {
var form_data = {
Opportunity_Id: $('#Opportunity_Id').val(),
Educator_Id: $('#Educator_Id').val(),
Educator_Classes: $('#Educator_Classes:checked').serialize(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('schedule/update_educator_class'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#response').html(data);
}
});
return false;
})
My controller:
function update_educator_class() {
$Educator_Id = $this->input->post('Educator_Id');
$Opportunity_Id = $this->input->post('Opportunity_Id');
$Educator_Classes = $this->input->post('Educator_Classes');
foreach($Educator_Classes as $Educator_Class):
$this->ion_auth_model->update_educator_class($Opportunity_Id, $Educator_Class, $Educator_Id);
endforeach;
}

You have to use [] for name attribute and not for id, otherwise it can't act like an array
<input type="checkbox" id="Educator_Classes" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>
And also your jQuery code can be simpler:
$("#Send_Invite").click(function() {
var form_data = $(this).closest('form).serialize();
form_data['ajax'] = 1;
$.ajax({
url: "<?php echo site_url('schedule/update_educator_class'); ?>",
type: 'POST',
data: form_data,
success: function(data) {
$('#response').html(data);
}
});
return false;
});
To debut what's passed to $Educator_Classes you can do this:
var_export($Educator_Classes);

The Solution is that you have to take the array of name attribute of checkbox.
Like :
<input type="checkbox" id="Educator_Classes[]" name="Educator_Classes[]" class="Educator_Classes" value="<?php echo $Class_Number; ?>"/>

Related

How to delete multiple records using php and ajax

I have multiple rows of news when I show them using php. I'm trying to remove multiple rows simultaneously using checkboxes next to each row.
This is my php code
<?
$select_news = $mysqli->query("SELECT * FROM news order by time desc limit $x,$numbershownews");
while ($rows_news = $select_news->fetch_array(MYSQL_ASSOC)){
$id_news = $rows_news ['id'];
$title_news = $rows_news ['title'];
?>
<table>
<tr rel="<? echo $id_news; ?>">
<td class="tdtable" id="<? echo $id_news; ?>" width="4%">
<input type="checkbox" rel="<? echo $id_news; ?>" name="checkbox[]" class="checkboxtable" value="<? echo $id_news; ?>">
</td>
<td class="tdtable" id="<? echo $id_news; ?>" width="50%">
<? echo $title_news; ?>
</td>
</tr
</table
<?
}
?>
<button class="deletecheckednews">Delete</button>
and this is jquery code
$(".deletecheckednews").on( 'click', function () {
var arr = new Array();
$(".checkboxtable:checked").each(function () {
arr.push($(this).attr("rel"));
});
if(arr == "") {
alertify.error("no selected news");
} else {
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: arr ,
cache: false,
success: function(data) {
alertify.success(data);
$.each(arr, function(key, value) {
$("tr[rel="+value+"]").fadeOut();
});
}
});
}
return false
});
How can I pass this array on to "delete_multiple_news.php"? I have tried this $checkedneww = $_REQUEST['arr']; and this $checkedneww = $_POST['arr']; but it doesn't work. How would I go about removing the selected rows?
On
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: {"array_del": arr} , / <-
cache: false,
success: function(data){
alertify.success(data);
In PHP use
$array_del = filter_input(INPUT_POST, 'array_del', FILTER_SANITIZE_STRING);
If you wanna see the result, just do:
In PHP ajax:
$array_del = filter_input(INPUT_POST, 'array_del', FILTER_SANITIZE_STRING);
echo json_encode($array_del);
In js:
$.ajax({
type: "POST",
url: "action/delete_multiple_news.php",
data: arr ,
cache: false,
success: function(data){
alertify.success(data);
console.debug(data);
//$.each(arr, function(key, value) {
// $("tr[rel="+value+"]").fadeOut();
//});
}
});
To delete you can use WHERE in sql to filter the results who you want delete example. If the results are more than one, you make a loop or a commun column.
$mysqli->query(DELETE FROM table_name WHERE some_column = $array_del[some_column]);
You're passing a raw array in your ajax call (data: arr) but you're expecting a named variable ($_POST['arr']).
I'm not sure if data: arr is possible with jquery (haven't used it in years) but if it is, then the ids array you're looking for is simply $_POST in its whole.
If that's not the case, or you want to do $_POST['arr'] you should change your JS to data: {arr: arr}.

$.ajax( type: "POST" POST method to php

I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
You need to use data: {title: title} to POST it correctly.
In the PHP code you need to echo the value instead of returning it.
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
function signIn()
{
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: "auth_loginCode.jsp",
data: {Username: Username, Password: Password},
success: function (data) {
alert(data.trim());
window.location.reload();
}
});
}
contentType: 'application/x-www-form-urlencoded'

How to get value on multiple textbox with jquery?

I have form like this:
<input type='text' name='people' id='namepeople'>
<input type='hidden' name='idpeople' id='idpeople'>
<input type='text' name='address' id='address' disabled>
<input type='text' name='age' id='age' disabled>
<input type='text' name='status' id='status' disabled>
and a jQuery script:
$("#namepeople").keyup(function()
{
var namepeople= $(this).val();
var name= namepeople;
$.ajax({
type: "POST",
url: "check.php",
data: "namepeople=" + name,
dataType: "json",
success: function(data)
{
$("#idpeople").val(data[0]);
$("#address").val(data[1]);
$("#age").val(data[2]);
$("#status").val(data[3]);
}
});//ajax
});//keyup
And php code :
<?
mysql_connect("localhost","root","");
mysql_select_db("dbajax");
$name = $_POST["namepeople"];
$sql = mysql_query("select * from anggota where upper(username) like '%$name'");
$row = mysql_fetch_array($sql);
$kt=mysql_num_rows($sql);
if($kt > 0)
{
$idnya=$row["id_anggota"];
$address=$row["address"];
$age=$row["age"];
$status=$row["status"];
}
else
{
$idnya="";
$address="";
$age="";
$status="";
}
echo "$idnya|$address|$age|$status";
?>
This is working out just for value of idpeople, but the other value are not coming out. How to get value on multiple textbox with jQuery?
You should modify your ajax call to send the entire form, because right now it only sends idpeople. You should use $('#myForm').serialize() as shown below, where myForm is the id of your form element. Then, within php you can access all your data with $_POST like $_POST['people'] for example. BUT, if you have your inputs disabled like in your example, they will not be sent to your PHP.
$.ajax({
type: "POST",
url: "check.php",
data: $('#myForm').serialize(),
dataType: "json",
success: function(data)
{
$("#idpeople").val(data[0]);
$("#address").val(data[1]);
$("#age").val(data[2]);
$("#status").val(data[3]);
}
You also need to change your php to return JSON. change the last line of your php to this:
echo json_encode(array($idnya,$address,$age,$status));
Your issue is on the return echo I believe. do the following:.
$res = array($idnya,$address,$age,$status);
$json = json_encode($res);
echo $json;
exit();
And you should be good

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 ;)

jQuery + Ajax form submission, PHP doesn't get any data

I am trying to submit a form that only has a radiobutton group with name=radiob. This is the script I am using for submitting data:
<script type="text/javascript">
$(function() {
$("#myForm").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "index.php?p1=<?php echo $_GET['p1']; ?>",
data: dataString,
success: function() {
$("#ppm").fadeOut("slow");
$("#ppmPlugin").load('?p1=<?php echo $_GET['p1'];?>&result=true');
}
});
return false;
});
});
</script>
But this is what I get in my PHP script:
$_POST array - empty
Array ( )
$_GET array
Array ( [p1] => xxx [result] => true )
But if I alert(dataString); I get radiob=2, that is, the value depending on the radiobutton selected..
How do I fix this problem?
I've tested your code and it works fine. Perhaps you have some kind of redirect in index.php?p1=xxx.
P.S. Tested with this code:
<?php $_GET['p1'] = 1; ?>
<form id="myForm">
<input type="radio" name="radiob" value="1" />
<input type="radio" name="radiob" value="2" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#myForm").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "index.php?p1=<?php echo $_GET['p1']; ?>",
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
And in index.php I have
<?php var_dump($_GET, $_POST); ?>

Categories