jQuery for Absolute Beginners: Day 13

Today, I’m going to show you how to submit information to a database asynchronously – using PHP and jQuery. We’ll be primarily working with the $.ajax method.


Download the Source Code

Day 13: Submitting Information to a Database Asynchronously



97

Comments
  • Ais says:

    Yeah Jeff, I think that’s the case, need to ask if they’re going to upgrade to PHP5 anytime soon.
    Got it work with my localhost though.

  • John Benson says:

    Loving the tutorials and thanks for using the PHP I’m looking forward to seeing that series as well.

    I’m curious thou a few days ago you showed us how to load content elements from another page into the page that we were on. if you were to use ajax to reuse a div with an ID=” content” how would you bind javascript to the newly loaded page elements like this form?

    another question that comes to mind is there would you place the javascript, would you put it in the original page, in the content loaded in ,or is thiere a plugin that uses some kind of get function to load the javascript and bind it ?

    Thanks again Jeffrey!!!

    PS: I love the way that you seem to plan mistakes and show us how to use tools to debug right here so that people like me who are learning can see how to use debugging methods instead of us wasting time trying to find what we missed.

  • Srigi says:

    Another great videotutorial by Jeff.

    audio:10,
    video:9 (sometimes overzoomed),
    information value:100

    I recomend to rename series to jQuery for advanced users now. I think you shoudn’t start PHP series and keep continuing with jQuery, with some advanced topics – offline form validation, form suggest, fancy css tabs with ajax, lightbox, plugins.

    Thanks for great job, keep pushing.

  • Great set of tutorials…

  • A Hassan says:

    This is one of the best tutorials!

  • Glenn says:

    Thanks.

    These are great. I think you nailed the speed/flow of the tutorials. Perfect!!!!

    Keep them coming!

  • svgrob says:

    The more I learn about jQuery, the more I love it lol

    Thanks for this awesome series! Im gonna be lookin for the PHP ones soon :D

  • Steve says:

    Another great tutorial thanks Jeff

    I am at the point where you first test the form and output to firebug. I am getting the following error in the console.

    fvd is not defined
    [Break on this error] for(handler in events[type])if(!parts[1]…ry.isReady)fn.call(document,jQuery);else

    line 26 of the jquery.min.js file

    Any ideas?

    Steve

  • binz says:

    Great class, I learn a lot from you! Thank you very much! By the way, I switch call PHP to save data to call .NET / .ashx, LINQ to sql.

  • kkathman says:

    Hi Jeffrey,

    I also have the mysqli error of “Call to undefined function mysqli()”, but unlike Ais I have PHP 5.2.6.

    I guess I got in the habit of using the 4.x mysql line commands, so I was really hoping to find out more about the mysqli. Perhaps it wasn’t implemented in 5.2.6?

  • Joe says:

    Love these tutorials.

    However, on this one, I’m having a problem and I cannot see what the problem is.

    I get this error in firebug:

    missing } after property list
    [Break on this error] data: ‘name=’ + name + ‘&email=’ + email + ‘&comments=’ comments,\n

    this is my javascript:

    $(function() {

    $(‘#submit’).click(function() {
    $(‘#container’).append(”);

    var name = $(‘#name’).val();
    var email = $(‘#email’).val();
    var comments = $(‘#comments’).val();

    $.ajax({
    url: ’submit_to_db.php’,
    type: ‘POST’,
    data: ‘name=’ + name + ‘&email=’ + email + ‘&comments=’ comments,

    success: function(result) {
    $(‘#container’).append(” + result + ”);
    $(‘#loading’).fadeOut(500);
    }
    });

    return false;
    });

    });

    I almost have no more hair to pull out.

  • Joe says:

    Nevermind, I was forgetting a + after ‘$comments=’

    :’(

  • Eric Warnke says:

    It seems that the videos hosted by Viddyou won’t play for me.

  • Tom says:

    Great series Jeff! If you are still taking suggestions for topics, I think a video (or series, if required) covering the general process of developing a web application would be great. Stuff like planning, which end of the application you start building first, version control, etc (I’d name more, but it’s now 2:30am – I suspect a certain jQuery video series is to blame). Keep up the good work.

  • craigcosmo says:

    Jeff, can you you enhance this tutorial in the advanced lession,like doing validating the form, and disable the submit button after user click, and enable it again it data was not inserted.

    And, in another scenario, there is a link “comment” if user clicks on that link a form will be loaded up, if they click cancel, the form goes away

    And, after submitting successfully, the form will close and the link ‘comment’ disabled and the comment will be retrieved from the database and display it

    And so on…

    You can call it the ultimate jquery-ajax-php form.

  • KihOshk says:

    @2:35, it appears you’re using your wife’s account; what’s that all about?

    Great work, thanks!

  • StevenR says:

    Really awesome! You convinced me to use jQuery over the other cool javascript frameworks there are.

  • Pritesh says:

    Hi Jeffery, Do you have a tutorial on how i would use AJAX and JQuery to select data from a mysql database?

  • thewackonerd says:

    Love your tutorials, thanks Can I make a request?
    I would like to see a tutorial on uploading an image and text to MySQL where the results are displayed under the form and the page does not have to reload. Thanks for all the great help so far in in the future.

  • markus says:

    hey jeffrey,
    would you be so kind to share your template folder. i like the idea of just copy/paste the files and start coding.

    great series of tutorials by the way,

    you’ve won another subsriber

    greetings,
    markus

  • rodel says:

    @jeffrey,

    i have it all working except for the fact that no record is appended to the table.

    what could be the problem with the insert?

    a little help will be much appreciated.

    by the way you got a great series of tutorials.,

    i’ll be subscribing.

    thanks in advance.

    greetings,

  • rodel says:

    @jeffrey,

    got it working now… (day 13 tut)

    if it will not be a tall request, is it possible to request for a tutorial on data manipulation using mysql, php and jquery?

    something like saving and displaying contents of database with cascading combo box update, radio buttons and check boxes.

    great tutorials. keep it up.

    thanks

  • carolina says:

    Hi Jerry!
    Great tutorials, i´ve learned a great deal from them.
    Just wanted to ask. I used your script from this tutorial and came across some issues in Internet Explorer, in particular, the contents of my site which are being loaded using jQuery just stoped loading alltogether. So you know why this could be happening?

  • Alex says:

    Try Coda Jeffery

  • mehdi says:

    thanks very useful tutorial i using mootools previously but when i see your tutorial i found jQuery very light and easier too use . tank you again . how your windows like a mac ?! :)

  • Brad says:

    Great job!!! i am usually never impressed by tutorials online, but i must say, what you have done blows me away. great job and keep up the great work!!!!!

  • Ben says:

    @Jeffrey,

    Is there a way to do this with a file upload (no database needed) Could not get it to work?

  • Brad says:

    @Ben,

    You need to be running a local server to do this correctly. wAMP/mAMP is what jeffery is using in these videos and is very easy to use. To submit information however, you will need run the scripts either a) on a server with mySQL & PHP installed or b) running from your local hsot

  • Sylver says:

    Very nice tutorial series.

    I am enjoying very much this intro to JQuery.

    Thanks.

  • Andri Yudatama says:

    Hi Jeff!

    I really wanna say thanks for creating such a great tutorial. It really helps me much in learning jquery from scratch.

    Right now, I am learning CodeIgniter PHP Framework with JQuery. Maybe you can also provide great tutorials about CodeIgniter (www.codeigniter.com).

    Thanks, and god bless u!

    Andri Yudatama
    Indonesian JQuery learner

  • Ronnie Overby says:

    I thought it would be neat to try this with asp.net instead of php. I was amazed at how easy it was to switch.
    I created an aspx page called submit_to_db.aspx and added the following code to the Page_Load event handler:
    ===========================================
    string name = Request.Form["name"];
    string email = Request.Form["email"];
    string comments = Request.Form["comments"];
    using (SqlConnection conn = new SqlConnection(”Server=.;Database=my_db;Trusted_Connection=True;”))
    {
    SqlCommand cmd = new SqlCommand(”INSERT INTO comments (name, email, comments) VALUES (@name, @email, @comments)”, conn);
    cmd.Parameters.AddWithValue(”@name”, name);
    cmd.Parameters.AddWithValue(”@email”, email);
    cmd.Parameters.AddWithValue(”@comments”, comments);
    try
    {
    conn.Open();
    cmd.ExecuteNonQuery();
    Response.Write(”Thank you. We’ll be in touch with you shortly!”);
    }
    catch
    {
    Response.Write(”There was a problem. Please try again later.”);
    }
    ===========================================
    And in the html file where the form resides, I changed the 2 references to the php file to the aspx file.
    That’s it!
    Greate series!

  • Ronnie Overby says:

    I forgot the closing bracket for the using block in my previous comment.

  • Rolf says:

    thank you!

    it was the first time, I am wathing and listening someone, while he ist writing code. And I enjoyed not to be the one, who has to create the neccessary files, to look for the images or to find the errors. :-)

    greetings from germany

  • beneblack says:

    Finally I found the solution, how to post a variable from javascript to php, with the help of this tut. But do I get them back to javascript? Ich tried the whole day, but didn’t find a way to do so.
    I just want get the Variable from PHP to Javascript (works), then post it do PHP an run a function (works) and get them back to javascript (works not right). I just want to insert the “result” in the successful-function into a variable, but I do not know how.

    Please help me.

    beneblack

  • rahul says:

    HI, Way, thank you very much for this informative presentation,
    I am working on J2ee framework, i was wondering how to Fetch ECHO value in result and show it on html?
    thank you

  • Saurabh says:

    thank you for these nice videos,

    i have one request can you please upload some videos of jQuery with Asp.Net
    like ajax calls, getjson etc

    Kind Regards
    Saurabh

  • Joe A says:

    I cannot get even the source material to work.

  • matt says:

    Could you do a tutorial about the asynchronous stuff?

  • Casper says:

    I find it hard to use mysql.
    I’ve been searching the internet from one end to an other, and I can’t find a good tut.
    I need to know what programs to use, where to find them, how to use them and so on.
    Have you ever made such tut?, or could you. Cause yore really good at explaining stuff. I learn so much from you.

    Thank You!
    Casper.

  • Denis says:

    Hello Jeffrey! Excellent tutorials!

    I have some problem with russian language.
    Usually utf8 should take care about this, but at this time output data were screwed up and i don’t know where exactly.

    I have tried to convert everything through utf8 without bom, but it didn’t helped.

    Output data in database from field comments:

    Проверка

    Could you please help? Firebug is showing this:

    User-Agent

    Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11

    Accept

    */*

    Accept-Language

    ru,en-us;q=0.7,en;q=0.3

    Accept-Encoding

    gzip,deflate

    Accept-Charset

    windows-1251,utf-8;q=0.7,*;q=0.7

    Keep-Alive

    300

    Connection

    keep-alive

    Content-Type

    application/x-www-form-urlencoded; charset=UTF-8

  • Denis says:

    I have found the problem:

    $querynew = ‘SET NAMES utf8;’;
    if($stmt->prepare($querynew)) {$stmt->execute();}

    Type it after:
    $stmt = $conn->stmt_init();

    And language problems should dissapear. If not, try iconv() function.

    By the way Jeffrey if you read this, could you please add sorting feature “sort by last commented” or something like that.

    Great job! :)

  • Patrich says:

    10/10 :)

    I relly like your tutorials :)

  • mPulse says:

    Hi Jeffrey,

    This is a great set of introductory tutorials to JQuery. You cover some excellent points. I especially like this video, and the tooltip lessons.

    If you have the time, I believe it would be very helpful to beginners to go back and do over a few of the videos to eliminate mistakes (ie. not closing the quote in the PHP script on this one), slow down a bit, and use proper indentation. I think that making these changes would make the videos easier to follow for beginners by eliminating distractions, and would easily make this video series the best out there for JQuery introduction.

    Keep up the great work!

  • matt says:

    Hi

    Really stuck wondering if anyone could help with the below???

    Great tutorial though!

    POST http://localhost:49749/jquery/submit_to_db.php

    405 Method Not Allowed
    22.08s jquery.min.js (line 19)
    ParamsHeadersPostPutResponseCacheHTML
    Response Headers
    Request Headers

    The HTTP verb POST used to access path ‘/jquery/submit_to_db.php’ is not allowed.

    body {font-family:”Verdana”;font-weight:normal;font-size: .7em;color:black;}
    p {font-family:”Verdana”;font-weight:normal;color:black;margin-top: -5px}
    b {font-family:”Verdana”;font-weight:bold;color:black;margin-top: -5px}
    H1 { font-family:”Verdana”;font-weight:normal;font-size:18pt;color:red }
    H2 { font-family:”Verdana”;font-weight:normal;font-size:14pt;color:maroon }
    pre {font-family:”Lucida Console”;font-size: .9em}
    .marker {font-weight: bold; color: black;text-decoration: none;}
    .version {color: gray;}
    .error {margin-bottom: 10px;}
    .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }

    Server Error in ‘/jquery’ Application.

    The HTTP verb POST used to access path ‘/jquery/submit_to_db.php’ is not allowed.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: The HTTP verb POST used to access path ‘/jquery/submit_to_db.php’ is not allowed.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    Stack Trace:

    
    [HttpException (0x80004005): The HTTP verb POST used to access path '/jquery/submit_to_db.php' is not allowed.]
       System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) +2872346
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8679186
    
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
    

    Version Information: Microsoft .NET Framework Version:2.0.50727.4016; ASP.NET Version:2.0.50727.4016

  • Jasper says:

    Great series.

    I love to see more of the Jquery data retrieval and data update querys.
    Great job on making this series im going to keep this as a golden find!.