0

I was having difficulty calling the necessary jQuery functions in php so I added them to the javascript, but the method I’m familiar with (the success function) prevents the php from performing anything other than the INSERT INTO and SELECT queries. How would I change this script so that it completes the php, and/or how would I combine the code so that the following can be accomplished?

Validates form (with separate rules for Men and Women)

If validation is successful: Both Genders: parent.close_field('notice'); (currently only works in javascript)

If Gender is Female:

  • INSERT information into customer_info table
  • Identifies user_id assigned to this account
  • Redirects user to the next page (currently in both php & javascript)

If Gender is Male:

  • Generates email notifying me of the request
  • INSERT information into invite_requests table
  • Echo message to Men (currently in both; Preferred method is in php)
  • Close Fancybox iframe (currently only works in javascript)

I am using fancybox2 and this jQuery validation plugin http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Javascript

var $custInfo = $("#customer_info");
$(document).ready(function () {
  var validator = $custInfo.validate({
    rules: {...},
    messages: {...},
    errorLabelContainer: "#messageBox",
    submitHandler: function () {
        $custInfo.ajaxSubmit({
            success: function () {
                if ($('input[name=gender][value=female]').is(':checked')) {
                    parent.close_field('notice');
                    window.location.href = "page1.html";
                } else if ($('input[name=gender][value=male]').is(':checked')) {
                    parent.close_field('notice');
                    parent.$.fancybox.close();
                    alert("This isn’t available yet for men, but we’ll send you an invitation as soon as it is");
                }
            }
        });
    }
  });
  $custInfo.find("input[name=gender]").change(function () {
    if ($(this).val() == "male") {
        $custInfo.submit();
    }
  });
}); 

PHP

<?php
//Start session and connection to database goes here
//Function to sanitize values received from the form goes here     
$gender = $_POST['gender'];
if ($gender==="female" ) {
    // INSERT information into customer_info table    
   $qry = "INSERT INTO customer_info(fname, lname, gender, zip, email, phone, terms, security_question, security_answer, participating_retailers, notify_new_items, notify_promotions, priority1, priority2, priority3, priority4, priority5, gift_privacy, user_name, password, Quickfill)      VALUES('$_POST[fname]','$_POST[lname]','$_POST[gender]','$_POST[zip]','$_POST[email]','$_POST[phone]','$_POST[terms]','$_POST[security_question]','$_POST[security_answer]','$_POST[participating_retailers]','$_POST[notify_new_items]','$_POST[notify_promotions]','$_POST[priority1]','$_POST[priority2]','$_POST[priority3]','$_POST[priority4]','$_POST[priority5]','$_POST[gift_privacy]','$user_name','".md5($_POST['password'])."','$_POST[Quickfill]')";
       $result = @mysql_query($qry);     
    if($result) {   

// Identifies user_id assigned to this account
          $qry="SELECT * FROM customer_info WHERE user_name='$user_name' AND password='".md5($_POST['password'])."'";
          $result=mysql_query($qry);            
    if($result) {
        if(mysql_num_rows($result) == 1) {
            session_regenerate_id();
            $member = mysql_fetch_assoc($result);
            $_SESSION['SESS_USER_ID'] = $member['user_id'];
            $_SESSION['SESS_USER_NAME'] = $member['user_name'];
            session_write_close();
// Redirects user to the next page
            header("location: page1.html");
            exit();
        }else {  //user_name failed
            header("location: login_failed.html");
            exit();  }   
    }else { die("Unable to access your account (Error Message 1)");   }    
    }else { die("Unable to access your account (Error Message 2)");   } 
  }   
// If Gender is Male    
  else { 
// Notify us of request via email    
$sendto  = "info@click2fit.com";$userfname = $_POST['fname'];$userlname = $_POST['lname'];$usermail = $_POST['email'];$gender = $_POST['gender'];$subject  = "Invite Request - " . ($gender) . " ";
// INSERT information into invite_requests table
   $qry = "INSERT INTO invite_requests(fname, lname, gender, zip, email, phone, terms, participating_retailers, notify_new_items, notify_promotions, priority1, priority2, priority3, priority4, priority5, gift_privacy, user_name, password, Quickfill)         VALUES('$_POST[fname]','$_POST[lname]','$_POST[gender]','$_POST[zip]','$_POST[email]','$_POST[phone]','$_POST[terms]','$_POST[participating_retailers]','$_POST[notify_new_items]','$_POST[notify_promotions]','$_POST[priority1]','$_POST[priority2]','$_POST[priority3]','$_POST[priority4]','$_POST[priority5]','$_POST[gift_privacy]','$user_name','".md5($_POST['password'])."','$_POST[Quickfill]')";
    $result = @mysql_query($qry);
 // Echo message to Men
  echo "<p><strong>Click2Fit is not yet available for men, but we'll be sure to send an invitation as soon as it is</strong></p>"; 
// Redirects user - This should be replaced with the function which closes the fancybox iframe
  header("location: home.html");
exit();     
    }
