Ajax form with jquery validation - ajax

I can't make heads or tails of this and am wondering if you could help! When I click on the button, nothing happens. Ideally, I would like the form to validate before submission and to prevent submission if it doesn't validate.
<script type="text/javascript" src="../assets/js/validate/jquery.validate.min.js">
</script>
<script type="text/javascript" src="../assets/js/validate/jquery.validate.more.js">
</script>
<script type="text/javascript" language="javascript">
var J = jQuery.noConflict();
J(document).ready(function(){
J("form#nameform").validate({
rules: {
"name": {
required: true,
format: true},
},
submitHandler: function() {
J.ajax({
type: "POST",
url: "process.php",
data: J("form#nameform").serialize(),
success: function(html) {
J('form#nameform').html('hello');
}
});
};
});
});
</script>
<div id="name">
<form id="nameform" method="post">
<input id="name" class="text" name="name" size="20" type="text">
<input type="submit" value="go" />
</form>
</div>

A lot of tutorial to make Jquery Form valitation, they show how to make ajax validation too :)

Related

How to return views upon Ajax requests in Laravel

Let me start off by saying I am a moderate at Laravel/JQuery so please bear with my question.
I would like to return a view when the user clicks a button, using ajax. Whenever I click the button, I receive no error but also do not get any html. Any help is appreciated.
I defined my routes web.php as:
Route::get('ajax', function() {
return view('test');
});
Route::post('/getmsg', function() {
$msg = "<strong>This is a simple message.</strong>";
$returnHTML=view('form1_sections/section2_form')->render();
return response()->json(array('html'=>$returnHTML, 'msg'=>$msg));
});
My test.blade.php looks like:
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Ajax Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
function getMessage() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/getmsg',
data: '_token = <?php echo csrf_token() ?>',
success: function (data) {
$("#msg").html(data.html);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<form>
<button onclick="getMessage()">Replace Message</button>
</form>
</body>
My section2_form view looks like:
<div class="well">
<div class="row">
<div class="col-xs-12">
<h4>Date of Previous Research Leave</h4>
<br>
<label>Start Date:</label>
<label>
<input class="form-control" name="startDate" id="startDate" placeholder="Start Date" type="date">
</label>
<br><br>
<label>End Date:</label>
<label>
<input class="form-control" name="endDate" id="endDate" placeholder="End Date" type="date">
</label>
</div>
</div>
Set the dataType of your request to json. Also your construction of your token is, well it's not incorrect, but there's a better way, observe the following for the complete answer:
$.ajax({
type: 'POST',
url: '/getmsg',
data: {
token: $('meta[name="csrf-token"]').content()
},
dataType: 'json',
success: function (data) {
$("#msg").html(data.html);
}
});
The reason it needs to be json is otherwise the request assumes the response is text/html. This means that it won't call JSON.parse() on the returned data, so you won't have an object that you can access properties from.

jQuery Mobile and Cordova not sending AJAX HTTP request multi-page model

I have searched this forum for answers and have tried different suggestions that worked for others but did not work for me - including adding the site address to the whitelist in config.xml.
I am working on developing a web app using HTML5, CSS and JavaScript with Cordova 3.5.0-0.2.6 and jQuery Mobile 1.4.3 for the UI. I am using a multi-page JQM page model with the need to make ajax request to submit forms to a server.
Testing the code on localhost works fine but when I build on Android platform in Cordova, the request is not even sent at all as I get the alert message I wrote for when the request is not sent ("Could not connect!").
The code is supposed to use the JSON object returned from the server to display the next page. My codes are as shown below:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery.mobile.theme-1.4.3.min.css" />
<link rel="stylesheet" href="jquery.mobile-1.4.3.min.css" />
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).on("pageinit", function(){
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
<script type="text/javascript" src="jquery.mobile-1.4.3.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
</head>
<body>
<div data-role="page" id="login">
<script>
$(document).bind('mobileinit', '#login', function(){
$(function() {
$("#loginSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
type: "POST",
cache: false,
dataType: "json",
data: $("#loginForm").serialize(),
success: function(result){
if(result.status == "true")
{
alert('Login Successful! ' + result.user);
$.mobile.changePage("#play");
}
else if(result.status=="false")
{
alert('could not login');
}
},
error: function(){
alert('Could not connect!');
}
});
});
return false;
});
});
</script>
</div>
<div data-role="header">
<h1>App Login</h1>
</div>
<div role="main" class="ui-content">
<h4>New account? Sign Up now!</h4><hr>
<form id="loginForm">
<label for="text-basic">Email:</label>
<input type="text" name="email" id="email" value="">
<label for="text-basic">Password:</label>
<input type="password" name="password" id="password" value="">
<br>
<button type="submit" id="loginSubmit">Submit</button>
</form>
<strong>Forgot Password?</strong>
</div>
<div data-role="footer">
</div>
</div>
<!----------------- SECOND PAGE ---------------------->
<div data-role="page" id="plan">
<script>
$(document).on('pagebeforeshow', '#plan' ,function() {
//e.preventDefault();
$('#gamebuttons').empty();
$.ajax({
url: 'http://url-address.php',
dataType: 'json',
Cache: false,
success: function(data) {
$.each(data, function(i,item) {
$('#gamebuttons').append('<button type="button" class="ui-btn ui-btn-inline" name="plannumber" id="gamepanelbutton" value="'+item+'">' + item + '</button>');
});
$('#gamebuttons').refresh();
},
error: function(){
$('#gamebuttons').append('error importing data');
}
});
});
$(document).on("pageshow", "#plan", function(){
$(function(){
$("#playSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
data: $("#play").serialize(),
type: "POST",
cache: false,
dataType: "json",
data: {"am": am, "rl": rl},
//data: {action: 'login', formData: $('#submitForm').serialize()},
success: function(result){
if(result.status == "true") {
alert(result.message);
//$.mobile.changePage("#play");
} else if(result.status=="false") {
alert(result.message);
}
},
error: function() {
alert('Could not send play request: Error executing request!');
}
});
});
return false;
});
});
</script>
<div data-role="header">
<h1>Main page</h1>
Options
Help
</div>
<div role="main" class="ui-content">
<p>
</p>
<form id="play">
<!---the other form elements go here-->
<p>
<button type="submit" class="ui-btn ui-shadow" id="playSubmit">Play</button>
</p>
</form>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
You should clean up your code and take care about indentation. I edited your first post with good indent. You will see that there is a that should not be here in your code, before the <div data-role="header"> of your 1st page:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery.mobile.theme-1.4.3.min.css" />
<link rel="stylesheet" href="jquery.mobile-1.4.3.min.css" />
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).on("pageinit", function(){
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
<script type="text/javascript" src="jquery.mobile-1.4.3.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
</head>
<body>
<div data-role="page" id="login">
<script>
$(document).bind('mobileinit', '#login', function(){
$(function() {
$("#loginSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
type: "POST",
cache: false,
dataType: "json",
data: $("#loginForm").serialize(),
success: function(result){
if(result.status == "true")
{
alert('Login Successful! ' + result.user);
$.mobile.changePage("#play");
}
else if(result.status=="false")
{
alert('could not login');
}
},
error: function(){
alert('Could not connect!');
}
});
});
return false;
});
});
</script>
<div data-role="header">
<h1>App Login</h1>
</div>
<div role="main" class="ui-content">
<h4>New account? Sign Up now!</h4><hr>
<form id="loginForm">
<label for="text-basic">Email:</label>
<input type="text" name="email" id="email" value="">
<label for="text-basic">Password:</label>
<input type="password" name="password" id="password" value="">
<br>
<button type="submit" id="loginSubmit">Submit</button>
</form>
<strong>Forgot Password?</strong>
</div>
<div data-role="footer">
</div>
</div>
<!----------------- SECOND PAGE ---------------------->
<div data-role="page" id="plan">
<script>
$(document).on('pagebeforeshow', '#plan' ,function() {
//e.preventDefault();
$('#gamebuttons').empty();
$.ajax({
url: 'http://url-address.php',
dataType: 'json',
Cache: false,
success: function(data) {
$.each(data, function(i,item) {
$('#gamebuttons').append('<button type="button" class="ui-btn ui-btn-inline" name="plannumber" id="gamepanelbutton" value="'+item+'">' + item + '</button>');
});
$('#gamebuttons').refresh();
},
error: function(){
$('#gamebuttons').append('error importing data');
}
});
});
$(document).on("pageshow", "#plan", function(){
$(function(){
$("#playSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
data: $("#play").serialize(),
type: "POST",
cache: false,
dataType: "json",
data: {"am": am, "rl": rl},
//data: {action: 'login', formData: $('#submitForm').serialize()},
success: function(result){
if(result.status == "true") {
alert(result.message);
//$.mobile.changePage("#play");
} else if(result.status=="false") {
alert(result.message);
}
},
error: function() {
alert('Could not send play request: Error executing request!');
}
});
});
return false;
});
});
</script>
<div data-role="header">
<h1>Main page</h1>
Options
Help
</div>
<div role="main" class="ui-content">
<p>
</p>
<form id="play">
<!---the other form elements go here-->
<p>
<button type="submit" class="ui-btn ui-shadow" id="playSubmit">Play</button>
</p>
</form>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
For your request problem, have you changed the URL to map the real server mapping?

