in ajax form do validation and show a hidden div - javascript

I have this function(to make my form work with ajax):
$(function() {
$('#restore_form').ajaxForm({
beforeSubmit: ShowRequest,
success: SubmitSuccesful,
error: AjaxError
});
});
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function AjaxError() {
alert("An AJAX error occured.");
}
function SubmitSuccesful(responseText, statusText) {
alert("SuccesMethod:\n\n" + responseText);
}
my form(django form) only contains a file upload field. i want also check validation and i have this function for this purpose:
function TestFileType( fileName, fileTypes ) {
if (!fileName) {
alert("please enter a file");
return false;
}
dots = fileName.split(".")
fileType = "." + dots[dots.length-1];
if(fileTypes.join(".").indexOf(fileType) != -1){
alert('That file is OK!') ;
return true;
}
else
{
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
return false;
}
}
now when i try to use validation function(TestFileType) in the first function, it doesn't work. both of them works seperately. fore example if i write the below line in onclick of submit button, it works:
onclick="TestFileType(this.form.file.value, ['tar.gz']);"
I also want instead of alerting user, show a hidden div in success function:
i have:
and i want in success function do:
$('.response').html(responseText);
$('.response').show();
EDIT:
Here is my template:
<form id="restore_form" enctype="multipart/form-data" method="POST" action="restore/">
{{ form.non_field_errors }}
{{ form.as_p }}
{{ form.file.errors }}
<p id="sendwrapper"><input type="submit" value="{% trans "Send" %}" id="submitButton" style="margin-bottom:10px; cursor:pointer; background-color:#F90;"/></p>
</form>
<div class="response" style="display: none;"></div>
but it doesn't work! it seems only alert works in this function. Can you please help me?
really thanks :)

I've attempted to use the AjaxForm plugin in the past and found that unless you have a very specific reason to use it, it's typically easier to write the ajax form submit code without the plugin. This is a simplified/commented version of a previous jquery ajaxform that I created using Jquery without the plugin:
$('form').submit(function(event) {
var form = $(this);
// creates a javascript object of the form data
// which can be used to validate form data
var formArray = form.serializeArray();
// (validate whatever values in formArray you need to check here);
if (form_is_valid) {
var formData = form.serialize(); // a URL-encoded version of the form data for the ajax submission
$.ajax({
type: "POST",
url: someUrl,
data: formData,
success: function(data) {
// update success message boxes here
}
});
} else {
// update client-side validation error message boxes
}
event.preventDefault(); // prevent the form from actually navigating to the action page
});
Hopefully this helps, I've found that the plugin can be useful at times, however I've typically found that this leads to easier to understand code and avoids the use of plugins..

Related

Alert message in browser using Ajax based on Node JS response

I developed a simple form where a user can enter an author name. The name will be queried using Node JS in the database to check if there are tweets written by this author or not. If there is no data, I want to response to the client using Ajax by showing an alert.
This is the client side:
<html>
<head>
<script>
$(document).ready(function() {
$.ajax({
error: function(error){
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
}
}
});
});
</script>
</head>
<body>
<form action="/process_post" method="POST">
<select name="SearchTypes">
<option value="Author" selected>Author</option>
<option value="Mention">Mention</option>
<option value="Tag">Tag</option>
</select>
<input type="text" name="term">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
This is the part of the Node JS that includes the response:
var query = connection.query(queryString, [term,term], function(err, rows) {
console.log(rows);
var tweet = JSON.parse(JSON.stringify(rows));
if (tweet.length == 0){
res.status(500).send('showAlert');
}else{
for(var i in tweet){
res.write("Author: ");
......
As you see, I used res.status(500).send('showAlert'); to send the response to the client side but what really happens is that when I provide an input that does not have any data in the database (tweet length is zero), it just prints showAlert in the HTML page.
That's because the above JavaScript runs the control only if there is an error, but your message is sent as a correct response. You should change your client code to check in case of success, like this:
$(document).ready(function() {
$.ajax({
error: function(error){
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
success: function(result){
if (result.responseText == 'showAlert'){
alert("There was an error")
}else{
//Do things...
}
}
}
}
});
});
You want to wrap the ajax call in a form submit handler. Right now, when you submit the form, it is doing a full synchronous request and coming back with the text "showAlert".
$(document).ready(function() {
$('form').on('submit', function (e) {
// keep the form from submitting synchronously
e.preventDefault();
var $form = $(e.currentTarget);
// submit via ajax
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
data: $form.serialize()
})
.done(function (response) {
console.log('done: ', arguments);
})
.fail(function(error){
console.log('failed: ', arguments);
if(error.responseText == 'showAlert'){
alert("Please enter correct user name and password.");
}
})
});
});
Remove those calls to console.log once you have it working as you need. See $.ajax for options in that call.
You will probably also want to give your form an id and then refer to it that way, e.g. $('#myForm'), so that you can add more forms to the page without causing any problems.

Troubles Submitting Form programmatically

I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

using jquery to make ajax call and update element on form submit

Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});

Help submitting a form to a JQuery script using a javascript submit() function

I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.

Categories