0

Everything works perfectly as is with the following files but in process.php if I echo the commented out messages after if (mysql_query($sql)), then form.php page goes to process.php page which is prevented in my_script.js - in other words some jQuery features from my_script.js don't work no more. Sometimes reverting back to the original echo lines still does not bring back the jQuery features until I erase and recreate the process.php file.

This is my first complete form, but what's happening is kinda spooky...am I missing something somewhere?

form.php

<?php
//filename - form.php
?>

<html>
<head><title>Registration Form: jQuery</title></head>
<body>

<form id="myForm" action="process.php" method="POST">
Username: <input type="text" name="username"/><br />
Password: <input type="password" name="pass"/><br />
First Name: <input type="text" name="fname"/><br />
Last Name: <input type="text" name="lname"/><br />
<button id="submit">register</button>
</form>

<div id="ack"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script type="text/javascript" src="script/my_script.js"></script>
</body>
</html>

db.php

<?php
//filename - db.php

// mysql_connect for process.php -
$conn = mysql_connect('myhost.mysql.com', 'formdb_user', 'pwd');
$db   = mysql_select_db('formdb');

?>

process.php

<?php
//filename - process.php

//capture errors
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

//initialize
//global $message;

//connect to formtable
include_once ('db.php');

//tried this file with mysqli method and parameters and it didin't solve the problem!
$username = mysql_real_escape_string ($_POST['username']);
$password = mysql_real_escape_string (md5($_POST['pass']));
$fname = mysql_real_escape_string ($_POST['fname']);
$lname = mysql_real_escape_string ($_POST['lname']);

$sql = "INSERT INTO `formtable` (`username`, `password`, `fname`, `lname`) VALUES ('$username', '$password', '$fname', '$lname')";

if (mysql_query($sql))
echo "Inserted Successfully";
//echo "Thank You! We'll Review Your Application.";
else
echo "Insertion Failed";
//echo "Submit Failed - Please Refresh Page And Try Again.";
//this method didn't help either - echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8');

?>

my_script.js

$("#submit").click( function() {
     $.post( $("#myForm").attr("action"),
             $("#myForm :input").serializeArray(),
             function(info) {
               $("#ack").empty();
               $("#ack").html(info);
                clear();
             });
    $("#myForm").submit( function() {
       return false;    
    });
});

function clear() {

    $("#myForm :input").each( function() {
          $(this).val("");
    });

}

EDIT

Everything works w/o any problem with the following:

if (mysql_query($sql))
echo "Inserted Successfully";
//echo "Thank You! We'll Review Your Application.";
else
echo "Insertion Failed";
//echo "Submit Failed - Please Refresh Page And Try Again.";

Problem starts when I use the following. Form data gets inserted to table but I get the success message on another page - the form's action page, process.php, which per the code in jQuery file, my_script.js, should not happen.

if (mysql_query($sql))
//echo "Inserted Successfully";
echo "Thank You! We'll Review Your Application.";
else
//echo "Insertion Failed";
echo "Submit Failed - Please Refresh Page And Try Again.";

Further when I try to reset back to the previous mode, sometimes things do not start working back correctly right away, takes a few minutes...

Ben
  • 45
  • 6
  • Unrelated, but you don't need `.each`, just write `$("#myForm :input").val("")`, it automatically loops. – Barmar Apr 30 '16 at 22:48
  • Your $post params aren't jiving jQuery.post( url [, data ] [, success ] [, dataType ] ) – Mistergreen May 01 '16 at 01:10
  • @Mistergreen - I am a noob on all this as I have admitted in my OP, but it seems even though the reqd AJAX params may be there, the format is missing - is that what you mean? If not can you pls show me how or perhaps provide a link to what you mean? – Ben May 01 '16 at 06:24
  • @Mistergreen The call is correct. `url = $("#myForm").attr("action")`, `data = $("#myForm").serialize()`, `success = function(info) ...`, and he omitted the optional `dataType` argument. – Barmar May 01 '16 at 08:38
  • I don't think it makes a difference in this case, but you shouldn't have `$("#myForm").submit()` inside `$("#submit").click()`. In general, it's wrong to bind one event handler inside another event handler, because you get multiple bindings when the first event occurs repeatedly. – Barmar May 01 '16 at 09:01
  • @Barmar - yes, I took it out and put `event.preventDefault();` after the first line that also got changed to `$("#submit").click( function(event) {`. Getting there :) – Ben May 03 '16 at 00:56
  • That's the right way. You could also put all the AJAX code in `$("#myForm").submit()` instead of the click handler. – Barmar May 03 '16 at 00:59
  • Yep, now that the gremlins are gone, my next step is to implement the right AJAX submit format...so that it's all clean to handle and maintain – Ben May 03 '16 at 01:09

1 Answers1

0

You're getting a PHP syntax error. When you have multiple statements in if or else, you need to wrap them in braces. If you omit the braces after if, and then put multiple statements, the else no longer matches up, so you get an error.

if (mysql_query($sql)) {
    echo "Inserted Successfully";
    echo "Thank You! We'll Review Your Application.";
} else {
    echo "Insertion Failed";
    echo "Submit Failed - Please Refresh Page And Try Again.";
}

I recommend you get in the habit of always using braces around your if/while/for/foreach bodies, even when they're just one line. See Why is it considered a bad practice to omit curly braces?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I'll try with curly braces even at one-liners, but I hope the section you picked from my code to illustrate your point above is just an example - as there's never the need for multiple lines especially the third line after `else` is just my comment. The point I was making there is - when I echo the second line instead of the first after `if`, jQuery cannot stop current page redirected to action url. – Ben Apr 30 '16 at 23:36
  • You said the problem happened when you uncommented those lines. If you did that without adding braces, the PHP script fails. When the script gets an error, the server returns a 500 error code, and the AJAX callback function doesn't run. – Barmar May 01 '16 at 00:57
  • My bad Barmar, I should have been more articulate, I am going to add edits at the end of my OP to make the problem clearer, hopefully... – Ben May 01 '16 at 05:25
  • Anyway, the good news is - I followed your recommendation to brace the one line `if` and `else` outputs with curly brackets respectively and it appears things are working at least in this file. But the remedy is not working in another file and if it continues to be a problem, I'll bring it up in a new posting as things are bit different there . For this one I'll just wait and see gremlins don't find their way back in and accept your answer. – Ben May 01 '16 at 06:11
  • So yes, everything is running ok for the last couple of days...beats me if it was me doing something goofy or would lack of curly braces on one liners create such a problem... but the thing gained here is good practice of always use curly braces :) – Ben May 03 '16 at 01:03
  • No, lack of curly braces would not cause a problem with one-liners. When I wrote my answer, I thought you were just uncommenting those lines, but not commenting out the line before it. – Barmar May 03 '16 at 01:05
  • Are you sure you had double quotes around the string `"Thank You! We'll Review Your Application.";`? If you put single quotes around it instead, you'll get an error because the apostrophe in `We'll` ends the string. – Barmar May 03 '16 at 01:07
  • On that I am sure...must be something else I was doing or not doing...thanks much for your help. – Ben May 03 '16 at 03:48