MCAK66
MCAK66

Reputation: 1

Why is this jquery post request not working?

I'm learning AJAX right now, using jQuery. When I try to make this registration system it doesn't work:

$('#submitr').click(function () {
    var username = $('#usernamefieldr').val();
    var password = $('#passwordfieldr').val();
    var email = $('#emailfieldr').val();
    alert("ERROR");
    $.post("test.php", {
        input: "register",
        name: username,
        pass: password,
        mail: email
    }, function (data) {
        $("#test").html(data);
        alert(data);
    }).error(function () {
        alert("ERROR");
    });
});

but this function works:

$.post("test.php", {input: "Ajax is working!"}, function(data){
    $("#test").html(data);
});

What am I doing wrong?

Upvotes: 0

Views: 90

Answers (1)

Jonathan Eltgroth
Jonathan Eltgroth

Reputation: 839

Your bottom example works:

$.post("test.php", {input: "Ajax is working!"}, function(data){
    $("#test").html(data);
});

But your top doesn't. Put in dummy data you know will validate properly in test.php and run it:

$.post("test.php", {input: "register", name: "dummyName", pass: "dummyPass", mail: "[email protected]"}, function(data){
    $("#test").html(data);
    alert(data);
});

If it doesn't work and you know you've written that line of JQuery correctly, you likely have a problem in test.php. If it does, then add your variables one at a time:

$('#submitr').click(function(){

  var username=$('#usernamefieldr').val();

  $.post("test.php", {input: "register", name: username, pass: "dummyPass", mail: "[email protected]"}, function(data){
     $("#test").html(data);
     alert(data);
  });

});

Does it work? If so, add the next var...and so on. When it breaks you know where the issue is then.

You could also try:

$('#submitr').click(function(){
    $.ajax({
       url:'test.php'
       type: 'post'
       data: $('#form').serialize();
    }).done(function(data){
       $('#test').html(data);
       alert(data);
    }).fail(function(){
       alert('Oh No!');
    });
});

And then just pull the data you need from the $_POST in test.php:

<?php

   $name  = $_POST['name'];
   $pass  = $_POST['pass'];
   $email = $_POST['email'];

   // Do stuff here

?>

Upvotes: 1

Related Questions