Grow your CSS skills. Land your dream job.

Need help converting Standard PHP Post request to AJAX…

  • # April 13, 2012 at 3:52 am

    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…

    here is my form & php

    HTML:






    PHP:


    < ?php
    if (isset($_POST)) {
    if (!empty($_POST)) {
    if ($_GET == 'newCategory') {
    $categories = $_POST;
    $query = "SELECT * FROM categories WHERE category ='$categories' ";
    $result = mysql_query($query) or die(mysql_error());
    if (mysql_num_rows($result)) {
    echo '';
    } 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 "";
    }
    }
    } else {
    echo "";
    }
    }
    ?>
    # April 13, 2012 at 8:20 am

    Anyone who isn’t a complete idiot spamming with blackhat seo tactics(that don’t even work!) want to try?

    # April 13, 2012 at 11:50 pm






    < ?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 ) && $_GET == 'newCategory' ){

    // remove any spaces
    $categories = str_replace( ' ','',$_POST );

    // 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:nt".
    // using newline+tab to concatenate helps format the message nicely
    implode( "nt",$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:nt".
    implode( "nt",$added );
    }

    // print the message (ajax response)
    print $return; exit;

    }
    # April 14, 2012 at 1:06 am

    @traq Slap my ass and call me betty…That is more than i expected, but DEFINITELY appreciated.

    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…






    # April 14, 2012 at 1:32 am

    no prob, it was fun

    …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 ) ){

    switch( $_GET ){

    // 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 );
    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 ) ){
    $ajaxAction = 'ajaxAction_'.$_GET;
    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 )

    function ajaxAction_addCategory(){
    /* ... */
    }

    function ajaxAction_removeCategory(){
    /* ... */
    }

    /* ...etc. ... */
    # April 14, 2012 at 1:36 am

    also, all of the HTML below is disappearing after the request has been completed…do you know why that is?

    all of the HTML below “what”?

    # April 14, 2012 at 1:41 am

    Well, on the actual page…I have it structured as followed:



    Manage Categories


    Add New Category


    < ?php ...... ?>

    Remove Category


    < ?php ...... ?>

    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.

    # April 14, 2012 at 1:55 am

    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:


    Manage Categories


    Add New Category


    < ?php ...... ?>

    Remove Category


    < ?php ...... ?>

    do THIS:

    < ?php

    $new_category_stuff = phpThatMakesHTML();
    $remove_category_stuff = phpThatMakesOtherHTML();

    $html = '

    Manage Categories


    Add New Category

    ';
    $html .= $new_category_stuff;
    $html .= '

    Remove Category

    ';
    $html .= $remove_category_stuff;
    $html .= '
    ';

    // * all done *
    print $html;
    ?>

    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

    # April 14, 2012 at 1:58 am

    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.

    # April 14, 2012 at 2:04 am

    I edited my post above, in case you missed it.

    # April 14, 2012 at 2:27 am

    @traq

    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….

    # April 15, 2012 at 12:34 am

    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:




    and on the php side

    < ?php

    if( !empty( $_GET ) && $_GET == 'newCategory' ){

    // check for ajax-ification
    $ajaxRequest = isset( $_GET )? TRUE: FALSE;

    // 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. ...
Viewing 12 posts - 1 through 12 (of 12 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".