ajax form input file upload loading a separate page in codeigniter - ajax

I am using
<script src="http://malsup.github.com/jquery.form.js"></script>
for my ajax form upload.
When I upload file without the Codeigniter framework this works fine. But when I used it within the frame work it shows me the following error :-
HTTP wrapper does not support writeable connections
plus it is actually loading a separate page
Here's my code :-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
clearForm: true,
resetForm: true
};
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
//alert("Thank you for your comment!");
});
$('#myForm').ajaxForm(options);
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="comment.php" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<br />
<textarea name="comment"></textarea>
<br />
<input type="file" value="Share a Pic" name="file" id="file" />
<br />
<input type="submit" value="Submit Comment" />
</form>
</body>
For Codeigniter I changed the action to
site/submit_myform
So it loads site/submit_myform. Site being my controller. other values are being stored in the database
Thanks

The ajax part isn't working if the page is redirecting. You need to return false; during the on submit to prevent the page from redirecting.
I would suggest following the ajaxSubmit()example provided in the form plugin.

Related

Combine client-side and server-side validation in Bootstrap 4 form

I have a Bootstrap 4 form with an input field, called runname. I want to perform the following validation on the input field:
runname cannot be empty
runname cannot contain spaces
runnamecannot already be used previously
I already have the code for a form which gives an error, using custom Bootstrap styles if the input field is empty:
// JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container">
<div class="col-md-12 order-md1">
<form class="needs-validation" novalidate method="post" action="#">
<div class="form-group row">
<label for="inputRunname" class="col-sm-2 col-form-label">Run name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputRunname" name="runname" placeholder="Run name" required>
<div class="invalid-feedback">
Please enter a run name
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
</body>
</html>
And I have some Javascript to check if an input contains spaces:
function cannotContainWhiteSpace(input, errorId, name) {
var value = input.value;
var errMsgHolder = document.getElementById(errorId);
if (!(/^\S*$/.test(value))) {
errMsgHolder.innerHTML =
'The ' + name + ' cannot contain whitespace';
input.focus();
return false;
}
}
And I also have some Python code on my Cherrypy backend which does a lookup in the database to see if the runname already exists:
try:
myConnection = mysql.connector.connect(host=self.database['host'], user=self.database['user'], passwd=self.database['passwd'], db=self.database['db'])
cursor = myConnection.cursor(buffered=True)
# unless overriden by the force flag, check whether the runname has already been used before
if not force:
reusedrunquery = "SELECT run FROM logs WHERE run = %s AND errormessage IS NULL"
cursor.execute(reusedrunquery, (runname,))
if cursor.fetchall():
flag = True
cherrypy.session['reusedRun'] = True
myConnection.close()
except mysql.connector.Error as err:
return self.database_failure(str(err))
But I don't know how to cobble all these different parts together to get a form where I have both the two client-side validations and the server-side validation.
On Submit event, you should have a method in your backend that actually intercepts the request and I think there you should be able to make a connection with your backend's logic.
Here they are the steps:
Form compiled correctly
Http POST request starts onSubmit event
Back-end receives the request and applies further logic by gathering the data on the method in charge to receive the Http POST request
Otherwise, you may try to make an AJAX call on which there will be executed the client-side validations and then it will call the server-side method/class for checking that runname has been used already.
Most of the times I use custom styles to achieve this.
.invalid-feedback{
display:none;
}
.invalid .invalid-feedback {
display:block;
}
<form novalidate>
<div class="form-group">
<label>Label</label>
<input class="form-control" name="runname" type="text">
<div class="invalid-feedback"></div>
</div>
</form>
In Javascript
Validate the input controls and set css classes and message text.In your case, validate not empty, no spaces, and not already used[server side].
If invalid add the class invalid to parent form-group, and set the validation message inside invalid-feedback div next to the input control.

Bootstrap validator - submitting fom without correct validation

