Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX not sending user-input from a form to PHP script

I've been trying to learn basic AJAX and Javascript by following various tutorials and examples online, but I've hit a wall. I'm trying to write a simple script to take user-input from a form using AJAX and submit it to a PHP script, which then just echos the input.

All I can really tell is that whatever is being entered is not going through, but I'm not at the point yet where I can say why. I've tried with both POST and GET, and with various dataTypes, with the same result. I'm certain that I'm doing something wrong or misunderstanding something, but I'm not sure what.

HTML/ AJAX

<form id="my_form">
    word <input type ="text" id="word1"/><br/>
    <input type="submit">
</form>
<script>
$(document).ready(function(){
    $("#my_form").on(function(e){
        e.preventDefault();
        var verb = $("word1").val();
        $.ajax({
            url: "testrun.php",
            data: "verb",
            type: "POST",
        });        
    });
});
</script>

PHP

if (isset($_POST['verb'])){
   $x= $_POST['verb'];
   echo $x;
}else { 
   echo "not working";
}

EDIT: I've tried a few of the suggestions thus far, copying and pasting them directly, and none of them have actually done anything that I can see. I think I'm starting to understand a bit more about how AJAX should work, based on the responses, but it's still not reaching the PHP for some reason. I've tried both with the AJAX/HTML in a separate file that calls to the testrun.php script and with putting everything into the testrun.php file and basically having it call itself with the AJAX, but neither approach has achieved anything.

If the AJAX that I've gotten from the responses is fine, then am I misunderstanding something in how the PHP should be set up in order to actually receive the POST data? I'm still rather lost.

like image 551
Ezra Avatar asked Feb 07 '23 16:02

Ezra


1 Answers

Three changes:-

1.var verb = $ ("word1").val(); need to be var verb = $ ("#word1").val();because its id (word1)

2.data: "verb", needs to be data: {"verb":verb},

3.form submission need to be correct so code given below (missing submit):-

Correct code:-

$(document).ready(function(){
    $("#my_form").on('submit',function(e){ // check here you have one missing `submit`
        e.preventDefault();
        var verb = $("#word1").val(); // remove space between `$` and `(`
        $.ajax({
          url: "testrun.php",
          data: {"verb":verb},
          type: "POST",
        });
   });
});
like image 57
Anant Kumar Singh Avatar answered Feb 10 '23 10:02

Anant Kumar Singh