jQuery validation submitHandler not work in $.ajax post form data - javascript

I have Send data using $.ajax and validation with jQuery validation plugin like this :
<div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
JS:
jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
In action my form validate using jQuery validation but after validation not submit and not send data.
how do fix this problem?!
DEMO HERE

The submitHandler is expecting a submit and you have a click event inside it and then an ajax call.
If you have a button type="submit" inside a form you don't even need a click event, the plugin will do the validation automatically. So just make the ajax call inside the submitHandler.
If you need to bind the action to a button using the click event, the proper approach should be something like this:
$('#button').click(function(){
var form = $('#myform').validate({...}); #store the validator obj
if (form.is_valid()){
// submit using ajax
} else {
// dont do anything
}
});

Call form.submit() at the end of your done function.
See: http://jqueryvalidation.org/validate/
Also, you do not need $("#ajax-1").click() because the submitHandler will be called automatically when you click on that button anyways. You can test this yourself by putting a console.log as the first line of submitHandler. Then fill out the form and press the button. See if it prints out your log message.

In submitHandler you are handling the submit , then again why did you write click event?
Here is the fix.
jQuery(document).ready(function($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [2, 20],
},
},
submitHandler: function(a, e) {
//a is form object and e is event
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false,
success: function(data) {
console.log(data)
},
error: function(err) {
console.log(err)
}
}).done(function(data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function(jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
Use success and error call backs to get data or error messages.
Note: Here (In StackOverflow) you will get 404 Page Not Found error when you submit. So try in your local.

Related

Button disappears when clicked in javascript

In case that chosen attributes are the same, after clicking "Save button" - button disappears.
(it disappears from code, got deleted)
[Image before clicking][1]
[Image after clicking][2]
Most confusing thing is that, add button was coded the same but it works well...
I've got no clue what might be the case here.
Button:
<input type="button" height="20" class="btn btn-warning" onclick="return saveEdit()" value="Save" />
function saveEdit() {
var elem = $('#Domain_Edit');
$.ajax({
url: "/Domain/DomainEdit",
type: "post",
data: elem.serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
alert(window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage);
}
else
{
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Code of button on page:
<input type="button" height="20" class="btn btn-warning" onclick="return btnSave('89515a0b-a671-4eff-a0eb-61c1d268f696')" value="Save">
function btnSave(id) {
var elem = $("." + id).closest('#DomainTrust_Edit');
$.ajax({
url: "/Domain/DomainTrustEdit",
type: "post",
data: $("." + id).closest('#DomainTrust_Edit').serialize(),
cache: false,
success: function (result) {
if (result.redirectTo) {
// The controller action returned a JSON object with the redirectTo property
window.location.href = result.redirectTo + '?siteMessage=' + result.siteMessage;
} else {
// The controller action returned a partial view with the form and the errors so update of the containing FORM with it is needed.
$(elem).html(result);
}
},
error: function (xhr, status, error) {
$(elem).html('<div class="alert alert-danger" role="alert">' + xhr.status + " " + xhr.statusText + '</div>');
}
});
}
Is your button located inside the #Domain_Edit element?
Since .html(result) replaces all html inside #Domain_Edit so if your button is inside that element, that would explain why it got removed.

Highlight and append msg to element on return from .ajax

Upon ajax successful return, the return data contains status. if status is false(not ajax fail), return data contains array of element names and associated error message. The goal is to replicate .validate() error functionality by appending msg after element and highlight.
HTML form:
<form class="form-horizontal" id="chngPwdForm" action="changepwd.php" method="post">
.
. various HTML....
.
<div class="form-group">
<div class="alert alert-div font-weight-bold" id="errorTxt" role="alert" style="display:none;"> </div>
<label for="crntPwd">Existing Password:</label>
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-key fa-fw"></i></span>
<input type="password" class="form-control" id="crntPwd" name="crntPwd" required>
</div>
</div>
.
. more HTML follows
.
JQUERY:
.
.yada, yada, yada
.
$("#chngPwdForm").submit(function(event){
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $("#chngPwdForm").attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var element;
var errorObj = new Error("");
$.each(data.Msg, function(elemName, errMsg) {
element = $("#chngPwdForm").filter("#" + elemName);
errorObj.message = errMsg;
$(element).closest(".form-group").addClass("has-error");
errorObj.insertAfter(element);
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})
.fail (function(response){
var Msg = "chngPwd call failed. errorThrown: " + response;
var obj = JSON.stringify(response);
alert("obj is: " + obj);
$('#chngPwdForm div[id="errorTxt"]').text(Msg);
})
}
else {
$('#chngPwdForm div[id="errorTxt"]').text('Please Correct errors').show();
}
return false;
The JSON response from changepwd.php:
{\"status\":false,\"Msg\":{\"crntPwd\":\"Current Password may only contain a-z, A-Z, 0-9, ! or #\"}
JS error
"TypeError: errorObj.insertAfter is not a function" is thrown for
"errorObj.insertAfter(element);"
The implemented solution:
JQuery:
// New Code has leading and trailing *
$("#chngPwdForm").submit(function(event){
*$(".chngPwderr").removeClass("error").text('');* //used to remove old messages
event.preventDefault();
if ($("#chngPwdForm").valid() ) {
$('#chngPwdForm div[id="errorTxt"]').hide();
Msg = $('#chngPwdForm div[id="errorTxt"]').text("Password changed. Click on Login to continue.");
var formURL = $(this).attr('action');
$.ajax({
url: formURL,
type: 'POST',
data: $(this).serialize(),
dataType: 'JSON'
})
.done (function(data, textStatus, jqXHR) {
if (!data.status) {
var Msg = "Password Not Changed. Password Change Failed.";
var focusSet = false;
$.each(data.Msg, function(elemName, errMsg) {
*$("#" + elemName).attr("type", "text");
if (!$("#" + elemName).parent().hasClass("error")) {
$("#" + elemName).parent().append('<div class="chngPwderr error">' + errMsg + '</div>');
}
if (!focusSet) {
$("#" + elemName).focus();
focusSet = true;
}*
});
}
$('#chngPwdForm div[id="errorTxt"]').text(Msg).show();
})

Why doesn't jquery submit work properly?

This code works fine in its current state where im using a click event on a button. But if i use a form tag around the input tags in my html code and use jquery's submit method it doesnt give any results. why is that happening? i have to use the form element because i want to be able to search with an enter key insted of clicking on a button
Html:
<body>
Title: <input type="text" id="title"><br/>
<input type="submit" value="Submit" id="btn">
<p id="results"></p>
<body>
jQuery:
$(document).ready(function(){
$("#btn").on("click", function(){
var textval = $('#title').val();
var playListURL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + textval + '&format=json&callback=?';
$.ajax({
type: "GET",
url: playListURL,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
for (var i = 0; i < 10; i++)
{
var url = "https://en.wikipedia.org/wiki/" + data.query.search[i].title;
$("#results").append("<b> <a href='" + url + "' > " + data.query.search[i].title + "</a></b></br> ");
//console.log(url);
}
},
error: function (errorMessage) {
}
});
//alert($('#title').val());
});
});
Try to change this line
$("#btn").on("click", function(){
to this:
$("#btn").on("click", function(e){
e.preventDefault();
Then the form will not submit default way on click

jQuery ajax to PHP, returning Error and empty object

I am trying to use jQuery ajax to call PHP and return JSON.
My test is very simple, but all I seem to be getting is an empty object.
I am not getting any PHP errors in the LOG File.
jqXHR is shown as an object with the 'alert', but does not appear in the 'Chrome' console.
The 'Unpacked' alert does not show at all
I have obviously missed something or made some stupid error, but I can not see what I have done wrong.
HTML
<body>
<form id="frmSearch" onsubmit="matchQryString();">
Search: <input type="text" name="qryWords" value="" />
<input type="submit" name="submit" value="Search" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function matchQryString() {
alert("Running AJAX");
$.ajax({
type:'POST',
url: 'rtnJSON.php',
data:$('#frmSearch').serialize(),
dataType: 'json',
success: function(response) {
alert("PHP Return SUCCESS");
alert(response);
},
error: function (jqXHR, exception) {
alert("PHP Return ERROR");
alert(jqXHR);
alert(exception);
console.log(jqXHR);
var op = "";
for (property in jqXHR) {
op += property + ': ' + obj[property]+'; ';
}
alert ("Unpacked: " + op);
}
});
return false ;
}
</script>
</body>
PHP
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
header('Content-type:application/json;charset=utf-8');
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
form being submitted before $.ajax() call ? Try removing onsubmit from html , type="submit" from input element , attaching click event to type="submit" element , calling .e.preventDefault() within click handler . Also note, obj does not appear defined within error handler of $.ajax()
html
<form id="frmSearch"">
Search: <input type="text" name="qryWords" value="" />
<input type="button" name="submit" value="Search" />
</form>
js
$(function() {
function matchQryString(e) {
e.preventDefault();
alert("Running AJAX");
$.ajax({
type:'POST',
url: 'rtnJSON.php',
data:$('#frmSearch').serialize(),
dataType: 'json',
success: function(response) {
alert("PHP Return SUCCESS");
alert(response);
},
error: function (jqXHR, exception) {
alert("PHP Return ERROR");
alert(jqXHR);
alert(exception);
console.log(jqXHR);
var op = "";
for (property in jqXHR) {
op += property + ': ' + obj[property]+'; ';
}
alert ("Unpacked: " + op);
}
});
};
$("[name=submit]").on("click", matchQryString);
})

create form dynamically and submit it

So I have a jQuery plugin I wrote below, in plugin.js. I want to be able to also submit the form via JSON/AJAX every time it's created.
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
$('#form').submit(function(e)
{
var postData = form.find('form').serializeArray();
if(postData.name === "someREGEXstring" || postData.email === "someREGEXstring") {
console.log("empty inputs not cool");
}
var formURL = $('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
$('#form').submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
in HTML view
<div id="newForm"></div>
<script>
$(document).ready(function(){
$("#newForm").create();
});
</script>
Is this the correct way to make this or should I:
Create a another namespace under the same file for the AJAX portion
Create another namespace under a different file the AJAX portion
If the question is purely about how to arrange the code, I would suggest you pull the form template out of the code completely and make your plugin more flexible.
Option 1. Create the form as a template in the page and pass the
template selector to plugin as an option
Option 2: Pass the template to your plugin
Here is an example of the first technique: http://jsfiddle.net/TrueBlueAussie/c8bmw/7/
Template in HTML:
<script id="template" type="template">
<div id="form" class="container">
<div>User Login</div>
<form action="/create/one" method="post"/>
<input type="text" name="name" placeholder="name"/>
<input type="email" name="email" placeholder="email"/>
<button type="submit">Login</button>
</form>
</div>
</script>
Create with:
$(document.body).create('#template');
And plugin simplified to:
(function ( $ ) {
$.fn.create = function(template) {
form = $($(template).text());
form.submit(function(e) {
// This is the actual form object now
var $form = $(this).find('form');
// Test contents of form here
// If values are correct proceed with Ajax call
var postData = $form.serializeArray();
var formURL = $form.attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); // Stop default action
});
return this.append(form);
};
}( jQuery ));
Now your plugin code will work with any form.
Based on your comment I have removed the automatic submit of the form, as that made no sense
This should work:
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
form = $(form);
form.submit(function(e) {
var postData = form.find('form').serializeArray();
var formURL = form.find('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
form.submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
Here is a demo in JSFiddle.
What is fixed:
form = $(form) is used in order to create the DOM elements based on the form string.
Change the way postData, formURL are initialized.
<div id="#newForm"></div>
should be
<div id="newForm"></div>
to load this form element
I have some chages, like:
$('#form').submit(function(e) should be $(form).submit(function(e) as variable form contains all the HTML of form wrapped within DIV.
in the submit of form, $(this) will refer to the form element itself.
Here is the modified code:
(function ($) {
$.fn.create = function () {
var formContainer = $("<div />", {
id : "form",
class : "container"
}).append("<div>User Login</div>");
var form = $("<form />", {
action: "/create/one",
method : "post",
submit : function(e){
var actionUrl = $(this).attr("action");
alert(actionUrl); // just to check if this is working or not
$.ajax({
url : actionUrl,
type : "POST",
data : $(this).serializeArray(),
success : function (data, textStatus, jqXHR) {},
error : function (jqXHR, textStatus, errorThrown) {}
});
e.preventDefault();
}
})
.append('<input type="text" name="name" placeholder="name"><input type="email" name="email" placeholder="email"><button type="submit">Login</button>')
.appendTo(formContainer);
return this.append(formContainer);
};
}(jQuery));
$("#test").create();
HTML for testing:
<div id="test"></div>
JS fiddle: http://jsfiddle.net/ashishanexpert/y99mt/2/
I have created the HTML nodes via jquery instead of just HTML string. attaching events to nodes is easier than converting string to HTML first and then attaching event to them. Hope you like it.

Categories

Resources