Good Day!
I have a contact form that is using bootstrap validator.
I am able to get the (in)validation of the fields to show up as expected, but it does not seem like the submit button is "respecting" the (in)validation before submitting - the fields does not HAVE to be validated in order for the form to be submitted. I am using ajax in order to submit the form without realoding the entire page.
The ajax code should be located in the mashup.js file, of my contact test page!
(in case you have not already noticed it, I am a n00b - and would really appreciate the help:)
UPDATE: (This is the current code)
.html
<meta charset="utf-8">
<!-- Website Title & Description for Search Engine purposes -->
<title>Contact Form</title>
<!-- Mobile viewport optimized -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Content-Type -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- Bootstrap CSS -->
<link href="includes/css/bootstrap.min.css" rel="stylesheet">
<link href="includes/css/bootstrap-glyphicons.css" rel="stylesheet">
<!-- Responsive Navigator -->
<link rel="stylesheet" href="includes/nav/responsive-nav.css">
<!--<link rel="stylesheet" href="includes/nav/nav_styles.css">-->
<!-- Include Modernizr in the head, before any other Javascript -->
<script src="includes/js/modernizr-2.6.2.min.js"></script>
<!-- BootStrap Validator CSS -->
<link rel="stylesheet" href="includes/css/bootstrapValidator.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="includes/css/style.css">
</head>
<body>
<div class="container">
<div class="row">
<br>
<form id="html5Form" method="post" action='mail/mail.php'
class="form-horizontal"
data-bv-message="This value is not valid"
data-bv-feedbackicons-valid="glyphicon glyphicon-ok"
data-bv-feedbackicons-invalid="glyphicon glyphicon-remove"
data-bv-feedbackicons-validating="glyphicon glyphicon-refresh">
<div class="form-group">
<label>Name</label>
<input class="form-control" placeholder="Name.." type="text" name="name" id="name"
data-bv-message="The username is not valid"
required data-bv-notempty-message="The username is required and cannot be empty"
pattern="^[a-zA-Z0-9]+$" data-bv-regexp-message="The username can only consist of alphabetical, number"/>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" placeholder="Email.." name="email" id="email" type="email" required data-bv-emailaddress-message="The input is not a valid email address"/>
</div>
<div class="form-group">
<label>Message</label>
<textarea class="form-control" name="message" id="message" rows="7" required
data-bv-notempty-message="No empty message"></textarea>
</div>
<input type="submit" id="submit" name="submit" value="Send"/>
</form>
<div class="loading">
Sender melding...
</div>
<div class="success">
</div>
</div>
</div> <!-- End content -->
<!-- Include jQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include Mashup -->
<script src="includes/js/mashup.js"></script>
<!-- Bootstrap JS -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<!-- BootStrap Validator JS -->
<script src="includes/js/bootstrapValidator.min.js"></script>
<script>
$(document).ready(function() {
$('#html5Form').bootstrapValidator();
});
</script>
</body>
</html>
.js
$(document).ready(function() {
$('form').on('submit', function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$(".loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$(".loading").fadeOut(function() {
//Display the "success" message
$(".success").text(data).fadeIn();
});
}
});
});
});
});
});
From looking at the provided Ajax example, it looks like you need to be watching for .on('success.form.bv'), not .on('submit'). So you would need to modify your event handler to look like this:
$('form').on('success.form.bv', function(e) { ... });
Hope this helps.

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

attaching a jquery validation engine on a keyup event

I am using jquery validation engine in my project on the input fields.
The code structure is like this
<form>
<input/>
<input/>
</form>
and i validate the fields in keyUp.
Now how do i show the prompt only on the input that has a focus.
or in otherwise how do i validate a single input element that has focus inside a particular form as the validation engine is attached to the form..
I use JavaScript-MVC framework
Please do help me. Thanks in advance
To validate a single input element that has focus inside a particular form on keyup try this
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.10.0/jquery.validate.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('form').validate({ onkeyup: false });
$('form').bind('keyup', function () {
$(':focus', this).valid();
});
});
</script>
</head>
<body>
<form>
<input name="one" class="required number"/><br />
<input name="two" class="required" /><br />
<input type="submit" />
</form>
</body>
</html>

Resources