skip to Main Content

This is driving me crazy. I’m trying to post a variable to a PHP script using AJAX but while I can verify that $_POST is set, the varibale remains undefined.

I’ve used almost identical code elsewhere and it works fine – I just cant see what the problem is here.

Here is a very stripped down version of the code –

The JS

$(function(){
  $('#load_more_comments').click(function(){

    var newLimit = 40;
      $.ajax({
          url: "scripts/load_comments.php",
          data: { limit: newLimit },
          type: "post",
          success: function(result){

            // execute script

          },
          error: function(data, status, errorString)
        { 
            alert('error');
        }
      });
      return false;
  });
});

The PHP

if (isset($_POST)) {

    echo "POST is set";

    if (isset($_POST['limit'])) {

        $newLimit = $_POST['limit'];
        echo $newLimit;

     }

}

UPDATE
var_dump($_POST) returns array(0) { } so I know that AJAX is definitely is not posting any values

2

Answers


  1. Using slightly modified version of the above I am unable to reproduce your error – it appears to work fine.

    <?php
        if( $_SERVER['REQUEST_METHOD']=='POST' ){
            ob_clean();
            if( isset( $_POST['limit'] ) ){
                echo $_POST['limit'];
            }
            exit();
        }
    ?>
    <!DOCTYPE html>
    <html lang='en'>
        <head>
            <meta charset='utf-8' />
            <title></title>
    
            <script src='//code.jquery.com/jquery-latest.js'></script>
            <script>
                $(function(){
                  $('#load_more_comments').click(function(){
    
                    var newLimit = 40;
    
                      $.ajax({
                          url: location.href,               //"scripts/load_comments.php",
                          data: { limit: newLimit },
                          type: "post",
                          success: function(result){
                            alert( result )
                          },
                          error: function(data, status, errorString){ 
                            alert('error');
                        }
                      });
                      return false;
                  });
                });
            </script>
        </head>
        <body>
            <!-- content -->
            <div id='load_more_comments'>Load more...</div>
        </body>
    </html>
    
    Login or Signup to reply.
  2. Try :

    if (count($_POST)) {
    

    Instead of

    if (isset($_POST)) {
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search