简体   繁体   中英

AJAX + PHP Form not passing variables?

So normally I can get my ajax to work without any issues however for some reason my script isnt passing variables through to my PHP form. Ive been trying to debug for a while and am hoping a fresh set of eyes can point out whatever dumb error I got going on (i stripped it to bare bones for simplicity, this wont pass variable).

AJAX + FORM

$('#formid').on('submit', function(e){
   e.preventDefault(); 
   $.ajax({ 
      type: "POST",        
      url: 'page.php', 
      data: $(this).serialize(),
      success: function(data) {
        alert(data);
      }
   });
});


 <form id="formid" method="post">
   <input type="text" name="name">
   <input type="submit" value="Add">
 </form>

PAGE.php

//Get Variables
$name = $_POST['name'];

echo 'Name is: '.$name;

This should display an alert that says 'Name is (whatever the user puts in the form)'
However it does not echo back what the user submits in the form. Can anyone see something wrong with this script?

Something is wrong with posting the data back to the php page data: $(this).serialize()

The code looks clean, however there may be an issue with context when doing $(this).serialize() inside the ajax function. It may be better to save your data to a variable first. The result would look something like this:

$('#formid').on('submit', function(e){
    e.preventDefault();
    var my_data = $(this).serialize();
    $.ajax({ 
      type: "POST",        
      url: 'page.php', 
      data: my_data,
      success: function(data) {
        alert(data);
      }
    });
});

If this doesn't work then it may actually be an issue with the PHP side.

EDIT: Added rest of JS to be more concise and clear.

您应该将表单方法设置为POST:

<form id="formid" method="post">

Your code seems to be ok. $(this).serialize() should not be the problem, but if you think so, you can give an id to the text input and try data: {name: $('#your-input-id-here').val()} .

An other thing could be that e.preventDefault(); may not be working properly. Try to place it after the ajax call or replace it by return false; after the ajax call.

Thank you for all the responses, I have no idea why but adding the form in front of the id made it work. $('form#formid') I must have duplicate IDs on my page without realizing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM