skip to Main Content

I cannot get my AJAX to work. Any help would be appreciated as I have spent hours on this with no avail. I am using test-data until I stop getting an error:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

My AJAX:

            $.ajax({
                type: 'POST',
                url: 'addsMeal.php',
                dataType:'json', 
                data: ({name: 'Emma'}),
                success: function () {
                    console.log("Sent data to addsMeal PHP file successfully.");
                }
            });

addsMeal.php:


<?php
    // topFields, newIngredient
    $name = $_POST['name'];
    echo($name);
?>

The error is:
Warning: Undefined array key "name" in C:xampphtdocsGroceryListGeneratorPagesaddsMeal.php on line 3.

The console logs the data was sent successfully…

2

Answers


  1. Try modifying your PHP code to check if the ‘name’ key exists before accessing it:

    <?php
        if(isset($_POST['name'])) {
            $name = $_POST['name'];
            echo $name;
        } else {
            echo "No name parameter received.";
        }
    ?>
    

    This will prevent the warning and handle cases where the ‘name’ parameter is not received properly.

    Login or Signup to reply.
  2. As a brief and quickly written example of a single page jQuery/PHP app perhaps the following might help clarify some of the points made above.

    <?php
        error_reporting( E_ALL );
        
        # logic test - only process ajax request if it is a POST request 
        # testing for key POST variables that you MUST have to contine 
        # makes sense.
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
            $_POST['name'],
            $_POST['colour'],
            $_POST['music'],
            $_POST['car']
        )){
        
            # ensure that no HTML before output 
            # is included in response
            ob_clean();
            
            
            # process AJAX request... do something interesting & send a response
            vprintf('The computer says: "<span>%s</span>" drove a "<span>%s %s</span>" 
            way too fast whilst listening to "<span>%s</span>" full blast', $_POST );
            
            /*
                update db, read from db, create images etc etc
            */
            
            # exit/die - ensure the whole HTML page 
            # does not become part of the response
            exit();
        }
    ?>
    <!DOCTYPE html>
    <html lang='en'>
        <head>
            <meta charset='utf-8' />
            <title>Single page basic jQuery/Ajax to PHP script.</title>
            <script src='//code.jquery.com/jquery-latest.js'></script>
            <style>
                div span{ color:red }
            </style>
        </head>
        <body>
            <div></div>
            <script>
                $.ajax({
                    type:'POST',
                    /* 
                        adding the `dataType:"json"` means you expect JSON
                        - which is fine but omitted here as response is
                        HTML
                    */
                    url:location.href,
                    data: ({
                        'name':'Emma',
                        'colour':'bright red',
                        'car':'Jaguar XKR',
                        'music':'The Dead Kennedys'
                    }),
                    success:function(r) {
                        document.querySelector('div').innerHTML=r;
                    }
                });
            </script>
        </body>
    </html>
    

    Which outputs a nonsense string:

    The computer says: "Emma" drove a "bright red Jaguar XKR" way too fast
    whilst listening to "The Dead Kennedys" full blast

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search