Undefined index

on laravel framework i want to build api that post json
this is my code

<html>
<head>
<title>Employees add</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $("@submit").click(function(){
        $.ajax({
            url: "post.php",
            type: "post",
            data: {
                message: $("#message").val(),
                firstname: $("#firstname").val(),

            },
            datatype: "JSON"
            success: function (jsonstr){
                $("#result").text(JSON.stringfy(jsonstr));
            };
        });
    });
});
</script>
</head>
<body>
    <h1>Employees</h1>
    <form name="em" id="em" method="post">
    message: <input type="text" name="message" id="message">
    firstname: <input type="text" name="firstname" id="firstname">
    <input type="button" value="submit" name="submit" id="submit">    
    </form>
</body>
</html>

and I want to post the json into the post.php page

<?php
$message  = $_POST["message"];
$firstname  = $_POST["firstname"];
if(asset($message)){
    $data = array([
        "User message"  => $message,
        "User firstname"  => $firstname,
    ]);
    echo json_encode($data);
};
?>

but I get this err in the post.php code saying

You should test to see whether the array variables exist prior to using them, using the isset() function (you seem to have a typo a bit later, unless you also have an asset() function defined somewhere).

What do you see if you var_dump($_POST) at the start of your PHP code? I’m not big on Ajax code but I can’t see anything obvious wrong there.

ETA - reading elsewhere, it might be because you have the line

datatype: "JSON"

in there, which sends the data in a way that doesn’t instantly extract in the $_POST array. Remove that line and see what happens. Doesn’t it need a comma on the end anyway?

EATA - check for typos. As well as the one I mentioned in your PHP code, there’s another in the JS that deals with the return from the PHP code.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.