0

I've gotten the hang of using PHP and javascript (as well as jQuery and some other libraries) fine.

The problem I have is how to properly exchange data. I know I can use POST and GET, but I usually only manage to do one sided communication, so I either send something to the server and let it work with the data (usually saving to a DB) or send the user over to a php page with some parameters.

What I need to do specifically is check our database to see if the user is already registered or not, and then warn the user with something such as "this email address is already in use".

I have this simple input form in my main page for registration:

<form>
    <input type="text" name="name" placeholder="Name:" required="required">
    <input type="email" name="email" placeholder="email:" required="required">
    <input type="text" name="cel" placeholder="cel:" required="required">
    <input type="submit" name="submit" formaction="register.php" value="reg">
</form>

Over on register.php I know what I need to do to check if the email address exists in the DB, but I have no idea how to send this information back to the client. I use a mySQL DB, currently testing in the localhost with xampp.

Kiloku
  • 474
  • 3
  • 7
  • 14
  • What you want is called `ajax`. With jQuery, you can use `$.post` or `$.get` or even `$.ajax` – Justin Iurman Aug 07 '14 at 20:06
  • 1
    Ajax to the rescue. Submit this form via Ajax, have your register.php code hit the DB and do a check, if email address already exists, echo a response, in your Ajax call process that response accordingly. Here's another answer with details http://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax – Josh KG Aug 07 '14 at 20:07

1 Answers1

2

You can use ajax to post to your server, and respond accordingly.

$.ajax({
  type: "POST",
  url: "register.php",
  data: data, // your form data goes here
  success: function(result_of_query) {
      // show alert that "this email address is already in use" based on result_of_query.
  },
  dataType: dataType
});
jh314
  • 24,533
  • 14
  • 58
  • 79
  • What should I do in register.php to have the data sent back to the client, though? How do I define the `result_of_query` for the `success` function? – Kiloku Aug 07 '14 at 20:57
  • 1
    In `register.php`, you take in some post parameters like usual, do your db query, and print out the result (printing out as JSON is a good choice). Then `result_of_query` will contain the JSON that your php script outputs. – jh314 Aug 07 '14 at 21:00