简体   繁体   中英

Jquery array send by ajax to php

I viewed so many post aboit this but still cant get my code to work.

I want to get a php array of my checked checkboxes values.

heres my code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<title>Untitled Document</title>

</head>

<body>

 <?php


echo'<form method="post">
<input type="checkbox"  name="cim"  value="valami">';
echo'<input type="checkbox"  name="cim"  value="valami2">';
echo'<input type="checkbox"  name="cim"  value="valami3">';
echo'<input type="checkbox"  name="cim"  value="valami4">
<input type="submit" value="Felvisz" name="feladat"></form>';

if (isset($_POST['feladat'])) {

?>  
<script type="text/javascript">

var checkedValue = $('.messageCheckbox:checked').val();

var myJSON = JSON.stringify(checkedValue);

$.ajax({        
       type: "POST",
       url: "proba.php",
       data: { tomb : myJSON },
       success: function(){
alert("OK");
}
    }); 

</script>

<?php

var_dump($_POST);

$array = json_decode(stripslashes($_POST['tomb']));
foreach($array as $arr){
    echo $arr;
}

}
?>

</body>
</html>

Massages i got: Notice: Undefined index: tomb in D:\\programok\\xamp\\htdocs\\SZAKDOGA\\Dropbox\\proba.php on line 48

Warning: Invalid argument supplied for foreach() in D:\\programok\\xamp\\htdocs\\SZAKDOGA\\Dropbox\\proba.php on line 49

Please someone can help me to solve this?

To get an array , you must convert the name to accept multiple so change the input's :

name="cim"

to

name="cim[]"

Also your jquery ajax function should be this :

<script type="text/javascript">
$(function(){

$("form").on("submit",function(e){
e.preventDefault();
var checkedValue = $(this).serialize();

$.ajax({        
       type: "POST",
       url: "proba.php",
       data: checkedValue,
       success: function(){
   alert("OK");
   }

});//end ajax 


});//end form submit
});
</script>

in php the cim will be the array example

var_dump($_POST["cim"]);

hope it helps

currently, you are testing for checked boxes with class messageChecked . assign your checkboxes that class, give your form an id , then test for checked condition on each checkbox,

 $('#yourForm').each(function() {
    if($('.messageChecked').is(':checked')) {
        checkedValue.push($('.messageChecked:checked').val());
    }
 }

now send it to your php script via ajax,

 $.ajax({        
   type: "POST",
   url: "proba.php",
   data: { tomb : (checkedValue) },
   success: function(){
      alert("OK");
   }
 }); 

if done like this you can remove json_decode and stripslashes from your $_POST statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM