1

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";
    
}
?>
13
  • If you trying to echo static string as echo 'Hello world'; is it working? I mean, do you know if the problem in the echo or in the post var? Commented Sep 10, 2020 at 10:37
  • console.log Arr above ajax and see if its outputting properly Commented Sep 10, 2020 at 10:38
  • @MrKhan yes it's outputting the json string properly with all the Id's inside Commented Sep 10, 2020 at 10:42
  • Are you sure you are looking at the right page? check your page name and the one you passed. Commented Sep 10, 2020 at 10:43
  • @dWinder No, when i echo out "Hello World" in the php script instead of $arr, nothing changes, i can't see the echo Commented Sep 10, 2020 at 10:44

1 Answer 1

1

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

    });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.