1

I'm working on a webpage that features a popup window that prompts the user for his/her email address. The data should then be uploaded to a database upon submission.

However, the email address is not uploaded to the database and I am not sure why. A database connection is definitely established and no error messages are yielded.

I'm a real beginner at using AJAX/jQuery.

Inside index.php:

<form form id="email_submit" action="insert.php" method="post" target="_top">

   <label>Email Address</label>
   <input type="text" name = "emailaddress" />
   <input type="submit" value="Add Email" onClick="send_data_to_server()">
</form>

Inside insert.php:

$username = "root";
$password = "root";
$hostname = "localhost";
$database = "emails";

$dbhandle = mysql_connect($hostname, $username, $password)
 or die("0");
echo "Connected to MySQL <br>";

$selected = mysql_select_db("emails", $dbhandle)
 or die("0");
echo "connected to db <br>"; 

$youremail = $mysqli->real_escape_string($_POST["emailaddress"]); 
echo "$youremail";
mysql_query("INSERT INTO email_table (emailAddress) VALUES ('$youremail')");
echo json_encode($youremail);

The AJAX script (placed at the end of the index page body):

function send_data_to_server() {

   $("email_submit").submit(function (ev) {
       ev.preventDefault();
       $.ajax({
           type : 'POST',
           url : "insert.php",

           data  : { "formData" : $("#email_submit").serialize() },
           datatype : 'html',
           success: function(data) {
               alert(data);
           }
       });
   });
 }

Output on the webpage:

Connected to MySQL 
connected to db 

Any help is appreciated.

CarlyQ
  • 81
  • 7

4 Answers4

1

Your script part is wrong. You have not properly closed the functions. It should be more like this

function send_data_to_server() {

    $("email_submit").submit(function (ev) {
        ev.preventDefault();
        $.ajax({
          type : 'POST',
          url : "insert.php",

          data  : { "formData" : $("#email_submit").serialize() },
          datatype : 'html',
          success: function(data) {
              alert(data);
          }
        });
    });
}

That is why you are getting the error

SyntaxError: Unexpected token '}'. Expected ')' to end a argument list.

  • i still get an error message of TypeError: null is not an object (evaluating '$("email_submit").submit') – CarlyQ Jun 21 '15 at 09:42
0

First, you can put the ajax function at the end of the file between <script></script> tags. Second, edit your function and use serialize() method to submit forms thought jquery. Add a id to your form like

<form id="email_submit" action="insert.php" method="post" target="_top">

and edit the function like this

 $.ajax({
  type  : "POST",
  url   : "insert.php",
  data  : $("#email_submit").serialize(),
  datatype : 'html',
  success: function(data) {         
    alert(data);
  }
});

Also don't forget to sanitize your $_POST variable value with real_escape_string

Allkin
  • 1,099
  • 9
  • 18
  • i still get an error message of TypeError: null is not an object (evaluating '$("email_submit").submit') – CarlyQ Jun 21 '15 at 09:29
0

Add this inside code(show below) script tags <script></script>


$("form").submit(function (ev) {
        ev.preventDefault(); //prevent form from default submit
        $.ajax({
            type: 'POST',
            url: "localhost:8888/insert.php",
            data: $('form').serialize()
        }).done(function (data) {
            console.log(data);
        });
    });

use ev.preventDefault() to prevent form from default submitting
Remove formdata and use $('form').serialize(), it will serialize your form inputs.

Unni Babu
  • 1,839
  • 12
  • 16
  • i still get an error message of TypeError: null is not an object (evaluating '$("email_submit").submit') – CarlyQ Jun 21 '15 at 09:42
  • remove unwanted attributes from your form....just add this
    , no need of form id="email-submit"... :)
    – Unni Babu Jun 21 '15 at 09:45
  • please see my js fiddle for complete explanation.and dont forget to add jquery to your html page....i have done this for you... if you are satisfied dont forget to vote up :) tnx https://jsfiddle.net/uypgb6h0/ – Unni Babu Jun 21 '15 at 09:49
0

You are missing the # in your jQuery selector. It should be:

$("#email_submit").submit(function (ev) { ...

And then that might work, but it's kind of weird. You have a click handler for a button that creates a submit handler on the button's form. This has the potential to create multiple submit handlers for the form (one for each button click) which could have bad side effects. In practice, the button will usually only be clicked once, so you might get bugs that don't show up right away, and are hard to reproduce.

Instead, you should be creating the submit handler once, in the document ready handler. You don't need a click handler at all since clicking a button is just a way of submitting the form.

$(init);                                    // document ready event binding
function init() {                           // document ready handler function
    $("#email_submit").submit(ajaxSubmit);  // form submit event binding
}
function ajaxSubmit(ev) {                   // form submit handler function
    ev.preventDefault();
    $.ajax({
        type: 'POST',
        url: "insert.php",
        data: { formData: $(this).serialize() },
        datatype: 'html',
        success: function(data) {
            alert(data);
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="email_submit" action="insert.php" method="post" target="_top">
   <label>Email Address</label>
   <input type="text" name = "emailaddress" />
   <input type="submit" value="Add Email">
</form>
gilly3
  • 87,962
  • 25
  • 144
  • 176
  • when i add the # in my current code i get [Error] TypeError: null is not an object (evaluating '$("#email_submit").submit') send_data_to_server (localhost, line 640) onclick (localhost, line 172) – CarlyQ Jun 21 '15 at 10:30
  • and adding the script in the document ready handler makes the site go straight to the form acceptance (insert.php) – CarlyQ Jun 21 '15 at 10:31
  • I'm not sure what to tell you. In my code snippet, the submit handler is not executed until the button is clicked, and there are no errors (besides the one about the ajax call failing, which is expected in this environment). – gilly3 Jun 21 '15 at 10:42
  • you mean that i should put the AJAX script in the file header correct?? – CarlyQ Jun 21 '15 at 11:37
  • It doesn't matter very much where in the document you include your script. The AJAX code should be executed in an event handler - I suggest the form submit handler. You should bind the form's submit handler in the document ready handler. I've edited my answer a little, separating out the functions and adding comments, with the hope that it clarifies what I mean. It shows the distinction between an event handler and event binding. – gilly3 Jun 22 '15 at 15:39