Magento ajax form validation - ajax

I have a form in Magento that I build in code, and that works with ajax, which I need to validate.
I would like to be able to use Magento's built-in validation functionality, but I don't know how I would trigger it since the form is not submitted. The data is retrieved via ajax and outputted in a list below the form.
Is there someone who can point me in the right direction?
Thanks in advance.
Edit:
This is the javascript code used to hande the ajax request. Its called by the onclick event of the button.
function advancedtranslateSearch(url){
new Ajax.Request(url, {
method: 'get',
parameters: $('search_form').serialize(),
onSuccess: function(transport) {
json = transport.responseText.evalJSON();
$('result').update('<div class="hor-scroll">'+json.records+'</div>');
}
});
}

You should use form's onsubmit event.
To prevent page from reloading you must return false value from your function.

Related

What else can I pass to the `form` property of Ext.Ajax.request?

Normally one posts an ExtJS form to the backend using form.submit({...}). I want to make my form submission synchronous now, so I'm switching to using Ext.Ajax.request({async: false, ...}). The form property of Ext.Ajax.request() usually looks like so:
Ext.Ajax.request({
url: 'formsubmit',
form: 'formid',
method:'POST',
success: function(response, opts) {
alert("successfull");
},
failure:function(res,opt) {
alert("request failed");
}
});
I'm dealing with a bunch of anonymous forms right now. Is there any way around this?
Given a var form = {xtype: 'form', items: [...]}
I've tried replacing 'formid' with form.getEl(), form.getForm(), and form.getForm().getFieldValues() which all don't work.
There's no other way around this other than assigning a generated id to each of my anonymous forms, is there.
Thanks for any input
It looks like you could just do this as an alternative to the form attribute:
var form = this.down('form');
Ext.Ajax.request({
url: 'test.xyz',
params: form.getValues()
// etc...
});
getValues gives you the name/value pairs you need for your submission.
It looks like the ExtJS forms do not actually use form elements in the markup. When the submit function is called on an ExtJS form, an HTML form element is crafted as part of the process, and that's the form that is used for the submission.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.action.Submit-method-buildForm
Ideally, you could modify the options that are used in the Ajax request called within the doSubmit function. Since you can't, you might want to consider overriding Ext.form.action.Submit such that you can, then calling the form.submit() function you mentioned in your question.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.form.action.Submit-method-doSubmit

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

How to get Validation script to work with Mootools form

I hope you can help,
I am relatively new to mootools
I have been using http://zendold.lojcomm.com.br/fvalidator/ to validate some webforms and I wanted to try and use it with an Ajax form. It is an oldish website using Mootools 1.2.5.
http://jsfiddle.net/jessicajet/gTqV8/ is the form I am trying to use it with. (The fValidator script is not added here)
This is what I am using to submit the form
formtostop.addEvent("submit", function(e) {
e.stop();
new Request({
url: this.get("action"),
method: "post",
data: this,
onRequest: function() {
document.id("result").set("html", "sending...");
},
onComplete: function() {
document.id("result").set({html: '<div class="response"><p>Thank you for completing our contact form, we will get back to you as soon as possible</p></div>', style: 'background:red'});
}
}).send();
});
When I hit submit the validation and the ajax form fires, which is to be expected.
Can I get the submit button to look for the validation script before the e.stop(); new Request({ or am I trying to do something not possible?
I will appreciate any advice that can be offered.
http://zendold.lojcomm.com.br/fvalidator/js/fValidator-full.js, take a look at the _onSubmit function. You should extend this class (http://mootools.net/docs/core/Class/Class) and modify the _onSubmit function to do a request if the isValid statement is true.

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

Jquery Validation Plugin, dynamic form validation

I'm using the Jquery Validation Plugin to forms loaded via Ajax (dynamic forms). I know that as of Jquery 1.4, live events on submit is now possible. Now the problem is I want to show a confirm message after the dynamic form has been validated. My code looks like this:
$('.dynamicForm').live('submit',function(){
$(this).validate();
if($(this).valid()){
if(!confirm('Are you sure?'))
e.preventDefault();
}
});
It's not working as expected. Somehow confirmation shows first, then at the second time I submit the form, that's the time the validation happens. Any ideas?
Somehow this seems to work:
$('.dynamicForm').live('mouseover',function(){
$(this).validate({
submitHandler:function(form){
if(confirm("Are you sure?")){
form.submit();
}
}
});
});
Use the submitHandler function available in the validate options:
$(".dynamicForm").validate({
submitHandler: function(form) { //Only runs when valid
if(confirm('Are you sure?'))
form.submit();
}
})
From the docs - submitHandler:
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.

Resources