?>
Chaya Cooper
  • 2,566
  • 2
  • 38
  • 67
  • Not question related, but you should really protect your db with PHP PDO. http://www.php.net/manual/en/book.pdo.php Don't do mysqli prepared statements. They suck. –  Dec 01 '12 at 00:44
  • Or use something like Codeigniter and forget about spaghetti code. Just a though... – elclanrs Dec 01 '12 at 00:48
  • 1
    Also, it looks like you're only dipping your toe into AJAX. Go all in. For your site to act exactly as the same server-side looking dull monster I'm sure it is now, you'll only need 30-50% of the lines of code you're currently using with total AJAX. If you ask me, server-side on the client is dead except for the most basic initial presentation tasks. Keep PHP at the server, jQuery on the client, and use AJAX to pass info between the two. Fill the saved lines with client-side awesomeness. –  Dec 01 '12 at 00:55
  • 1
    @JoeCoderGuy: Now that I have a better understanding of the role AJAX plays (thanks to Logan Besecker's explanation below), your comment is both really helpful and a good reason to figure AJAX out :-) – Chaya Cooper Dec 01 '12 at 02:52
  • 1
    It's made me love webapp programming again. You should look into json too just to understand the format of your transmissions. Once you go the total AJAX route, you'll also run into the problem of doing both http and https on the same page. You might as well go all https. The speed u lose in https is more than made up for with AJAX. I tried to get CORS to work, but chrome wouldn't take it. Use fetchall(fetch::assoc) to put your data into a var in php, and send it directly with json_encode back to jquery. You're going to absolutely love it! –  Dec 01 '12 at 03:08
  • @JoeCoderGuy: You've given me a lot of really great info :-) I may not have the time to figure out both AJAX and PHP PDO now, so I'm curious which one you think is more important to focus on? (my primary goal is creating moderately complex database queries, and at the moment we're using mySQL) – Chaya Cooper Dec 01 '12 at 16:00
  • PDO's easy. You're already doing mysqli. This is probably the most complex it'll get for you: http://stackoverflow.com/questions/920353/php-pdo-can-i-bind-an-array-to-an-in-condition Now your database is secure. -- AJAX = easy. Your code above is actually more complex. It's really as easy as this: http://williamjxj.wordpress.com/2011/10/02/jquery-json-and-phpjson_encode-example/ Just pass variables back and forth via $.ajax(). Process on PHP, manipulate the display on jQuery. It looks like you already know jQuery & PHP, so you're already there, u just don't know it yet. –  Dec 01 '12 at 16:04

1 Answers1

1

It's important to understand that javascript is a client-side language(meaning it runs in the user's browser) and php is a server-side language(meaning that it runs on your server). In order to get javascript and php to interact with each other, you're going to need to use AJAX.

since you're already using jQuery, I would suggest you check out their AJAX api. Essentially, every time you want to call a php function from within your javascript code, you're going to have something along the lines of this:

$.ajax({
  type: "POST", /*usually POST, but it can also be GET and some other HTTP requests in certain browsers*/
  url: "some.php", /*the url of the php which processes your data*/
  data: { name: "John", location: "Boston" } /*the data you want to pass to the server.  It will be contained in the $_POST array because of the 'type: "POST"' line above*/
}).done(function( msg ) {
  alert( "Data Saved: " + msg ); /*'msg' is what server send back to you while the contents of the function are what you do once the server finishes.  You can change the variable name, msg, as well as the function contents to suit your needs */
});
Logan Besecker
  • 2,733
  • 4
  • 23
  • 21
  • Thank you so much for explaining that :-) Even though I've used countless tutorials and samples, I never understood that basic piece of information – Chaya Cooper Dec 01 '12 at 01:59
  • glad to help, it's a common misunderstanding among new web developers. Let me know if you have further questions :) – Logan Besecker Dec 01 '12 at 02:03
  • That's really sweet of you to offer, and I may take you up on it :-D – Chaya Cooper Dec 01 '12 at 02:42
  • 1
    I don't know what the columns that customer_info are, but if you print json_encode $result, you can access the columns something like msg[0].id for id, msg[0].column1 for column1 etc. Use the chrome console to examine your json data more closely. You can see the individual ajax requests under Network. In Logan's case, it'll show up as "some" when you fire it. –  Dec 01 '12 at 03:14