Cakephp Ajax Tutorial – Using Cakephp's Js Helper and jQuery



hello this is Andrew Perkins and in this video I'm going to walk you through using jQuery to add some Ajax to your cake PHP applications we'll be building a contact form will first use the built-in CakePHP JS helper to do the Ajax database submission but then we'll also write some custom jQuery to do some Ajax validation using our cake PHP model validations so this should give you a good idea of how to implement Ajax into your cake apps using both the built-in Jas helper and dropping down and using writing your own jQuery to get it working with cake PHP so how the application will work is a user can come to our contact form here and send us a message the message will be validated and if it validates it'll be stored into the database all of this will be using Ajax we won't actually be sending any emails as the point of this tutorial is how to do Ajax validation and Ajax DB submissions in que PHP so first I want to go over what I already created here and what I'm working with it's a very basic installation of cake PHP I've created a form and we can take the users name email and message and it validates that information this is not using any Ajax yet and if it all validates it'll save it to the database so let's take a look at the code real quick here is my CakePHP application in my text editor under the app folder I'll just start at the top I have a messages controller and it has an index action and it's just going to handle the form submission this is pretty standard checks if the form is empty it checks if the save was successful and if it was it sent it sets a flash message and redirects the user inside the models folder I have a message model and this just does some basic validation for the name email and message fields I'm checking – well I'm ensuring that the name and the message fields are not empty and for the email I'm ensuring that it's a valid email using the email and not empty rules that cakephp gives you inside of the views folder I have a messages folder to hold our messages controllers views and I have one view index ETP that's for the index action and this just creates a form if you notice I'm doing the create method for the form helper a little different you don't actually have to pass in the model and then the array as a second parameter and telling it what action to submit to you can leave it blank and cakephp will by default submit to its own action to itself so it'll submit since this is the index view for our messages controllers index action by default if I leave it empty it's going to submit to the index action a few other things to note here that you'll want to make sure you do is I've created an ID for each of these fields so I have a field for name email and message and the ID for each one is exactly the same as name for that field and it also matches the field name in the database and that's important because when we do our Ajax validation we will be passing in the name of the field that way we can dynamically check whether or not the field is valid or not so you need to make sure that your ID is the same as the name of your field and finally have a submit button and I close the form so let's take a look at our table real quick in our database let's go to the structure and here you can see I have an ID field it's an int type to auto increments and it's a primary key I also have a name and email field both of those are of our car type and finally I have the message field which is of a text type and notice that these name email and message like I said they're the same as the ID name name email and message and that is important that your IDs match up because again we'll be using that to dynamically check when we pass it in through using jquery's Ajax method called post we'll be using the post method to do the Ajax validation it needs to match up with the name of the table so that we can dynamically check whether or not it validates so there's the basic structure of our application it's really simple just as a simple database submission currently and we're going to add some Ajax to it the first thing we're going to do is actually get the submission to do we're going to submit using Ajax and we're going to use cakephp helper the J's helper to do that submission the Jas helper by default uses the jQuery framework or library so we need to go get that we can go to jQuery calm and download it we can select all of this and copy it and after you copy it we need to create a new file we'll go to our text editor under app under web root and in the jas folder we'll create a new Java Script file I'm going to call it jQuery Jas and I'm going to paste in the jQuery library code that I just copied save it and close it out so now we need to tell our application to actually use the jQuery file since we don't need jQuery on all of our pages we only need it on our index page right here at the top we can use the HTML helper and it's script method and we can tell it to include a JavaScript file for us so we're going to say include jQuery now by default if you leave it like this when you look at your source code it's actually going to create the link tag and link to your JavaScript and it's going to be right there in the body of your HTML and we don't want that we want it to be in the head of our HTML like you normally do where you stick your CSS files and everything so you can pass the second parameter to the script method until it false and that will make it use the script for layout variable that's inside of your layout so we'll take a look at the layout real quick under app under use layouts I have default CTP and this is a standard cakephp layout I copied it right from the CakePHP library you can get a copy of this just by going to your cake holder under lives under view under layouts and you'll see default dot CPP you can just copy all of this the only difference is is that I removed the documentation at the top and I also got rid of the call to the SQL element dump here so I just copied all of that and created my own default layout here and I'm using that code and as you can see cake uses scripts for layout so in your view files if you want to only load this jQuery file for this page you can call the HTML helper method HTML helpers script method tell it to load jQuery and pass in false as the second parameter and it'll load it in this spot of your document where scripts for layout is so it'll load it up here in the head for you so we can close the layout so we have jQuery loaded let's check and make sure it works we can go back to our browser and I'll refresh this page and if we look at the source code we can see that it did not insert it in the body but if we scroll over up here in the head we can see that it included the script tag for our jQuery file right here in the head just like we wanted all right now we need to enable a helper and a component that we're going to be using to add some Ajax to our application so at the top of our messages controller I'm going to create a new variable here called helpers this is to load in any helpers that I want to use and I'm going to be using the Jas helper the Jas helper is like a combination of the now deprecated Ajax and JavaScript helpers it'll give you a Jackson JavaScript functionality you don't have to write any JavaScript with it you can just write PHP and it generates the JavaScript for you we're also going to be using a component so I will create a component variable here to load in the component that I would like to use we're going to be using the we're going to be using the request handler component the request handler component has a really cool method called is Ajax and it returns a true or false value of whether or not the current request is an ajax request or not and we'll be using that later you go so once you have the Jass helper and the request handler loaded in the next thing we need to do is tell k PHP where any JavaScript that's generated by our Jas helper should be loaded or where it should be displayed inside of one of our views when we use the jl / it's going to generate some JavaScript for us so we need to tell the application where that should be displayed whether it should be inline whether it should be displayed right where we put it in the view or whether it should be cached and put inside of a JS file so that it's unobtrusive we're going to choose the last one so what I'm going to do is open up our layout file again I'm gonna close the cake folder open up app views layouts and open up default CTP one more time and here in the layout after the scripts for layout call we're going to use the H the J s helper and we're going to use its write buffer method so we're going to echo out this and then the J s helper and we're going to use its write buffer method the write buffer method is telling the J's helper where it should put any JavaScript that it generates in this case we're saying to display it in the head right after any of the scripts that are called from our views so in our index view it's going to load the jQuery file first and then when we use the JSL / it's going to be called right after it and by default it's going to write our javascript inline right into our HTML but we'd liked it to be cached and held in a separate file so that it's unobtrusive and it's not just sitting in our HTML to do that all you have to do is pass in an array of options to the write buffer method and set cache equal to true we can save it we won't actually be able to see that that's working right now but we will in a moment after we start using the JSL burr so now we're ready to get started actually doing some Ajax so I'm going to go back to our index view and we're going to do an ajax submission using the JSL / to do so it's really simple the form helper has this submit button method to create a submit button but the j/s helper also has a submit button but rather than just being a regular form element it also doesn't Ajax we've an ajax submission so we're going to change this to be the GS helpers submit button it takes the same parameters as the regular form helper method does the first one is a string of what you want the text on the button to be the second one is an array of options the difference is is that this array of options for the GS submit method also has some Ajax options that the form submit method does not so we're going to be setting these Ajax options there's three of them that we're interested in the first one is called before and this is what you want to happen before the request is completed or while it's going on when someone clicks the submit button there may be a pause like as there as the submission is happening so we want to give them some visual feedback that something is going on and we can do that using the before key part of this array of options and what we want to happen is this will display like some text say saying sending so that they know something is happening so we can use the j/s helper to fade in that text because we don't want the sending text to just be there when it's not actually sending we only want it to show up when they click the button and then we want it to fade out after it's finished so before the request is completed we want to use the JSL / and we're going to use its get method the get method takes a string which is an ID of an element that you would like to select in this case we want to select an element called sending we don't actually have this element yet so let's create it so I'm going to create a div down here with an ID of sending and it'll have the text of sending so this is the element that the user is going to see whenever they click the button as their submission is being processed now as it currently is it's being displayed all of the time so we need to use a little bit of styling here to hide it so I'm going to use some inline styling and set the display property to none that way it's hidden so back up here in our submit button where we're setting what should happen while the request is processing we're going to use the JSL / to get the element with an ID of sending that's this message down here and if you're using PHP 5 you can chain on methods part of you can chain on methods using the J's helper so we're using the get method and we're getting the element of sending and then we're going to chain on the effect method to apply an effect to that element the effect that we're going to apply is called fade in so when they click the button while they're waiting for the submission to go on before it's complete we grab the element with an ID of sending and we fade it in because it's currently hidden because we set the display to none we can also set what happens on success this means it has completed we want to fade out the sending message because it's done they no longer need to send it so we should get rid of it so we're going to do pretty much the same thing use the JSL / it's get method we're going to grab the sending element we're going to chain on an effect and we're going to tell it to fade out and finally we can tell it when it's completed whether or not it should update a part of the page and we can tell it what part of that page it should update so we can use the update key as part of this array of options and we can pass in a string which is an ID of an element that we want to update in this case I'm going to create an element with an ID of success so when the submission is successfully completed it's going to update an element with an ID of success so I'm going to create that element real quick up here at the top of the page I'll create a div with an ID of success and it's just going to be blank for now they won't actually see nothing it is there and once the request has completed once it's successful whatever is returned is going to be updated and stuck inside of this success tip so we're going to give the user a success message and it's just going to display that and if that's going to be done via Ajax so let's go over this one more time we've changed the sub button to use the J SL / instead the text that will appear on the submit button is called sin we're passing in an array as a second parameter to the submit button and it's an array of Ajax options we're telling it before the request is completed while the users waiting we're giving them some visual feedback we're selecting the element with an ID of sending and then we're fading it in when it is completed we're selecting that element again and then we're fading it out because it's completed and they no longer need to see the message of sending and after it is completed we're telling it to update the element on the page with an ID of success and that element is up here and when it's updated it's going to display a success message to the user letting them know that their submission was complete so now we need to go to our messages controller and we need to modify our index actions so that it can handle the Ajax requests we are checking whether this data is not empty that means the form has been submitted we're checking whether or not the data that was passed from the form can be saved if it does were giving them a flash message and redirecting them this is what we want to do if it's a regular request if they don't have any JavaScript enabled and it'll still work without JavaScript but we want to check whether or not it's an ajax request so we can handle the request differently and to do that we're going to use the request Handler we're going to check if this request Handler and we're going to use the is ajax method is ajax returns true or false whether or not the request is an ajax request or not so if it is we can handle the ajax here and if it's not that means it's a regular request so we're going to do it the normal way by giving them a flash message and redirecting so back up here in the part where it is an ajax request we need to handle what should happen after the save is done we don't want to redirect we don't want to set a flash message because those all require a page refresh instead we just want to render a view and whatever is rendered is going to be sent to our view and it's going to be put in to whatever we tell it to update so whatever view we say to render here when the Ajax submission is complete whatever is in that view is going to be stuck inside of this div with the idea of success so here in the true part of this if condition if it is an ajax request we're going to use the controller's a render method and we can tell it to render review in this case we're going to render a view called success i haven't created that but i will in a moment we're also going to pass on a second parameter to the render method and this is telling it which lay out this view file should use if by default if you leave it as you don't pass in a second parameter it's going to use our default HTML layout here that means when it renders that view file it's going to have all of this HTML around it as well and we don't want that we want it to use whatever is on the current page it'd be like this double amounts of HTML rendered so what we can do is pass in a second parameter telling it to use a different layout we can tell it to use the Ajax layout and the Ajax layout is already built for you we can take a look at it real quick down here in your cake folder again under libs view layouts and you see you have Ajax CTD this is the Ajax layout and as you can see it's there's no HTML all it's doing is use echoing out the content for layout that means it's just going to use only what's in your view file and that's exactly what we want here so I'm going to close it and I'm going to close the cake folder again alright so we checked when the form if the form has been submitted and if it's successfully saved we check whether or not it was an ajax request if it was we render our success view file using the ajax layout and that will be stuck inside of the div with the ID of success that'll be updated whenever the ajax request was successful if it was not an ajax request it's going to do it just like a normal form submission it's going to set a flash message and then redirect the user so it'll work even without JavaScript so what do we need to do now we need to create this success view so that it has the view file to render so under App under views inside of your messages folder that's where your index ctp view is we'll create a new file and call it success CTP and I'll create a pee tag here and I'll say message sent let's also give it a little styling so we can see it a little better when it pops up I'm just going to set the background color to be light green and then I'm going to go back into my index CTP file and where I'm fading in and fading out this div which is our sending div giving the user visual feedback that the Ajax submission is happening inside of the style attribute I'm going to also set its background color to be light green as well so that it's easier to see on the page so I think we're ready to try this out let's give it a go go back to our browser and let's refresh the page and let's look at the source code so we scroll over and there's our jQuery file and then you're going to see this other JavaScript file that's random here this is what the JavaScript helper generated for us it cached the JavaScript that was generated from that j/s submit helper method and it stuck it inside of this file and here you can see the code that the j/s helper created this is jQuery JavaScript code that it created for us and we didn't have to write any of that we pretty much just wrote one line and set some options so let's try it out let's enter in a name here my message and let's hit submit or send so what you should see is the page will not refresh we should get our sending message it should fade in and then fade out once it's complete and then we should get a message sent up here and remember this will happen via Ajax and the page won't refresh so let's try it out hit Send message sent and if we take a look at Firebug we can see in the console that we did a post and it was 200 okay that means it was successful we can try it again Joe – my message again here and if you watch Firebug you'll see that another post will happen in there there we go it happened again and the message was sent so let's take a look in the database and see if it actually saved it there we go we can see Joe – Joe and there's our messages that we sent and those were all done via Ajax and so that's the basics of using the j/s helper there's a lot of other methods that you can take a look at but we're going to move on and we're going to write our own jQuery to do some Ajax form validation because currently the validation will not happen uh it will only happen it won't work correct as what I'm trying to say so we're going to implement it to where if they don't have a name here and they tab out underneath the name it's going to do an ajax request in the background check whether or not the value of this field validates and if it doesn't it'll display the error same with the email field if they enter an incorrect email address when they tap out and move to the next field it's going to do an ajax request and check whether or not the email field is valid and if it's not it'll display the error message and they can go back and fix it this way they have a really seamless experience with the application and they can get the error messages before actually hitting the send button so let's get started on that let's go back to our text editor we can close a couple of these out we don't need the layout file anymore we don't need our success view anymore and we don't need our model anymore so we'll keep the controller and the index of you open and what we need to do is create a new JavaScript file first we're going to make sure we load it in so we don't forget to load it in so at the top of this page remember this javascript file is only needed on the index view so we can load it in right here and we'll pass in false just like we did before and that'll make sure that it's a stuck inside of a script tag at the top in the head section of our HTML so I just duplicated that and I'm going to create a JavaScript file called validation I haven't made that yet but I will in a moment but we're loading in a script tag or a script called validation save it and let's create that under App web root under JavaScript I'll create a new file called validation jeaious and in here we're going to write jQuery to do an Ajax validation request here we're not actually going to be submitting to the database we're only going to be passing the field name and the value of the form field to the controller the controller is going to check whether or not those values are correct or valid if they are nothing will happen because that means it's valid so there shouldn't be anything the user can just just submit the form if there are errors it's going to send errors back to the validation script we'll have a callback function that's going to handle those errors and we'll display the error on the page and that will all happen with Ajax and jQuery it's pretty simple there's quite a bit of code here though so I hope you are familiar with jQuery let's get started we're going to use the standard document dot ready open up our function here so first we need to grab the form element that we want to check so we have three form elements we have name email and message and they each have an ID of the same name so let's just do the name field first we'll get that one working and then we'll apply the same code for the email and message afterwards for those fields so we can grab the or select the form field with an idea the main and we're going to use the blur function or blur method the event to check whether whenever a blur event happens on the element with an ID of name that and so whenever a blur event happens just in case you don't know what a blur event is a blur event is when you have the name field selected right now when I hit tab and I move to the email field that's a blur that means a blur event occurred on the name form field the same can happen when I click away from it that's also a blur so whenever that happens this code is going to be run inside of the blur callback function so whenever a blur have blur event happens on the field with an ideas name we're going to do an ajax request we're going to do that using the post method break that onto a new line oops the post method takes a couple different parameters the first one is the location that it should post to in this case it's our cake contact Ajax and to the messages controller and I'm going to call it validate form so I'll be creating this action validate form and that's what we're going to submit to and it's going to do the Ajax validation for us the second parameter is an object of values that you want to send we're going to be sending two values to our validate form action the first value is going to be the field name and the second value is going to be the actual value of the form field that we want to validate to see if it's a valid value to actually stick into the database so we're going to create field that's going to be the field name the reason we need to pass in the field name is so that it's dynamic in our controller when we create this validates form action we don't know whether or not the data that was passed in when the blur happens is coming from the name field or if it's for the title field or the email field or there isn't a title field if it's for the email field or the message field by passing in what the field name is we know which one to check and how we get the field name is because we set the ID of that form field the ID is the same name as the field name so the ID of our name field is name and this matches the field in the database for a name and so we can check whether or not the name field in our model is validating appropriately so we're going to pass in the ID of the name formfield so we need to grab the name field and we can use the attribute method to grab the ID attribute of the field with an ID of name so that means it's going to get the ID of our name input field the ID is named currently we also need to pass in the value of the form field so that we can check whether or not that value is valid we can get the value using we we select the name form element again and we just used the Val method of jQuery and that will return the value of whatever was entered into the name form field so that's it for the second parameter the third parameter and the final one that we'll be using here is a callback method or callback function this function will be called whenever the post the post for the Ajax request has completed so I'm going to call mine handle name validation and save it now we just need to write this handle name validation callback function so still inside of the document dot ready but outside of the blur callback function I'm going to create a function called handle name validation now when you create a callback function using jquery's post method to do an ajax request whatever comes back from that request will be passed in as a parameter to the callback and in our case it's going to submit to validate form in our messages controller I don't have the validate form action created yet but once I do if there is an error it's going to send that error back and that's going to be available in our callback and that's going to be passed in as the first parameter so I'm going to call that error so now we have this error variable that we can use in here to check whether or not when we did our Ajax request whether or not we have an error so we can first say if error not linked is greater than zero if the error dot length is greater than 0 that means we obviously have an error now since we have an error that means we need to create an HTML element to display that error on the page so that the user can see that there's been an error we're going to give that HTML element a unique ID that way we can reference it and check whether or not it's currently displaying and so we can also hide it because if there are no errors like the first time they go to it if they tap out it's going to display the error but if they go back and they enter in valid information and they tab out we need to make sure that we then hide the error we don't want it to display so we're going to be giving it a unique ID so first we're going to check we're going to select an element in this case it's going to be for our name name form field so we're going to check for a name not empty and this I am naming myself this is what the ID of that form element which is going to contain our error message is going to be this is what the ID will be of that element so I'm checking whether or not it's length is equal to zero if it's length is equal to zero that means it's not there so we need to display it and so we're going to create that element we're going to create a div here we're going to close the div and what's going to be inside of the div is going to be whatever the error was that was returned so if we have an error we're going to create a div tag there's the opening tag and there's the closing tag and the contents of that div tag contains whatever error was passed back to the callback function of our post request up here so we need to give this div the unique ID that I told you about the unique ID is what we're checking for the length of up here if it's equal to zero we don't have it so we're going to display it first so we're going to give I B equals name – not empty meaning the ID of this div is just it's for the name field and we're saying that it's supposed to be not empty so this will display the div tag properly but we need to put it in the correct position we don't want it to just be anywhere we want to insert it after that form field so we have this form field of name as an ID of name if they tab out without entering anything and it's invalid we want the div to show up underneath here correct so we can we can see it that it's part of the name form field so we need to tell it to insert after that form field that's really easy using jQuery we can just select the name form field again and we'll use the after method to tell it to insert it after the name form field I'm also going to give this div which displays our error a class this class is going to be called error message and the CakePHP default layout and its style sheet has styling already for a class called error message and that'll style our error message to make it look pretty for us that's all it's there for is for styling so we can save it so this is going to handle if we have an error and if we don't have an error we need to make sure that if this is a vet if the div showing the error message is there that we remove it because if there's no error we don't want to tell them that there is an error so we can just remove it that's why we gave this div container an ID a unique ID so that we can check or reselect it and then remove it so we're selecting the error div and then we're just going to remove it so if we have an error we display the error message after the form field if we don't have an error we make sure that we remove it just in case it's there so it's not being displayed again so we can save this and now we can write our validate form action in our controller because that's where this post is going to post to so in our messages controller I'm going to create a new public method called validate form and this is actually pretty simple we're just going to check if this we're going to use the request handler again we're going to check if the request is an ajax request if it is an AJAX request what we need to do is populate the this data array remember that this data array is the array that you can check when a forms been submitted like up here when the forms been submitted all of its values are in this data and it's properly formatted to be submitted to the model to be saved we're not actually doing a save here we're just checking whether or not the form field is valid we just want to do the check and if it's not valid we want to send them an error and display that and we're doing that I via Ajax so what we want to do is pre populate this data with whatever was sent or posted back from our jQuery AJAX call remember we're going to post the field name and we're going to post the value of that field now we can access these values whatever field we passed in and whatever value we passed in using the controller's params or yes the params array so we can access the value of field and we can access the value of value using the params array and we can pull those respective values from whatever was posted so what we need to do is populate the message data array and we could hard code in here that we want to populate the name or the email but that won't work because we don't know whether we're checking the name email or the message this needs to be dynamically inserted this is why we passed in the field name this will be dynamic to whichever field is being validated field is going to be equal to whichever field we're trying to validate so if we tab out of the name field the Ajax request is going to send in the field name of name if we tab out of the email field the field name is going to be sent in as email and that's going to be available to us through these field and value parts of the per a mass or per am array so we want to pre-populate that this data array and it's part of the message because remember this data the first part of the key of the array is the model and the second is the field name so here we're going to use the params array and we're going to access the forum and then we're going to grab the value of the field this field matches this field that we post it back so we're just going to populate that and we're going to make its value be equal to the value of the params that was passed this value is the same as this value here we're grabbing these values that we posted back the value holds the value of the current form field that we're validating and field holds the field name of the field that we're validating so we're taking the value of that field and we're populating it into this data array so that we can check whether or not it's valid to check whether or not it's valid we can use the models set method to send the data to the model to be validated all we're doing is calling the model set method and we pass in the this data array remember we just populated this data array with the value of the form field that we want to check is valid next we need to check if it is actually valid when you send data to the model we now have a new method that we can check we can save this message validates and we can use that in a conditional like I'm doing here I'm saying if this message validates this is going to return true or false if whatever we pass to the model validates or not if it does validate that means there was no errors we don't want to do anything we don't want to display anything we just want to leave it alone and to do that we need to tell it to set Auto render equal to false that way it doesn't render a view because if you don't put anything in there by default cake actions will render the view it's going to try and render the validate form view and that's not that's not what we want if the message validates that means there were no errors so we don't want to render anything we just want to leave it alone but else meaning that the message did not validate we need to send the errors to them so we can display those errors and let them know that they need to correct the form before submitting it so I'm going to create a variable here called error and we can grab the current errors by using the this call validate errors method and then just pass in the actual message and this is going to pull all of the validation errors for the message model and it's going to store it as an array inside of this error variable but it's going to be an array so we can now send this error to the view so that we can display the error we can do that by using the set method of course and make it available in the view as a variable called errors or error in this case and then the second parameter is the actual data that we want to send to the view what we want to send is our error array up here but we only want to send the error for the current field because remember we're populating this data with the field that's being passed in from our post so if they tab out of the name field it's going to be field is going to be name and we only want the error for that current field we don't want the error for any of the other fields so we can tell it to only include the error for that field and we access that through the key the key is going to be that field that we're validating and remember that's passed into the validate through our post request back here so we can save this so I know there's a lot going on here and it might be confusing at first but it's actually pretty simple we're just doing a post request we're passing in the field name of the field that we're trying to validate and we're passing in the value of that field we can access those values using the params array and it's inside of the first the first key is inside of the form key and then you can access field and value respectively since we're not doing a database submission we're only checking if these values are valid we have to populate this data manually so we're populating this data and the first key is the message because we're dealing with the message model and the second key is the field name and this is dynamic so we're using the params field value that we passed in and we're giving it a value of whatever value was passed in from our post request we're then setting this data to the model so we can check it the validates if it does validate meaning there's no errors we make sure that it doesn't render anything we want to make sure that it just just doesn't do anything there's nothing wrong with the form they can just continue but otherwise they do have errors so we grab the validation errors for the message model and then we pass in only the error for the field that's being validated and it's available inside of our view as error so now we need to create this validate form view so if we go to views messages create a new file call it validate form dot CPP that correct yes and then in here all we need to do is display the error so we can just echo out an error remember this error is coming from when we're setting it we're setting the error here and it's going to display the error for the current field the validate form error the validate form view whatever is displayed in that view is going to be stuck inside of this div that we created in our handle name validation function or callback so it's all together we should be able to try this out it's all together at least for the name field we haven't duplicated any of this code for the email and message fields yet but it should work for the name field maybe we have some errors let's try it out we'll go to the browser will refresh this page no errors yet let's look at the source code and make sure that our validation script is being loaded in there it is all right let's try it out so if we don't enter anything in here and we tab out on the blur event it should do a an AJAX request and check whether or not the current value is valid we tab out and you can see it now says enter your name it's not valid we go back to it and tab again it's displaying it again so it looks like we do have an error let's figure out what I did wrong here let's go back to my validation j/s file yeah here is my error you can see I accidentally wrapped the when we created the new div here you can see I wrapped it in an extra jQuery object here we don't need that so we can remove this and the closing one there and save it so it should be we select the element or the form filled with the idea of name and then after it we're creating the div here to display the error message that was the problem so we can save it go back to the browser and let's try to refreshing so if we tab out we get enter your name we tab out again still not working so looks like I made another mistake it's pretty easy to make these typos as you can see in the actual ID declaration I'm including a hash symbol you don't need to do that there that's you only need to do that when you're trying to access it through jQuery here I'm actually setting the IP of the element you don't want to put the hash symbol in there with it so hopefully that's the last error that was two errors in a row huh all right let's try it again we're selecting the correct elements here I hope it works let's save it and go back to our browser and I'll refresh and let's tap out and our error shows up if we tab again there we go we still only have one error and that's how it should work it shouldn't give us multiple errors in a row so it did the Ajax request it checked if a blank name value is correct and of course it's not it's saying enter your name so we enter our name here in tab out our error now disappears because it's now valid and it doesn't need to display the error so it looks like it's working let's try it again and we can see the Ajax submissions happening down here in Firebug let's clear all of this real quick and so if I tab out you can see it does the the post request and then I enter in a name it does another post request so let's now apply this to both the email and the message fields as well so we need to go back to our text editor and in validation j/s we're just going to duplicate the blur and the callback function now of course you could refactor this out so you don't have duplicated code but just to make this easy for people who are not quite familiar with jQuery and CakePHP by doing it this way it's more linear and easier to understand for the tutorial so I'll paste it down here and we want to change this to be for the email field and for the email field so we're going to just change all of this over so that it's for the email field and of course we need to rename our callback function here so I'm going to say handle email and then we'll rename it here handle email and we need to give the div its own unique ID so it's going to be email and save valid and so we need to duplicate that up here email valid and we need to make sure we're checking inserting after the email field not the name field and then again down here we want to remove email valid and let's see if that works we can refresh and if we go to the email field and we tab out says enter a valid email address so we'll enter in some gibberish and see if that works as you can see it still says enter a valid email address so we enter in my email the validation goes away and we'll check the name again please enter your name please enter your email and lastly let's do that for the message field to change all of this to message and the callback should be handle message validation and my message and so you need to change this ID to be message and not empty down here the ID should be message not empty message not empty there we go so save it and we should try all three out now name email and message and so if we enter a name a wrong email and our message the name and message fields validate let's close out Firebug we can see that it's working but the emails still wrong so we'll try Joe I'll select that it validates so now we can hit Send sending message sent so it was Andrew Joe Gmail and then this gibberish message let's see if it's in our database there it is Andrew Joe at gmail and our message so that's a look at using jQuery with cakephp and using cakes built-in j/s helper to do ajax submissions and ajax validation I hope you found this helpful it is a little confusing as you can see those errors that I made are very easy to make so while you're following along make sure you type very carefully because you mess up one of the IDs or anything like that and your application will break so let me know what you think about it in the comments and thank you for watching

