0

I am trying to submit a form via ajax but it doesn't let me:

Ajax - samepage

<script type="text/javascript">
  $(document).on('submit','.subscribe',function(e) {
  $.ajax({ url: 'lib/common-functions.php',
     data: {action: 'subscribe'},
     type: 'post',
     success: function(output) {
                  alert(output);
              }
     });
  });
</script>

HTML - same page

  <form class="subscribe">
    <label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
    <label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail" > 
    <input type="submit" id="ssub" value="Subscribe">
  </form>

PHP - common-functions.php

<?php
  require_once('dbconn.php');
  function subscribe() {
    $name = $_POST['sname'];
    $email = $_POST['semail'];
    $db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ($sname, $email, 0)");
    echo "You have been subscribed";
  }
?>

EDIT added dbconn

$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
  echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}

In the console I get nothing. After I click submit and check the console. I can see in red how is actioning common-functions.php but doesn't do anything. Please help.

user3140607
  • 303
  • 4
  • 19

2 Answers2

3

You have to include the data youre accessing via Post in PHP in the data object in the $.ajax call:

$.ajax({ url: 'lib/common-functions.php',
 data: {action: 'subscribe',
        sname: $("#name").val()
        semail: $("#semail").val()},
 type: 'post',
 success: function(output) {
              alert(output);
          }
 });

});

Also your PHP function subscribe doesnt get called just by setting action:"subscribe" You have to check wheter $_POST["action"] is "subscribe":

if($_POST["action"]=="subscribe")
{
    subscribe();
}
Hoff
  • 243
  • 1
  • 6
  • I get Notice: Undefined index: action in common-functions.php after I added the if() after the function subscribe. – user3140607 Mar 19 '14 at 15:17
  • 1
    Sorry I misspelled the id of the name input fiel: It should be sname:$("#sname").val() – Hoff Mar 19 '14 at 15:18
3

TL;DR You need to do six things to fix the problems in the code you have provided. There are pitfalls with event propagation, scoping, and variable validation.

First, add this to your JavaScript: event.preventDefault(); event.stopPropagation();.

Second, submit your actual data.

Example showing these fixes:

$(document).on('submit','.subscribe',function(e) {
    e.preventDefault(); // add here
    e.stopPropagation(); // add here
    $.ajax({ url: 'lib/common-functions.php',
        data: {action: 'subscribe',
            sname: $("#sname").val(),
            semail: $("#semail").val()},
        type: 'post',
        success: function(output) {
            alert(output);
        }
     });
});

Third, actually call subscribe().

Fourth, you have a scoping problem: $db is a global, but you don't refer to it as one. That's why I added global $db; below.

Fifth, check the existence of your POST values.

Sixth, put quotes around your database values and escape them first.

<?php
require_once('dbconn.php');
function subscribe() {
    global $db;
    if(isset($_POST['semail'], $_POST['sname'])) {
        $name = $_POST['sname'];
        $email = $_POST['semail'];
        $db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($sname)."', '".$db->escape_string($email)."', 0)");
        echo "You have been subscribed";
    }
}
subscribe();
?>

NOTE: This just shows how to fix the code that you have posted. The code in the question, however, is wide open to SQL injection. You really should use prepared statements instead of relying on escaping of special characters.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • nice catch on event.preventDefault(); I been slacking today – xlordt Mar 19 '14 at 15:16
  • I get Notice: `Undefined index: sname , semail` and `Notice: Undefined variable: db` and `Fatal error: Call to a member function query() on a non-object in line `$db->query(`` – user3140607 Mar 19 '14 at 15:21
  • It should be sname:$("#sname").val() :) – Hoff Mar 19 '14 at 15:21
  • Undefined: errors, all you have to do is just define the vars like.. $db = ""; – xlordt Mar 19 '14 at 15:23
  • @user3140607 See my edit. You have a variable scoping problem. – elixenide Mar 19 '14 at 15:24
  • @xlordt It's updated. Now the fatal error is gone, but those 2 persist: Notice: Undefined index: semail and sname. + It's echoing the message that i put it to post even if i did not clicked the button. I think for the message I need to add what Holf told me, but the undefined index.... – user3140607 Mar 19 '14 at 15:27
  • Check my edit above; I was missing a comma. If the alert appears before you click the button, something is going on somewhere else in your code causing it to submit the form. – elixenide Mar 19 '14 at 15:30
  • Ok re-added your code and still getting `Notice: Undefined index: semail in lib\common-functions.php on line 6` and `Notice: Undefined variable: sname in lib\common-functions.php on line 7` and message echo ed `You have been subscribed` – user3140607 Mar 19 '14 at 15:36
  • It sounds like you are describing what happens when you call `common-functions.php` directly rather than through your AJAX call -- is that right? If so, then yes, you will have problems, because there's no POST data. You really should check whether the POST values exist with `if(isset($_POST['semail'], $_POST['sname']))` before doing the rest of the actions in `subscribe()`. – elixenide Mar 19 '14 at 15:40
  • use either `e` or `event` please – code-jaff Mar 19 '14 at 15:40
  • Added smth like this in common-functions.php http://pastebin.com/H3yW1HXy. But I am getting now `Notice: Undefined variable: email on line 11` and really don't get it why? Also the message stays. – user3140607 Mar 19 '14 at 15:49
  • Also undefined is `name` – user3140607 Mar 19 '14 at 15:55
  • Added an else condition and message + undefined variable dissapeared, but is still not inserting in the database after i submit. It only echo's the message in php style above the page. http://pastebin.com/hbF6KMQc – user3140607 Mar 19 '14 at 15:57
  • @user3140607 You're doing it backwards. You don't set the variables if the POST values exist, then insert into the database regardless. You check the existence first, then only if the values exist do you set the variables and do the insertion. See my edit to my answer. – elixenide Mar 19 '14 at 16:00
  • @code-jaff How exactly, i am a nob in ajax and jquery. Also in my console now I can see the entire HTML page with the message echo'ed on top. – user3140607 Mar 19 '14 at 16:01
  • Ed Cotrell ok, re-changed and still nothing inserted and message disappeared now after submit. In the console I can only see the html page. Also in the address bar the url looks like this after i hit submit `subscribe.php?sname=John&semail=hello@yahoo.com` which from my experience of previous scripts is because the action is not properly set. But don't know exactly. – user3140607 Mar 19 '14 at 16:04
  • That implies you are actually submitting (via GET), not submitting via AJAX. Did you add the `event.preventDefault();` line? Try adding `event.stopPropagation();` as well; that should stop the submission. – elixenide Mar 19 '14 at 16:11
  • ok added those 2. Still seeing in the console the html page, no message and no insertion in the dbs. – user3140607 Mar 19 '14 at 16:13
  • Can you explain what you mean by this: "Still seeing in the console the html page?" What about this: "no message?" – elixenide Mar 19 '14 at 16:14
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/50052/discussion-between-user3140607-and-ed-cottrell) – user3140607 Mar 19 '14 at 16:16