user934902
user934902

Reputation: 1204

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()

Upvotes: 0

Views: 1191

Answers (4)

David
David

Reputation: 143

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.

Upvotes: 2

user934902
user934902

Reputation: 1204

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

Upvotes: 0

Fernando Prieto
Fernando Prieto

Reputation: 520

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.

Upvotes: 1

ivankoni
ivankoni

Reputation: 651

You should set form method as POST:

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

Upvotes: 1

Related Questions