vozzek Posted November 15, 2007 Share Posted November 15, 2007 Hi all, I've got a javascript function called addToCart() that gets called OnSubmit from my detail page. Since it's updating my SQL database (the shopping cart table) the function is 99% php... I just wrapped it up in javascript to make it easy to call from html. The problem I'm having is the function is adding the item to the shopping cart every time the page loads. Obviously I only want this to happen when and if the ADD TO CART button is clicked. Here is the <form> portion of the code that calls the addToCart script (the validateAddToCart script happening before it is working perfectly so in the interest of space I'm not going to include it). <form ACTION="view_cart.php" method="POST" name="addtocartform" id="addtocartform" onSubmit="return validateAddToCart(); addToCart()"> And now here is the javascript function addToCart, made up of the php code: <script type="text/javascript"> <!-- function addToCart() { <?php // current session id $sid = session_id(); // check if the product is already // in cart table for this session // (RecordID was passed as a variable from master to detail) $sql = "SELECT pd_id FROM tbl_cart WHERE pd_id = $RecordID AND ct_session_id = '$sid'"; //$result = dbQuery($sql); $result = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($result) == 0) { // put the product in cart table $sql = "INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ct_date) VALUES ($RecordID, 1, '$sid', NOW())"; $result = mysql_query($sql) or die(mysql_error()); } else { // update product quantity in cart table $sql = "UPDATE tbl_cart SET ct_qty = ct_qty + 1 WHERE ct_session_id = '$sid' AND pd_id = $RecordID"; $result = mysql_query($sql) or die(mysql_error()); } ?> } //--> </script> So I guess my question is, am I going about this the right way? I thought the php code would only get executed when the addToCart function was called, and not upon page load. Am I wrong? Thanks in advance. Quote Link to comment Share on other sites More sharing options...
emehrkay Posted November 15, 2007 Share Posted November 15, 2007 ajax - look into it Quote Link to comment Share on other sites More sharing options...
jeet_0077 Posted November 15, 2007 Share Posted November 15, 2007 Ideally a JavaScript function runs only after it is called through an event.(other than if it for body onload event ). But when you add pure php code inside JavaScript then your php code will run first irrespective of the javascipt. here the problem. You can use Ajax request for that. Quote Link to comment Share on other sites More sharing options...
s0c0 Posted November 15, 2007 Share Posted November 15, 2007 You absolutely HAVE to use Ajax. Quote Link to comment Share on other sites More sharing options...
vozzek Posted November 15, 2007 Author Share Posted November 15, 2007 I just took the Ajax tutorial on Tizag.com (love that site) but it was a bit short. If anyone has any other good Ajax resources, I'm open to suggestions. Thanks for the response everyone. Quote Link to comment Share on other sites More sharing options...
s0c0 Posted November 15, 2007 Share Posted November 15, 2007 Well you really need to get a book and just learn. You will have the basics of Ajax down in 2 months along with some nifty DOM tricks, less than that if you are smarter than me Basically your onsubmit in your example calls validateAddToCart(1); function. That 1 as the parameter in the function call you need that, its not the best way to do this, but it prevents you from needing a second function for your call back. I'm still learning so thats how I do it for now, someone here will criticize me for it I am sure. Anyways: <script type="text/javascript"> /** * setXMLHttpRequestObject - set the xml http request object */ function setXMLHttpRequestObject() { XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } } /** * httpPost - execute an HTTP POST */ function httpPost(url, params, stateChangeFunc) { if(XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", url, true); XMLHttpRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); XMLHttpRequestObject.setRequestHeader("Content-length", params.length); XMLHttpRequestObject.setRequestHeader("Connection", "close"); XMLHttpRequestObject.send(params); XMLHttpRequestObject.onreadystatechange = stateChangeFunc; } } /** * validateAddToCart - update shopping cart */ function addToCart(val) { if(val==undefined) { if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200) // handle http return { try { // put in your user notification here. You can figure that out yourself, use DOM or a dumb alert if lazy } catch(err) { alert('an error occured'); } } } else // make http request { var params = 'func=validateAddToCart' httpPost('YOUR_PHP_PAGE_HERE.php', params, validateAddToCart); } } </script> Now at the top of your PHP page have this: /* POST: determine which function the HTTP POST request wants */ if($_POST[func]) { switch($_POST[func]) { case 'validateAddToCart': PUT YOUR PHP CODE HERE OR YOUR PHP FUNCTION CALL break; } return; } If you can't figure that out then you need to get a book. You need to get a book anyways. Quote Link to comment Share on other sites More sharing options...
aosmith Posted November 16, 2007 Share Posted November 16, 2007 try adding this at the end of your php: *form name*.submit(); Quote Link to comment Share on other sites More sharing options...
vozzek Posted November 16, 2007 Author Share Posted November 16, 2007 sOcO, First off, I promise to get an Ajax book. Thanks for all the help. I took yet another Ajax tutorial and then went over your code until it made sense to me. I decided to insert your code into my site and tweak it around until I could get it to work. I think I'm close... but my database is still not being populated. I changed your naming convention of 'validateAddToCart' to 'checkAddToCart', only because I already had a validateAddToCart javascript function (to check user form input). I also thought maybe you missed the semicolon at the end of the var params = 'func=checkAddToCart' statement, but if it's not needed then I'm the one who's wrong. Here is the javascript on the detail page: <script type="text/javascript"> <!-- /** * setXMLHttpRequestObject - set the xml http request object */ function setXMLHttpRequestObject() { XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } } /** * httpPost - execute an HTTP POST */ function httpPost(url, params, stateChangeFunc) { if(XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", url, true); XMLHttpRequestObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); XMLHttpRequestObject.setRequestHeader("Content-length", params.length); XMLHttpRequestObject.setRequestHeader("Connection", "close"); XMLHttpRequestObject.send(params); XMLHttpRequestObject.onreadystatechange = stateChangeFunc; } } function addToCart(val) { if(val==undefined) { if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200) // handle http return { try { // put in your user notification here. You can figure that out yourself, use DOM or a dumb alert if lazy alert ("Successful"); } catch(err) { alert('An error occured'); } } } else // make http request { var params = 'func=checkAddToCart'; httpPost('cart_functions.php', params, checkAddToCart); } } //--> </script> As you pointed out, I also changed my <form> call to pass the '1' parameter as follows: <form ACTION="view_cart.php" method="POST" name="addtocartform" id="addtocartform" onSubmit="return validateAddToCart(); addToCart(1)"> Finally, I created a php file called cart_functions.php. Here it is: <?php /* POST: determine which function the HTTP POST request wants */ if($_POST[func]) { switch($_POST[func]) { case 'checkAddToCart': // current session id $sid = session_id(); // check if the product is already // in cart table for this session // (RecordID was passed as a variable from master to detail) $sql = "SELECT pd_id FROM tbl_cart WHERE pd_id = $RecordID AND ct_session_id = '$sid'"; //$result = dbQuery($sql); $result = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($result) == 0) { // put the product in cart table $sql = "INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ct_date) VALUES ($RecordID, 1, '$sid', NOW())"; $result = mysql_query($sql) or die(mysql_error()); } else { // update product quantity in cart table $sql = "UPDATE tbl_cart SET ct_qty = ct_qty + 1 WHERE ct_session_id = '$sid' AND pd_id = $RecordID"; $result = mysql_query($sql) or die(mysql_error()); } break; } return; } ?> I'm not sure if I did everything right, but it doesn't seem to be hitting the call. Do I need to include my cart_functions.php file at the top of the detail page? I didn't think that was necessary as it's being called directly during the http request. Please let me know if I missed anything. Thanks to all who read this. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.