31 thoughts on “Cakephp Ajax Tutorial – Using Cakephp's Js Helper and jQuery

  1. Thank you!!
    jqueryがよくわからなかったので、ひとまずかけました。ありがとうございます!

  2. Also, when I submit the form without any fields entered, I get error messages, and a double form on the page. One right under the other?

  3. I am new to learning cakephp I followed your tutorial, which I like very much, but I cannot get the error messages to show. The code works fine and I don't get any errors in firebug, but no message on blur event? I am using 2.4.5 version of cakephp if that makes a difference?

  4. Nice tutorial !!!

    In Cake 2.x you'll have to do some adjustments, especially in the controller to set the Model's data:

    $this->request->data['Message'][$this->request->data['field']] = $this->request->data['value'];

  5. Great tute! Well paced, clear and explained in understandable terms. As a someone very new to CakePHP & JQuery I found this a great help. Look forward to seeing more of these!

  6. my blur validation not working properly and after submit blank form all field are showing error as we done.
    but a new contact form is creates automatically flow the first contact form

  7. What do I do when the username and password fields fulfill the validation rules but, the user doesn't actually exist? I would surely need some response like, 'User unknown, please check your details and try again.'. How do I add this to the Model?

  8. hi andrewpark
    pls upload video for cron job for mail in cakephp;if it possible give full detail of cron and functionality

  9. I fixed this by ensuring that only echo $scripts_for_layout; is the function calling scripts in default.ctp. Also, updated cake uses $this->request->data instead of $this->data in messagescontroller's validate_form() function

  10. Managed to get the 'sending' section to work but I'm not getting any form validations to work – no error messages appear when I tab or click out of the field.
    Only error I can see (and it doesn't show an error in the webpage itself) is in 'validate_form.ctp' it says "$error seems to be uninitialized"
    I've encountered this error before but can't seem to work this one out, and I've followed and double-checked through the tutorial.

    Thanks. Great tutorial nonetheless.

  11. I've hit upon the same problem where 'succe­ss' isn't displayed on submission yet everything else appears to be working, sending message appears and messages saved in SQL. Any ideas how to solve this problem? I did try your suggestion of adding a path $this->render('/Messages/succe­ss', 'ajax'). I'm using CakePhp 2.2.4

  12. Your tutorials are great! Please keep the cakephp ones coming, they are the best I found and the 2.x changes are driving me crazy when I try to follow old tuts.

  13. Notice (8): Undefined property: View::$Js [APPviewslayoutsdefault.ctp, line 16]
    Fatal error: Call to a member function writeBuffer() on a non-object in C:xampphtdocscakeajaxappviewslayoutsdefault.ctp on line 16

  14. Andrew Perkins , you are very talented in making difficult things seem easy as a piece of cake. thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *