0

I am working on a simple signup page using jQuery and PHP using AJAX.

Here is the script for making the ajax call:

<script>
    function submitForm(){
      var data1=$('#regform').serialize();
      $.ajax({
        type:'POST',
        url:'signup.php',
        data:data1,
        success: function(response){
          console.log(response);
          if(response==1)
            alert('taken');
            else if(response==2)
              alert('registered');
              else
                alert(response);
        }
      });
    }
  </script>

and the PHP script which responds to the call:

signup.php:

<?php
require_once 'dbconnect.php';
if($_POST) {
    $user_name = $_POST['user_name'];
    $user_email = $_POST['user_email'];
    $user_password = $_POST['password'];  
    try {
        $sth = $dbh->prepare("SELECT * FROM logindata WHERE email=:email");
        $sth->execute(array(":email"=>$user_email));
        $count = $sth->rowCount();   
        if($count==0){    
            $sth = $dbh->prepare("INSERT INTO logindata(username,email,pass) VALUES(:uname, :email, :pass)");
            $sth->bindParam(":uname",$user_name);
            $sth->bindParam(":email",$user_email);
            $sth->bindParam(":pass",$user_password);   
            if(!$sth->execute()) {
                echo "3";  
            } else {
                echo "2";
            }
        } else{    
        echo "1"; 
        }    
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
}
?>

using PDO.

dbconnect.php:

<?php
  $dbhost='localhost';
  $dbuser='root';
  $dbpass='';
  $dbname='ambitio';  
  try{
    $dbh=new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  }
  catch(PDOException $e){
    echo $e->getMessage();
  }  
?>

Problem: Neither of the two responses are being returned to the jQuery ajax call. I checked with console.log() but nothing shows up in the browser. Data gets stored in the MySQL database (checked it) which means that execute() is working fine in PHP, but still no alert is shown in the browser. 1 does get returned in case count evaluates to 0.

Also, when I refresh the form without actually submitting the form, I get the error POST 412 (Precondition Failed) at the browser console.

EDIT:Posted full php.

EDIT2: Apache access log

::1 - - [19/Jul/2016:23:51:55 +0530] "GET /ambitio/css/bootstrap.css HTTP/1.1" 304 - "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [19/Jul/2016:23:51:55 +0530] "GET /ambitio/css/overboot.css HTTP/1.1" 304 - "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [19/Jul/2016:23:51:55 +0530] "GET /ambitio/css/font-awesome.css HTTP/1.1" 304 - "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [19/Jul/2016:23:51:55 +0530] "GET /ambitio/js/jquery.js HTTP/1.1" 304 - "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [19/Jul/2016:23:51:55 +0530] "GET /ambitio/js/bootstrap.js HTTP/1.1" 304 - "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [20/Jul/2016:00:43:36 +0530] "GET /ambitio/signup.html HTTP/1.1" 200 1454 "-" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [20/Jul/2016:00:43:46 +0530] "POST /ambitio/signup.html HTTP/1.1" 200 1454 "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
::1 - - [20/Jul/2016:00:43:46 +0530] "POST /ambitio/signup.php HTTP/1.1" 200 1 "http://localhost/ambitio/signup.html" "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"

EDIT3: Form HTML markup:

<form method="post" id="regform" onSubmit="submitForm()">
      <input type="text" placeholder="Username" id="user_name" name="user_name" />
      <input type="email" placeholder="Email" id="user_email" name="user_email" />
      <input type="password" placeholder="Password" id="password" name="password" />
      <input type="password" placeholder="Retype password" id="rpassword" name="rpassword" />
      <input type="submit" id="submit"/>
</form>
np_complete
  • 154
  • 1
  • 9
  • post all your php code –  Jul 19 '16 at 18:50
  • It is not a asynchoronous call ? – msantos Jul 19 '16 at 18:51
  • @0x13a updated the question. – np_complete Jul 19 '16 at 19:00
  • @msantos more functions will be added later. – np_complete Jul 19 '16 at 19:02
  • Is display errors enabled on the server? If not, what does your apache access and error logs say? Is the server seeing the request? Does it log a failure before returning a result? – SuperJer Jul 19 '16 at 19:10
  • I've reformatted, after your last closing `}` add `else { echo 'No Post';}`. – chris85 Jul 19 '16 at 19:19
  • @SuperJer error log says nothing about the page. Posting the apache access log. – np_complete Jul 19 '16 at 19:22
  • Okay, I see that the server is being hit by the request with the given logs, and there are (presumably) no 500 errors. Now what does your browser debugger show for the request? In Firebug, you should see a `POST` line in the Console. In Chrome and others, you should get a line listed under the NET tab or something similar. What do you see in your Headers and Response sections for that (if any) request there? – SuperJer Jul 19 '16 at 19:28
  • @chris85 did it, but still nothing on the console. – np_complete Jul 19 '16 at 19:28
  • 1
    If Console tab is empty that's mean your submitForm wasn't call. – Quynh Nguyen Jul 19 '16 at 19:32
  • @SuperJer In Firebug, Headers: https://postimg.org/image/83k60hvvz/ and the Response contains the html code for the page containing the script. – np_complete Jul 19 '16 at 19:39
  • That is sending to `signup.html`? – chris85 Jul 19 '16 at 19:56
  • **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Jul 19 '16 at 20:00
  • @JayBlanchard It'll be done later. First I have to get this working. – np_complete Jul 20 '16 at 12:40
  • 1
    I hate when people say *"I'm not that far along..."* or *"This site will not be public..."* or *"It's only for school, so security doesn't matter..."*. If teachers and professors are not talking about security from day one, they're doing it wrong. Challenge them. They're teaching sloppy and dangerous coding practices which students will have to unlearn later. I also hate it when folks say, *"I'll add security later..."* or *"Security isn't important now..."* or *"Ignore the security risk..."*. If you don't have time to do it right the first time, when will you find the time to add it later? – Jay Blanchard Jul 20 '16 at 12:41
  • Your AJAX says `url:'signup.php'` why is it going to `.html`? – chris85 Jul 20 '16 at 12:44
  • @JayBlanchard I completely agree with what you said. Will do it right away. – np_complete Jul 20 '16 at 12:45
  • @chris85 The `signup.html` is the file which has the AJAX script, I have two files here: `signup.php` and `signup.html` . Am I doing something wrong here? – np_complete Jul 20 '16 at 12:47
  • Can you add your form markup to the question? – Jay Blanchard Jul 20 '16 at 12:47
  • Oh, I thought the screenshot was of the AJAX submit. What does the AJAX request look like? Just to confirm the AJAX is going to `signup.php`, not `.html`.. – chris85 Jul 20 '16 at 12:50
  • @JayBlanchard Added form markup. – np_complete Jul 20 '16 at 12:52
  • Have you watched the AJAX request / response in the browser's developer tools? Are there any errors reported? Are you running this on a web-server? – Jay Blanchard Jul 20 '16 at 12:53
  • @chris85 `signup.php` is receiving the AJAX request. https://postimg.org/image/4t4zs3kq7/ – np_complete Jul 20 '16 at 13:01
  • I'm running on localhost. There is no error related to the AJAX or the PHP but on refreshing the page generates `POST 412 (Precondition Failed)`. – np_complete Jul 20 '16 at 13:02
  • HTML markup of `signup.html` is returned as response as seen from firebug. – np_complete Jul 20 '16 at 13:04
  • Okay, what does the `POST` tab contain? – chris85 Jul 20 '16 at 13:05
  • @chris85 Here is the `POST` tab: http://postimg.cc/image/ju7a9d3fz/ – np_complete Jul 20 '16 at 13:22
  • I find it interesting that there really isn't anything listed for Response under the Headers tab. Check to see if the script is getting the post data by putting something like this at the top of your signup.php: `file_put_contents('postdata.txt', date('G:i:s ').print_r($_POST, true));` Run it, then move the line below your connection `require()`, then in your `if()` block, etc. That'll write the time, and the contents of your $_POST to the file. Useful for finding out where the breakdown is. – SuperJer Jul 20 '16 at 20:51

1 Answers1

2

Since your form doesn't contain a url to send to and your onSubmit-Handler (submitForm) doesn't return false, the form will actually get posted by the browser to the page it's currently on (which is most likely not capable of processing the form's POST data) and will just reload the login-form containing page.

The POST will likely be send to your ajax script as well, but your browser won't wait for the reponse, because it already moved on.

See https://html.spec.whatwg.org/multipage/forms.html#concept-form-submit for further details on the submit process.

Solution would be to either add return false to your submitForm function or to the onSubmit handler (;return false)

Jakumi
  • 7,105
  • 2
  • 11
  • 28