weixin_33720956 2019-08-03 01:32 采纳率: 0%
浏览 13

将数据从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.

  • 写回答

2条回答 默认 最新

  • weixin_33681778 2019-08-03 01:55
    关注

    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"]);
    
    评论

报告相同问题?