I have an issue I can't seem to solve. First some context that may be relevant.
I am building a MVC-like (I say "like" because I'm still learning how MVC works) php framework for my software. I want all the input forms to submit data via ajax to a backend controller that routes the data and inputs it into the appropriate database. All the HTML code is generated through php classes and the JavaScript in included through php classes.
The problem I'm having is with the ajax function. It keeps trying to submit the post request normally while I want it to submit asynchronously. I've had it working properly at various points in time but it seems to break when I change aspects of the framework. I've tried various combinations of "form.preventDefault()" and "return false" but it doesn't seem to matter. The validation part works (it won't submit with invalid entries. Using this plugin). I discovered that JavaScript caches itself and I've worked through that by appending version numbers to the file name.
Here is the ajax code. It returns a message to the user about the status of the request. Any idea why it refuses to submit asynchronously?
$(document).ready(function() {
// Initialize form validation
***old code
$("form[name='ajaxform']").validate({ ***
// Specify validation rules
***Updated code
$('#ajaxsubmit').on('click', function() {
$("#ajaxform").valid();
});
// Initialize form validation
$('#ajaxform').validate({ ***
....[omitting the validation rules for brevity]
errorElement : 'div',
errorLabelContainer: '#usermessage',
submitHandler: function(form) {
$.ajax({
cache : false,
url : $(form).attr('action'),
type : 'POST',
dataType: 'text',
data : $(form).serialize(),
success : function(data) {
var response = $.parseJSON(data);
if(response['error']){
$('#usermessage').html(response['error']);
}else{
if(response['success']){
$('#usermessage').css({"color":"#00b300","font-weight":"bold"});
$('#usermessage').html(response['success']);
}
}
},
error : function(err) {
alert(err);
}
});
return false;
}
});
});
Here's how I've handled having problems with forms trying to submit even when I'm trying to preventDefault().
I haven't seen your HTML markup so I can't be certain.
If you have a
<button type='submit'>Submit</button>
Change it to
<button type='button'>Submit</button>
and then listen for the click on the button with javascript rather than a form submission
You can change the handler:
submitHandler: function(form) {
To handle the events as well:
submitHandler: function(form, event) {
event.preventDefault();
Related
If i have a page which has an ajax link and that the code returns a that form needs validating, where do i put the validation code please. Say my form had this validation using the jquery validation plugin
jQuery(document).ready(function() {
$("#basicForm").validate({
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function(index, element) {
var $element = $(element);
$element.data("title", "") // Clear the title - there is no error associated anymore
.removeClass("error")
.tooltip("destroy");
});
// Create new tooltips for invalid elements
$.each(errorList, function(index, error) {
var $element = $(error.element);
$element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data("title", error.message)
.addClass("error")
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
});
},
submitHandler: function(form) {
var myselect = $('select[name=ddCustomers]');
//alert(myselect.val());
window.location.replace("customer.php?customer_id=" + myselect.val());
}
});
$("#basicForm").removeAttr("novalidate");
});
where do i put it as the document.ready where i would normally out this code has already been called
I hope this makes sense
Could i have it on the page in the initial page load ready for when the form is returned
I've read i coud have the validation in the document.on function but dont really understand. Would i post something like this back with my ajax response for the validation
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
Thanks for your help. Its confusing and I cant find a decent example on google
EDIT
I know how to write the validation code for the dynamically generated forms so thanks for those answers but I am alright on that. The question is WHERE that code should i put it in the ajax return?
Perhaps i have a misconception but i am using jquery validate module (base assistance( and i have only ever seen the `form validate method called in doc. ready on the first page - never an ajax postback
document.ready
Options
1) Hard coded in page already writing for when form injected by ajax? not dynamic enough - the injected form is created dynamically so the validation may need to
be
2) Add validation code to
document.on
when i do ajax postback for the new form? Is this even possible? Im not a client side programmer.
I am bemused that such a common scenario doesnt have a design pattern. Though i have read postng back forms via ajax is bad practice as it can confuse the browser and now what ajax whs written for so perhaps that why i cant find a solution
thanks
I've coded and developed many web apps just with jquery, php being the server side script. The way I formed was to have the jquery code and html on the same page since jquery needs to check the html element and respond with the proper error message and sanitize all the data fields before I submit to the "form-process.php" for an example if that was the name of your server side script.
Have:
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
code as the same page as say: create-username.html or create-username.php page
html elements. Some prefer to have jquery on the bottom, depends on how you have your
page structured, but I like to put the js on top from old practices although sometimes it doesn't apply to jquery.
include your tooltips code in the same block. I don't like to have jquery all over the place; incase of errors or if you need to modify in future reference it wouldn't be hard to pinpoint to edit, add or fix code. I hope this helps.
You need to initialize the validation plugin first and set up the rules you want. Then when a user submits the form, prevent the default form submission behavior and if all is validated successfully based on the criteria of the rules you set, you manually submit the form to the server using ajax.
$('#basicForm').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
$('document').on('submit', '#basicForm', function(e){
if($(this).valid()){
//client side is valid, make ajax call
}
e.preventDefault();
});
I would like to ask help on jQuery Mobile plugin conflict on my main scripts. Im trying to create another version of the website, which is the mobile version with a bought template that uses jQuery Mobile. Still the site is in CodeIgniter framework based from the web version.
In my main scripts, I have a preventDefault() function on every form submit to display the validation errors. Then when I migrated the site I'm working on with the bought Mobile Template, it seems not to listen to the preventDefault(). whenever I submit a form, it will show validation errors but will change the page seconds after before I could read it. It refreshes the site.
My script looks something like the code below. This works on my web version. >>>
$('form#frm-signup-updates').submit(function(e){
e.preventDefault();
$.post(base_url+'home/subscribe', $('#frm-signup-updates').serialize(), function(data){
if(data == 'success'){
loadpopup();
}
else{
var json = $.parseJSON(data);
$("span.error-notif#name").append(json.name);
$("span.error-notif#email").append(json.email);
}
});
});
Try return false to block submit.
$('form#frm-signup-updates').submit(function(e){
$.post(base_url+'home/subscribe', $('#frm-signup-updates').serialize(), function(data){
if(data == 'success'){
loadpopup();
}
else{
var json = $.parseJSON(data);
$("span.error-notif#name").append(json.name);
$("span.error-notif#email").append(json.email);
}
});
return false;
});
UPDATE:
Well, I checked source code of jQuery Mobile and found that jQM prevent form submit by default, and handle with ajax.
//bind to form submit events, handle with Ajax
$.mobile.document.delegate("form", "submit", function(event) {
var formData = getAjaxFormData($(this));
if (formData) {
$.mobile.changePage(formData.url, formData.options);
event.preventDefault();
}
});
preventDefault is invalid because submit is done by $.mobile.changePage not browser.
So, if wanna prevent submit, that is $.mobile.changePage, I have two suggestions:
1. Add 'data-ajax=false' attribute to form element
demo1
2. Do ajax when submit button clicked
demo2
I have a div set up with a form inside and set to post using ajax and returning the results in the div like so
$(document).ready(function(){
$("#guestList").validate({
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
//$('form').attr('id', 'guestList1')
$.post('brides_Includes/guestlistDisplay1.php', $("#guestList").serialize(), function(data) {
$('#results').html(data)
$("form#guestList")[0].reset();
});
}
});
});
When the results come back it shows the correct changes and replaces the form. However when I post the form again. The relevent changes take place as they should but it then also refreshes the page and shows the posted info in the address bar
How can I post the form and replace it allowing it to post and call the script again without this happening?
the problem with returning forms using ajax is that any JavaScrip code already on the page will not see/take advantage of the new form. The best way to get around this is to pass the JavaScrip and the HTML back using ajax.
Basically you pass the below code back each time you pass a new form back. You'll need to update the IDs and links (brides_Includes/guestlistDisplay1.php). You will need to replace your code on the main page with this code as well because this is needed to execute any JavaScrip passed back.
<script type="text/javascript">
$(document).ready(function(){
$("#guestList").validate({
debug: false,
submitHandler: function(form) {
// do other stuff for a valid form
//$('form').attr('id', 'guestList1')
$.post('brides_Includes/guestlistDisplay1.php', $("#guestList").serialize(), function(data) {
$('#results').html(data);
//This executes the JavaScript passed back by the ajax.
$("#results").find("script").each(function(i) {
eval($(this).text());
});
$("form#guestList")[0].reset();
});
}
});
});
</script>
My adventures continue...
On my page, I want to display a registration form in colorbox, allow the user to submit the form which is processed by a php script and then display a thank you style message in the colorbox which the user will then close.
At the moment I have the processing script in the same page as the form and this works on it's own outside of colorbox.
I've seen similar questions here that suggests to post the form using an ajax call
$('form').live('submit', function(e){
var successHref = this.action,
errorHref = "formError.php";
e.preventDefault();
$('#cboxLoadingGraphic').fadeIn();
$.ajax({
type: "POST",
url: "processForm.php",
data: {someData: $("#someData").val()},
success: function(response) {
if(response=="ok") {
console.log("response: "+response);
$.colorbox({
open:true,
href: successHref
});
} else {
$.colorbox({
open:true,
href: errorHref
});
}
},
dataType: "html"
});
return false;
});
I'm a bit confused with this....
I think I'm ok with sending my form via $,ajax (although any clarity appreciated) but I'm not clear how to handle the response from the form. What do I need my php script to output (and how) so that a thank you message is displayed? Is it simply an echo statement from the php script?
Should I also separate out my processing script from the form )i did it this way as I kept getting path errors and it was easier at the time.
Thanks
Success!
I've managed to get it to work - all logical in the end - shame I'm not very logical..
First move was to separate the php form process script out into a separate file.
Colorbox link to the form all works ok
Used an ajax post to the php script and waited for a message back from the php script.
The php script produces two html messages depending on success or failure which are then displayed in the colorbox by replacing the form html in its div
Yay!
I'd like to add a simple functionality to my pages, where a user will see a "follow" button and by clicking it a db record will be created (userID and pageID). I'll handle query on the backend, I suppose. I think I need to do it in AJAX, but I havebn't done much with AJAX. I was also thinking that updating the button status from FOLLOW to FOLLOWING (or something similar) I could do with jQuery, with some sort of toggle, while the request is being processed on the background.
Am I on the right track with this?
You're on the right track.
I've created an example which uses a button like <input type="image" class="follow">. When I user clicks on it it sends a request to the server (url). On success it updates the button image.
$('input[type=image].follow').click(function() {
var button = $(this);
var current_img = $(button).attr('src');
var current_alt = $(button).attr('alt');
$(button).attr('src', '/style/icons/ajax-loader.gif');
$(button).attr('alt', 'Requesting data from the server...');
$.ajax({
url: url of script the processes stuff (like db update),
type: 'POST',
data: {},
dataType: "json",
error: function(req, resulttype, exc)
{
$(button).attr('src', '/style/error.png');
$(button).attr('alt', 'Error while updating!');
window.setTimeout(function() {
$(button).attr('src', current_img);
$(button).attr('alt', current_alt);
}, 3000);
},
success: function(data)
{
$(button).attr('src', '/style/followed.png');
$(button).attr('alt', 'Followed');
}
});
return false;
});
Above is just some example code. Change it at your will. Have fun with it.
AJAX is right, jQuery makes ajax easy.
//Post with jQuery (call test.php):
$.post('test.php', function(data) {
//Do something with result data
});
It sounds like you are on the right track here. If you're working with a smaller application then using an AJAX request and creating your record would be easiest using a Java servlet and putting for example some JDBC code in your doGet or doPost method to perform the database operations.
At the same time your onSuccess method for your AJAX request can call the jQuery code necessary to update your button. Good Luck!