I’ve a form with a simple button in it. When clicking on the button the function delete_data()
is called. This function fills an array with data. I would like to send this array to PHP with Ajax.
Problem: When using the event.preventDefault();
as you can see in my JavaScript code, the success alert messages is displayed (“OK”) but i don’t obtain the echo from my php script.
Could you correct my code bellow or tell me what is wrong? Thanks a lot!
HTML CODE
JavaScript
x
<form id="form" method="POST">
<button type="button"id="delete" onclick="delete_data();" name="delete"><i class="fa fa-remove" aria-hidden="true"></i> Delete Zone(s)</button>
</form>
JavaScript CODE
JavaScript
function delete_data(){
event.preventDefault();
var checkedIds = $(".chk:checked").map(function() {
return this.id;
}).toArray();
var Arr = JSON.stringify(checkedIds);
$.ajax({
type: "POST",
url: "./delete_measurement.php",
data: {arr: Arr},
cache: false,
success: function(){
alert("OK");
}
});
PHP CODE
JavaScript
<?php
include_once("./conn.php");
if(isset($_POST['arr'])){
$arr = json_decode($_POST['arr']);
echo $arr; //can't echo
}else{
echo "Failed";
}
?>
Advertisement
Answer
It’s logic that you don’t see the echo. Add a parameter to the success function like this:
JavaScript
$.ajax({
type: "POST",
url: "./delete_measurement.php",
data: {arr: Arr},
cache: false,
success: function(data){
// This will show what you echo in PHP (in the console)
console.log(data)
alert("OK");
}
});