jQuery AJAX/POST not sending data to PHP

前端 未结 7 1363
春和景丽
春和景丽 2020-12-29 03:54

So I have this problem for a while now, and I know there are countless questions on this topic, believe me I tried every solution possible but still does not work.

T

相关标签:
7条回答
  • 2020-12-29 04:32

    Why not use jQuery.post?

    $.post("ajax/add-user.php",
           {name: 'John'},
           function(response){
               console.log(response);
           }
    );
    

    Then in your PHP you could save the input like so:

    if(isset($_POST["name"]))
    {
        $name= $_POST["name"];
        file_put_contents("name.txt", $name)
        header('HTTP/1.1 200 OK');
    }
    else
    {
        header('HTTP/1.1 500 Internal Server Error');
    }
    
    exit;
    
    0 讨论(0)
  • 2020-12-29 04:40

    I was trying many things but I found below working code for me:

    if ( $_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) ) {
        $_POST = json_decode(file_get_contents('php://input'), true);
    }
    

    This will work if you will try.

    0 讨论(0)
  • 2020-12-29 04:48

    You need to set the data type as json in ajax call.

    JQUERY CODE:

    $.ajax({
      url: "ajax/add-user.php",
      type: "POST",
      dataType:'json',
      data: {name: 'John'},
      success: function(data){
          console.log(data);
      }
    });
    

    At the same time verify your backend code(php), whether it can accept json data ?

    If not, configure the header as below:

    PHP CODE:

    /**
     * Send as JSON
     */
    header("Content-Type: application/json", true);
    

    Happy Coding :

    0 讨论(0)
  • 2020-12-29 04:48

    I was having this same problem and the issue turned out to be one of my variables in the data object was undefined. For some reason that prevented the post data being sent. Setting the variable to something other than undefined fixed the problem.

    0 讨论(0)
  • 2020-12-29 04:49

    You should check your .htaccess file, close lines with "#" symbol

    # To externally redirect /dir/foo.php to /dir/foo
    # RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
    # RewriteRule ^ %1/ [R,L]
    
    0 讨论(0)
  • 2020-12-29 04:52

    I recently came across this issue but because of other reasons:

    1. My POST data was redirected as 301
    2. My Server request was GET
    3. I did not get my POST data

    My reason - I had a url on the server registered as:

    http://mywebsite.com/folder/path/to/service/
    

    But my client was calling:

    http://mywebsite.com/folder/path/to/service
    

    The .htaccess on the server read this as a 301 GET redirect to the correct URL and deleted the POST data. The simple solution was to double check the url path.

    @C.Ovidiu, @MarcB - Both of you guys saved me lots of hours in debugging!

    0 讨论(0)
提交回复
热议问题