skip to Main Content

I have a very simple php page with a jquery function

<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            url: "test.php",
            type: "POST",
            data: {
                myvar: 1,
            },
            success: function(result) {
                console.log("it works");
            }
        });
    });
</script>

My AJAX function is supposed to be triggered as soon as the document is ready. My test.php just shows my $_POST.

<?php
    var_dump($_POST);
    die();

Nothing is happening. I should go to test.php and see the var_dump. It works if I have a button and start the AJAX function on the click but not like that… Isn’t possible to do so ?

2

Answers


  1. I test your code work with datatype like :

    ajax page:

      $(document).ready(function() {
            $.ajax({
                url: "test.php",
                type: "POST",
                dataType: 'json', //add that line
                data: {
                    myvar: 1,
                },
                success: function(result) {
                console.log(result);
                    console.log(result['name']);
                }
            });
        });
    
    Login or Signup to reply.
  2. Since on the Back-end part you expect $_POST the best you can do is to use

    FormData API

    jQuery(function($) {
    
      // Your object
      const data = {
        myvar: 1,
        foo: "foo",
      };
    
      // Create FormData from Object
      const FD = new FormData();
      Object.entries(data).forEach(([prop, val]) => FD.append(prop, val));
    
    
      $.ajax({
        url: "test.php",
        type: "POST",
        processData: false, // https://api.jquery.com/jquery.ajax/
        data: FD, // pass the formData and enjoy with $_POST in PHP
        success: function(result) {
          console.log("it works", result);
        }
      });
    
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search