ajax form does not submit

I can't get this form to submit via Ajax to a PHP script and cannot figure out why. Please help. I am planning to use this in phone gap after development and was under the impression this ajax format would work better than xmlhttprequest method - is this really the case?
<html>
<head>
<title></title>
</head>
<body>
<h1>Welcome</h1>
<hr>
<form id="idForm" name="idForm">
<input type="text" size="8" id="date" name="date"><br>
<input type="hidden" size="8" id="reversedate" name="reversedate"><br>
<input type="hidden" size="1" id="dow" name="dow"><br>
<input type="submit" id="submitbutton" name="submitbutton">
</form>
<br><br><br>
<br>
<br>
<p id="p1">x</p>
<br>
log out
<script>
$('#submitbutton').click(function(){
$("#idForm").submit(function() {
var url = "fetchsimple.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/ui.js"></script>
</body>
</html>

ajax helpers in mvc call non-asynchronously

I am developing in asp.net mvc and today I saw some strange thing in using ajax helpers.
If I use Ajax.BeginForm(...) or Ajax.ActionLink(...), they do not call (post to) the actions asynchronously, and they work as they are normal form or normal link, but when I check Request.IsAjaxRequest() in action, it returns true.
For ajax forms, I use
$('#createqfrm').submit(function () {...}
and it works fine, and send the form asynchronously.
Note: I know I have to change .live() to .on() in jquery.unobtrusive-ajax.min since new versions of jquery.
also here are my referenced java libs:
<script src="#Url.Content("~/Scripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Edited:
Checking Request.IsAjaxRequest() and saw that it returns false.
Action Code Added:
public ActionResult GetStriing()
{
if (Request.IsAjaxRequest())
{
return Json("ajax called",JsonRequestBehavior.AllowGet);
}
else
{
return Json("ajax not called", JsonRequestBehavior.AllowGet);
}
}
part of html code for form:
<form action="/admin/xxxx/create" data-ajax="true" data-ajax-success="handeCreateQuestionnareSuccess" id="form0" method="post"> <div class="editor-label">
<label for="Title">title</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="*" id="Title" name="Title" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="Status">Status</label>
</div>
....
<script type="text/javascript">
function handeCreateQuestionnareSuccess(context) {
debugger;
if (context) {
$("#CreateQuestionnarieform").empty().html(context[1]);
$("#CreateQuestionnarieform").append('<input type=hidden name=questionnarieid value=' + context[2] + '/>');
} else {
$("#CreateQuestionnarieform").empty().html(context[1]);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
}
}
</script>
Code that submits form with ajax call:
$('#createqfrm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (context) {
}
});
}
return false;
});
not a solution but can notify other users:
The problem is with jquery 1.9.0 and updates that I get from nuget for jquery.validate.min.js and jquery.validate.unobtrusive.min.js I changed back to 1.8.3 and it works fine.....
Well that sounds like UnobtrusiveJavaScriptEnabled is set to false. Have a look in your AppSettings-File. In section <appsettings> there should be:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
EDIT:
Just found this link after a minute of googling:
http://forums.asp.net/t/1877166.aspx/1?jquery+unobtrusive+ajax+js+error+with+jQuery+1+9+0+updated
Unobtrusive Ajax stopped working after update jQuery to 1.9.0

jquery ajax is not working

i have two files trying to use ajax
here is code of test.php file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
var email = $('#email').val();
$(document).ready(function(){
$("#submit").click(function() {
$.ajax({
url:"test1.php",
success:function(){
alert('');
}
});
});
});
</script>
</head>
<body>
<form method="post">
Email:<input type="text" name="email" id="email" />
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</body>
</html>
and here is code of test1.php file
<?php
echo "hi";
exit;
?>
it is not working i am not able to get alert in sucess function
Change the submit button type to just a button. Otherwise, you are submitting the form before the ajax is firing.
Try giving a return false in the end of the click function.
var email = $('#email').val();
$(document).ready(function(){
$("#submit").click(function() {
$.ajax({
url:"",
success:function(){
alert('');
}
});
return false;
});
});​
This might work!
In this case I'd use the submit event on the form because if you bind the click event on the submit button, the submit event still gets triggered.
see the example here
http://api.jquery.com/submit/

Resources