将数据从Ajax发布到PHP

Trying to send a post request from ajax to php.

I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.

main.php

<script>
    $(document).ready(function(){
        $(".editContact").on("click", function(){
        let dataID = $(this).attr("data-id");
        console.log(dataID);

        $.ajax({
            type: 'POST',
            url: 'functions/phonebook.php',
            dataType: "text",
            data:{data:dataID}              

         });

        });
    });
</script>

functions/phonebook.php

if(isset($_POST["data"])){
        $res = array($data=>var_dump($_POST["data"]));
    }
    else{
        $res ='null';
    }

Then print the $res variable containing the dataID from ajax to my html element in main.php

<label class="m-label-floating">Contact name <?php echo $res; ?> </label>

The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.

Your problem is here:

$res = array($data=>var_dump($_POST["data"]));

You are using var_dump the wrong way.

From the docs:

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.

What you need to is:

$res = array($data => $_POST["data"]);

If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:

 window.location.replace(...)

If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:

 $.ajax({
        type: 'POST',
        url: 'functions/phonebook.php',
        data:{data:dataID},                
        success: function (html) {
             // do your HTML replace / add stuff  here
        },
     });