Toby
Toby

Reputation: 717

Submit a Form Using Jquery Ajax

Fiddle And Code:

$("form.signupform").submit(function(e) {
  var data = $(this).serialize();
  var url = $(this).attr("action");
  var form = $(this); // Add this line
  $.post(url, data, function(data) { 
    try {
        data = JSON.parse(data);
		$(.result).html(data.result + " Watchlist");

    } catch (e) {
        console.log("json encoding failed");
        return false;
    }
});
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="result"></p>
<form class="signupform" method="post" action="admin/signupinsert.php" onsubmit="this.onsubmit=function(){return false;}">

    <input type="text" name="firstname" />
	  <input type="submit" value="Sign Up"/>

</form>

admin/signupinsert.php code:

// Insert into DB code in PHP

$response = new \stdClass();
$response->result = "".$result."";
die(json_encode($response));

I am trying to submit this form using My Jquery Ajax Code. And the signupinsert.php file will return a value in $result variable. I am trying to print it inside <p class="result"></p>

But, the code re-directs users to signupinsert.php page.

What's wrong?

Upvotes: 3

Views: 11357

Answers (2)

Alex Andrei
Alex Andrei

Reputation: 7283

you must prevent the default action of submitting the form

$("form.signupform").submit(function(e) {

    e.preventDefault(); // <-- add this

    var data = $(this).serialize();
    var url = $(this).attr("action");

also, in your php file return proper JSON and avoid parsing the response in javascript with JSON.parse(data);

the output in your php file should look like this

$response = new \stdClass();
$response->result = $result;

header('Content-Type: application/json');
print json_encode($response);

and in your success handler just process the data parameter as a normal json object

$.post(url, data, function(data) { 
    $(.result).html(data.result + " Watchlist");
}

Also, just a curiosity, what is this supposed to do?

$response->result = "".$result."";

Update:
I just realized why you had most of the issues:

$('.result').html(data.result + " Watchlist");
  ^       ^

see the missing quotes

Upvotes: 3

Therichpost
Therichpost

Reputation: 1815

you are redirecting because of action:

action="admin/signupinsert.php"
var url = $(this).attr("action");

got me?

Upvotes: 0

Related Questions