Skip to content
Advertisement

Send Javascript array to PHP using Ajax (can’t echo out the array from PHP)

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

<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

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

<?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:

    $.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");
        }

    });
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement