I am kicking myself in the arse here because i can't for the life of me figure it out...this is supposed to be a quick and dirty project, but, I decided i want to try something new, and I have little to no experience with the AJAX methods in jQuery...Any help would be more than appreciated, thanks guys!
Again, I am wondering how to go about converting this standard request to AJAX using jQuery...
<?php if (isset($_POST['submit'])) { if (!empty($_POST['category'])) { if ($_GET['action'] == 'newCategory') { $categories = $_POST['category']; $query = "SELECT * FROM categories WHERE category ='$categories' "; $result = mysql_query($query) or die(mysql_error()); if (mysql_num_rows($result)) { echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>'; } else { // Simply cleans any spaces $clean = str_replace(' ', '', $categories); // Makes it possible to add multiple categories delimited by a comma $array = explode(",", $clean); foreach ($array as &$newCategory) { mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')"); } echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>"; } } } else { echo "<script>alert('Please Enter at Least One Category.')</script>"; } } ?>
<script src="your/copy/of/jquery.js"></script> <script> $( "#myAjaxForm" ).submit( function( e ){ var form = this; $.post( "categories.php?action=newCategory" ,$( form ).serialize() ,function( data,status,jqXHR ){ if( status == 'success' ){ alert( data ); form.reset(); }else{ alert( status ); } } ); e.preventDefault(); return false; } ); </script>
<?php // check 'action' first, since that determines what you're going to do // if you add more 'action's, you might use a "switch" statement instead if( !empty( $_GET['action'] ) && $_GET['action'] == 'newCategory' ){
// remove any spaces $categories = str_replace( ' ','',$_POST['categories'] );
// check if $categories contains a single name or a comma-separated list if( strpos( $categories,',' ) ){ $categories = explode( ',',$categories ); }
// even if it's a single name, we'll pretend it's an array anyway, // to make processing easier else{ $categories = array( $categories ); }
// remove empty values from $categories // print message (ajax response) if there are no non-empty values if( !( $categories = array_filter( $categories ) ) ){ print "Please Enter at Least One Category."; exit; }
// I'm using mysqli in this example: // the mysql extension is outdated and shouldn't be used for new stuff $DB = new mysqli( 'database host','username','password','database name' );
// loop through them all foreach( $categories as $category ){
// escaped value (for database queries) // this is VERY IMPORTANT // $x_category = $DB->real_escape_string( $category );
// check if category exists $SQL = "SELECT 1 FROM `categories` WHERE `category` ='$x_category'"; $R = $DB->query( $SQL ); if( $R->num_rows >0 ){
// category already exists; add name to reject pile $exists[] = $category;
}else{
// we're good, insert new category & add name to success list $SQL = "INSERT INTO `categories`( `category` ) VALUES( '$x_category' )"; $DB->query( $SQL ); $added[] = $category;
} }
// ready to write our return message $return = '';
// if any names were rejected, list them in the message if( !empty( $exists ) ){ $return .= "The Following categories already exist:\n\t". // using newline+tab to concatenate helps format the message nicely implode( "\n\t",$exists ). // this part of the message will be first (if present), // so we need a newline to keep it separate from the success part "\n"; }
// if any names were added, list them in the message if( !empty( $added ) ){ $return .= "The following categories were added:\n\t". implode( "\n\t",$added ); }
// print the message (ajax response) print $return; exit;
...except the part where I spent twenty minutes testing and getting super-frustrated because it JUST WASN'T WORKING before I realized I'd forgotten to include the jQuery library...
anyway,
<?php
if( !empty( $_GET['action'] ) ){
switch( $_GET['action'] ){
// list each case case 'addCategory': addCategory(); break; case 'removeCategory': removeCategory(); break;
// other cases, etc. ...
// ignore by default all requests that you don't expect default: break; }
}
// move all the procedural code from my example into its own function: function addCategory(){ $categories = str_replace( ' ','',$_POST['categories'] ); if( strpos( $categories,',' ) ){ $categories = explode( ',',$categories ); } else{ $categories = array( $categories ); } if( !( $categories = array_filter( $categories ) ) ){ print "Please Enter at Least One Category."; } /* etc., etc... */ }
function removeCategory(){ /* etc., etc... */ }
if you want to make it even easier, try this:
<?php
if( !empty( $_GET['action'] ) ){ $ajaxAction = 'ajaxAction_'.$_GET['action']; if( is_callable( $ajaxAction ) ){ $ajaxAction(); } else{ exit; } } // now, any function that you prefix with "ajaxAction_" // will be run automatically when you pass the function name // (without the prefix) via the query string // (e.g., ?action=addCategory )
Well, on the actual page...I have it structured as followed:
<div class="post"> <h1>Manage Categories</h1> <h2>Add New Category</h2> <?php ...... ?>
<h2>Remove Category</h2> <?php ...... ?> </div>
The AJAX request is solid...but on completion the 'Remove Category' Portion disappears completely...and once again, i put my head through a wall.
however, i do understand the other code you just put up as well, excellent excellent stuff...I am already learning a ton of stuff from it...In fact looking at it, if i put the PHP code at the bottom of the pages instead and use the function() method described above i think it may solve my issue.
if i put the PHP code at the bottom of the pages instead and use the function() method described above...
I would recommend the exact opposite, actually - it's okay to put function definitions at the very bottom, but you'd be better off if your entire script (the program logic) was at the top of the page, before any output (including, e.g., all HTML outside of your <?php ?> tags).
It might not affect your current script*, but as your scripts get more involved, you'll run into problems when you just echo things out whenever you "need" them. Usually a coder's first encounter with this is when they try to use sessions and get an error along the lines of "Cannot set session headers: headers already sent at line ...".
* actually, it would affect it - the whole point of having the if() block at the top of the page, and ending it with exit;, is to block any other markup that might otherwise be sent along with the ajax response.
The AJAX request is solid...but on completion the 'Remove Category' Portion disappears completely..
This actually sounds like the ajax isn't working, and the form is just submitting normally. When you submit the form, does your page URL change? Do you get a javascript alert afterwards, or is the message just in the body of the page?
-------------------------------
It's better, by far, to do all of your work first and then send it to the browser.
SO, instead of this:
<div class="post"> <h1>Manage Categories</h1> <h2>Add New Category</h2> <?php ...... ?>
I (almost) _never_ break out of <?php ?> (I use HEREDOC syntax instead for large blocks of HTML markup). You could also wrap your whole script, indiscriminately, in an output buffer (and people do do that), but it's a bit on the clumsy/hacky** side.
Thanks for that man, i really really appreciate it, my PHP knowledge is going to increase quite a bit this evening...I am going to read up on all the new info...Thanks again and again.
The URL is changing and the message is being printed to the page as it should be in the PHP script...if i remove the action from the form should the AJAX request still work? I am not sure how to tell either way....
if the URL is changing (also note that the example I gave you would show the ajax response in an alert() box, not in the page body), then one of two things is happening:
1) you're not preventing the default submit action (form submission). So, the ajax request is sent, but the form is submitted normally also, and you never see the ajax response because you already left that page (left it and came back to the same page again, but you still left it). The "normal" submission is treated like an ajax request by the php script, which exits after printing the specific response (hence your missing markup).
2) the ajax call is not being made in the first place, and the form is submitted normally as above.
I probably couldn't tell you which without seeing your page "live." Start by checking to make sure you don't have any javascript errors (and that you have jquery on the page ; ) of course). If you put the page live somewhere, feel free to give me the url and I'll take a look.
--------------------- This does illustrate some problems you run into when you mix your processing with your output:
-- You probably don't want to remove the action from the form -- it's nice to be able to use the form normally (e.g., if the user has javascript disabled).
-- You _do_ want one type of output when the form is accessed via ajax (only the response), and another via normal web browsing (the whole page, plus the response). You can't decide one way or the other if you have blocks of html that are output, alwaysnomatterwhat, at various places in your script.
We could modify my example above (and your form) to help determine the choice:
<form action="categories.php?action=newCategory" method="post"> <!-- etc., etc. ... notice the query string says "action=" --> </form> <script> $( "#myAjaxForm" ).submit( function( e ){ var form = this; $.post( "categories.php?ajax&action=newCategory" /* etc., etc. ... notice the query string also says "ajax" */ </script>
// etc., etc. ... // when you're ready to write the return message, // check how the request was made: if( $ajaxRequest ){ /* it was an ajax request; output message only and the exit */ }else{ /* it was a normal form submission; compose message but continue script and add message to HTML output later */ } // etc., etc. ...
Again, I am wondering how to go about converting this standard request to AJAX using jQuery...
here is my form & php
HTML:
PHP:
Thank you so much for improving the php as well! I wish there was some type of system to give props for the help!
I do in fact have other actions, how would i implement switch in regards to the script as is? for instance one other action is "removeCategory"...
as you can see it is as sloppy as the first...
...except the part where I spent twenty minutes testing and getting super-frustrated because it JUST WASN'T WORKING before I realized I'd forgotten to include the jQuery library...
anyway,
if you want to make it even easier, try this:
all of the HTML below "what"?
The AJAX request is solid...but on completion the 'Remove Category' Portion disappears completely...and once again, i put my head through a wall.
however, i do understand the other code you just put up as well, excellent excellent stuff...I am already learning a ton of stuff from it...In fact looking at it, if i put the PHP code at the bottom of the pages instead and use the function() method described above i think it may solve my issue.
I would recommend the exact opposite, actually - it's okay to put function definitions at the very bottom, but you'd be better off if your entire script (the program logic) was at the top of the page, before any output (including, e.g., all HTML outside of your <?php ?> tags).
It might not affect your current script*, but as your scripts get more involved, you'll run into problems when you just echo things out whenever you "need" them. Usually a coder's first encounter with this is when they try to use sessions and get an error along the lines of "Cannot set session headers: headers already sent at line ...".
* actually, it would affect it - the whole point of having the if() block at the top of the page, and ending it with exit;, is to block any other markup that might otherwise be sent along with the ajax response.
This actually sounds like the ajax isn't working, and the form is just submitting normally. When you submit the form, does your page URL change? Do you get a javascript alert afterwards, or is the message just in the body of the page?
-------------------------------
It's better, by far, to do all of your work first and then send it to the browser.
SO, instead of this:
do THIS:
I (almost) _never_ break out of <?php ?> (I use HEREDOC syntax instead for large blocks of HTML markup). You could also wrap your whole script, indiscriminately, in an output buffer (and people do do that), but it's a bit on the clumsy/hacky** side.
** in a negative context
The URL is changing and the message is being printed to the page as it should be in the PHP script...if i remove the action from the form should the AJAX request still work? I am not sure how to tell either way....
alert()box, not in the page body), then one of two things is happening:1) you're not preventing the default submit action (form submission). So, the ajax request is sent, but the form is submitted normally also, and you never see the ajax response because you already left that page (left it and came back to the same page again, but you still left it). The "normal" submission is treated like an ajax request by the php script, which exits after printing the specific response (hence your missing markup).
2) the ajax call is not being made in the first place, and the form is submitted normally as above.
I probably couldn't tell you which without seeing your page "live." Start by checking to make sure you don't have any javascript errors (and that you have jquery on the page ; ) of course). If you put the page live somewhere, feel free to give me the url and I'll take a look.
---------------------
This does illustrate some problems you run into when you mix your processing with your output:
-- You probably don't want to remove the
actionfrom the form -- it's nice to be able to use the form normally (e.g., if the user has javascript disabled).-- You _do_ want one type of output when the form is accessed via ajax (only the response), and another via normal web browsing (the whole page, plus the response). You can't decide one way or the other if you have blocks of html that are output, alwaysnomatterwhat, at various places in your script.
We could modify my example above (and your form) to help determine the choice:
and on the php side