Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Oct 2010
    Posts
    17
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Can't get php and jquery/ajax to play nice

    Hi all,

    I'm very new to php and jquery and ajax but I keep learning and I hope someone can help me.

    I have implemented a blog commenting system on my web site to enable users to post comments to blog articles along with form validation. I have had success doing this with php

    But of course with php the page has to reload in order for the comment to show. I am trying to implement Jquery's ajax method in order to try to get comments to load without reloading the page.

    I am using Jquery Library version 1.4.2. When I try to implement the jquery code, something in process.php script causes jquery1.4.2.js file to throw an error on line 5252.

    Line 5252 in the jquery library file is this:

    Code:
    try {
    5252 xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
    Hope that makes sense.

    Here is the jquery code I'm trying to implement.

    Code:
    $(function() {
            $('div.cform input#submit').click(function() {
            $('div.cform').append('<img src="../images/pageElements/ajax-loader.gif" class="loaderIcon" alt="Loading..."/>');//this will simulate processing by loading an animated gif
    
            var name = $('input#name').val();
            var email = $('input#email').val();
    	var website = $('input#website').val();
            var comments_body = $('textarea#comments').val();
    	var aid = $('input#id').val();
    
            $.ajax({
                type: 'post',
                url: 'process.php',
                data: 'name=' + name + '&email=' + email + '&website=' + website + '&comments=' + comments_body + '&id=' + aid,
    
                success: function(results) {
                    $('div.cform img.loaderIcon').fadeOut(1000);//fade out processing simulation image
                    $('ul#response').html(results);//display succcess or failure errors.
                }
            }); // end ajax
        });
    });
    When using Firebug, the form is processed by jquery but the information doesn't seem to be passed off to process.php because the data is not added to the database table.

    Here's my php script which functions without implementing Jquery

    PHP Code:
    <?php

        mysql_connect
    ("localhost""root""m3gatr0n");
        
    mysql_select_db("masscic");

        
    //initialize the variables for the form if users want to post a comment
        
    $name ='';
        
    $email ='';
        
    $website ='';
        
    $comments ='';
        
    $id ='';
        
    $regExp ='';
        
    $errorMsg ='';
        
        if (isset(
    $_POST['submit'])) {

        
    //grab the form data
        
    $curnum 0//will itemize the number of errors we have
        
    $name $_POST['name'];
        
    $email $_POST['email'];
        
    $website $_POST['website'];
        
    $comments $_POST['comments_body'];
        
    $id $_POST['aid'];

        
    //do some injection cleaning
        
    $name stripslashes($name);
        
    $email stripslashes($email);
        
    $website stripslashes($website);
        
    $comments stripslashes($comments);
        
        
    $name strip_tags($name);
        
    $email strip_tags($email);
        
    $website strip_tags($website);
        
    $comments strip_tags($comments);
        
        
    $regExp '/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/';

    //check for errors    
         
    if (strlen($name) < 2) {
              
    $curnum ++;
             
    $errorMsg['name'] = '<span style="color:#ff0000">'.$curnum.'. Your name is required</span>';
            }
         if (!
    preg_match($regExp$email)) {
              
    $curnum ++;
              
    $errorMsg['email'] = '<span style="color:#ff0000">'.$curnum.'. Please enter a valid email address</span>';
             }
         if (
    strlen ($comments) < 3) {
              
    $curnum ++; 
             
    $errorMsg['comments_body'] = '<span style="color:#ff0000">'.$curnum.'. You need to post a comment</span>';
            }
            
        
    $name mysql_real_escape_string($name);
        
    $email mysql_real_escape_string($email);
        
    $website mysql_real_escape_string($website);
        
    $comments mysql_real_escape_string($comments);     
                
    //done with error checking now perform the insert
        
    if (!$errorMsg) {
            
    $sqlInsert mysql_query("INSERT INTO comments(aid, name, email, website, comments_date, comments_body)                 VALUES('$id','$name','$email','$website', now(), '$comments')") or die (mysql_error());
            
            echo 
    '<li class="success"> Congratulations, ' $name '. Your comment was posted successfully! </li>';    
        }
        else {

            
    $response = (isset($errorMsg['name'])) ? "<li>" $errorMsg['name'] . "</li> \n" null;
            
    $response .= (isset($errorMsg['email'])) ? "<li>" $errorMsg['email'] . "</li> \n" null;
            
    $response .= (isset($errorMsg['comments_body'])) ? "<li>" $errorMsg['comments_body'] . "</li>" null;
            
            echo 
    $response;
        } 
    # end if there was an error sending
    }

    ?>
    Sorry this is so long but there's a lot of stuff going on as you can see.

    Thanks for any information.

  • #2
    Senior Coder Spudhead's Avatar
    Join Date
    Jun 2002
    Location
    London, UK
    Posts
    1,856
    Thanks
    8
    Thanked 110 Times in 109 Posts

    Question

    Couple of things.

    First, your code isn't stopping the default behaviour of the submit button. Which means your page is going off to wherever the form is aimed at, regardless of your js code. You'd be better off tying your js to the form's submit event, then you can use jQuery's preventDefault() to halt the form submission.

    Second, the PHP is looking for a form element called "submit". That doesn't get sent with the AJAX.

    Finally, you can save yourself some time and trouble using jQuery's serialize() function to wrap the form up in a nice AJAX-friendly object. Just remember that any element you want it so send needs a name attribute set.

    Oh - and you may as well use $.post() instead of $.ajax().

    So, something like this:

    Code:
    $(function() {
            $('#your_form_id').submit(function(event) {
                    event.preventDefault(); // stop the form submitting
                    $('div.cform').append('<img src="../images/pageElements/ajax-loader.gif" class="loaderIcon" alt="Loading..."/>');//this will simulate processing by loading an animated gif
                    var data = $(this).serialize(); // $(this) represents the form object
                    $.post('process.php', data, function(results) {
                            $('div.cform img.loaderIcon').fadeOut(1000);//fade out processing simulation image
                            $('ul#response').html(results);//display succcess or failure errors.
                    });
            });
    });
    make sense?

  • #3
    New Coder
    Join Date
    Oct 2010
    Posts
    17
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi Spudhead,

    Thanks for replying.
    Some of what you are saying makes sense. I don't quite understand how stopping the default action of the form will allow the form to work.

    I don't think my form is aimed anywhere other than process.php specified in the jquery. The variables are being passed (I see the results in firebug under the "post" tab). I'm not specifying an action or a method in the form. Form code is below.

    Code:
    	<div class="cform">
        <h3>Add Comment</h3>
        <form action="" method="" enctype="">
            <div class="row">
              <label><span class="label">Your Name:</span>
              <input name="name" type="text" class="formw" id="name" />
              </label>
            </div>
            <div class="row">
              <label><span class="label">Email:</span>
              <input name="email" type="text" class="formw" id ="email" />
              </label>
            </div>
             <div class="row">
              <label><span class="label">Website:</span>
              <input name="website" type="text" class="formw" id="website" />
              </label>
            </div>
            <div class="row">
              <label><span class="label">Comments:</span>
              <textarea name="comments_body" rows="10" class="formw" id="comments"/></textarea>
              </textarea>
              </label>
            </div>
            <div class="row">
            <input type="hidden" name="aid" id="id" value="<?php echo $id; ?>" /> <!--grabs the id of this article-->
            </div>
              <input name="submit" type="submit" id="submit" value="Add Comment" />
              </form>
              <ul id="response" /><!--error messages or success message will display here -->
              </div><!--/ cform div-->
    Second, the PHP is looking for a form element called "submit". That doesn't get sent with the AJAX.
    I am assuming you are referring to this line in the php code:

    PHP Code:
    if (isset($_POST['submit'])) { 
    Should I remove that?

    I think I will try your $.post method in the jquery. I'm confused as to where I would add the variables and form element information?

    Thanks for your help sorry if I seem dense.

    Oh, one other thing, I am using a class in my form as opposed to an ID because I would like to use something similar to this on other pages where I have multiple forms on one php page. (But that is a problem to tackle another time)

    Gerry

  • #4
    New Coder
    Join Date
    Oct 2010
    Posts
    17
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Ok,

    Thank's to Spudhead's help and great jquery code example (now using .post() as opposed to .ajax() ) and tweaking process.php, I managed to get this to work.

    The php form validation works, the new comment gets inserted into the comments table and I even managed to add jquery to clear the form data all without reloading the page. Here's the jquery:

    Code:
    $(function() {
            $('#comfrm').submit(function(event) {
                    event.preventDefault(); // stop the form submitting
                    $('div.cform').append('<img src="../images/pageElements/ajax-loader.gif" class="loaderIcon" alt="Loading..."/>');//this will simulate processing by loading an animated gif
                    var data = $(this).serialize(); // $(this) represents the form object
                    $.post('process.php', data, function(results) {
                            $('div.cform img.loaderIcon').fadeOut(1000);//fade out processing simulation image
                            $('ul#response').html(results);//display succcess or failure errors.
    			//clear the form data
    			$('#name').val('');
    			$('#email').val('');
    			$('#website').val('');
    			$('#comments').val('');
                    });
    		
    	});				
    
    });
    Unfortunately, while the comment gets inserted into the table based on the article id, I still cannot get the most recent comment to display without refreshing the page.

    I have read online something about using JSON to do a callback to the page but am unfamiliar with how to implement this and if I would need to go back to the .ajax() instead of .post() or create a new function with .ajax() ?

    Any suggestions on how to accomplish this would be greatly appreciated.

    Thanks
    Gerry


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •