I am trying to save some store details and getting a response from the controller using Ajax but when I am trying to do so the request is not received by the Controller please see the code and help me what I am doing wrong here.
MasterAjaxClass: The class is used to send the request and receive a response
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
/*toggleSpinnerOff();*/
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
/*toggleSpinnerOff(); */
callBack(responseData,textStatus);
}
});
}
//return this.responseData;
}
}
Ajax Request method
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append("logoURL", $("#file-input-2").val());
console.log($("#storeName").val());
console.log($("#country").val());
console.log($("#city").val());
console.log($("#street").val());
console.log($("#address").val());
console.log($("#zipCode").val());
console.log($("#storeDescription").val());
console.log($("#storeOpenTime").val());
console.log($("#file-input-2").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
StoreForm.jsp
<form:form name="storeForms" modelAttribute="storeForm"
method="POST" enctype="multipart/form-data">
<%-- <c:if test="${not empty error}">
<div class="alert alert-danger" role="alert">
<h5 class="alert-heading">Failed to Save</h5>
<hr>
<p>${error}</p>
</div>
</c:if>
--%>
<!-- Hidden For Update employee -->
<form:input type="hidden" path="id" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<form:input type="text" path="storeName" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<form:input type="text" id="country" path="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<form:input type="text" id="city" path="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<form:input type="text" id="street" path="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<form:input type="text" id="address" path="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<form:input type="text" id="zipCode" path="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<form:input type="text" path="storeDescription" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<form:input type="text" path="storeOpenTime" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<form:input type="file" path="logoURL" id="file-input-2"
data-default-value="Size of logo should not Exeed 1mb" />
<label for="file-input-2">Choose logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore();" value="Add Store">
</div>
</form:form>
Controller Method
#Controller
#RequestMapping("/store")
public class StoreController {
#ResponseBody
#RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(#ModelAttribute("storeForm") StoresDTO store,#RequestPart("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
Error On browser Console
Status :403
Related
someone please help im trying to submit details together with image to databasei need help in figuring this whole thing out
<form id="register-form">
<!-- <div class="form-group">
<input type="file" id="imageInput" accept="image/*">
</div> -->
<div class="form-group">
<div class="file-upload">
<div class="image-upload-wrap">
<input name = 'sampleFile' enctype = "multipart/form-data" class="file-upload-input" type='file' id="profilepic" onchange="readImage(this)"
accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content d-none">
<img class="file-upload-image" src="#" id="imgPreview" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span
class="image-title">Uploaded Image</span></button>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
// document.getElementById("addImage").addEventListener("change", function () {
// readImage(this);
//});
// document.getElementById("submitBtn").addEventListener("click", function () {
// var title = document.getElementById("title").value;
//});
function readImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = e.target.result;
document.getElementById("imgPreview").style.display = "block";
};
reader.readAsDataURL(input.files[0]);
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const pic = $("#profilepic").val()
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
image: pic,
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
const formData = new FormData();
formData.append("image", pic);
formData.append("title", title);
formData.append("description", description);
formData.append("release_year", release);
formData.append("language_id", lang);
formData.append("rental_duration", rental_duration);
formData.append("rental_rate", rental_rate);
formData.append("length", length);
formData.append("replacement_cost", replacement_cost);
formData.append("rating", rating);
formData.append("special_features", feature);
formData.append("category_id", category_id);
formData.append("actors", actors);
formData.append("store_id", store_id);
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, formData, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(formData)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/home");
});
}
</script>
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.post("/upload", (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file in a upload directory
sampleFile.mv("./upload/" + sampleFile.name, (err) => {
if (err) return res.status(500).send(err);
res.send("File uploaded!");
});
});
my html form code and app.js code i just cannot send image to database idk why, i try usin express file upload but the code just cannot insert it in. Someone, please help i have 48 hours left before my deadline please!!!!!! this is my first time doing this , someone guide me
I have an issue about submitting a form via ajax and open a modal Dialog after the ajax function is completed successfully. When I click a submitButton, the process cannot be completed.
Where is the problem in an ajax method or anywhere?
How can I fix it?
Here is my form HTML part.
<form id="contactForm" role="form" class="php-email-form">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton" data-bs-toggle="modal">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</form>
Here is my modal part.
<div class="modal fade" id="modalDialog" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#ViewBag.Success
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Kapat</button>
</div>
</div>
</div>
</div>
Here is my javascript part.
<script type="text/javascript">
$(document).ready(function () {
$("#submitButton").click(function () {
var nameSurname = $("#nameSurname").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
var form = $('#contactForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Home/Contract/',
data: {
__RequestVerificationToken: token,
nameSurname: nameSurname, email: email, subject: subject, message: message
},
type: 'POST',
success: function (data) {
$("#modalDialog").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('custom message. Error: ' + errorThrown);
}
});
});
})
</script>
Here is my Contract action in Home Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail);
ViewBag.Success = "Success";
}
else
{
ViewBag.Error = "Error";
}
return View();
}
EDIT
After I realized Ok() isn’t accessible in an MVC controller I found this solution which does essentially the same thing.
In your controller, change:
return RedirectToAction(“contract”);
To:
return new HttpStatusCodeResult(HttpStatusCode.OK);
RedirectToAction() and View() will by default load or refresh a page while a 200 (OK) response will just return a success status code.
You can do it this way:
View:
#using (Ajax.BeginForm("Contract", "ControllerName", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</div>
</div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
// do what is necessary
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail)
return Json("Success", JsonRequestBehavior.AllowGet);
}
else // return result
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
}
We have to create OnSuccess function in view to do something with result;
<script>
function OnSuccess(data) {
if (data == 'Success') {
$("#modalDialog").modal('show');
}
}
function OnFailure(data) {
//log failure
}
function OnBegin() {
// do something on begin
}
</script>
Using Laravel framework.
I don't get it. I have a hidden input with id = prime near the top.
<form name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
{{ csrf_field() }}
<input type="hidden" id="parking_lot_id" name="parking_lot_id" value="{{ $parking_lot_id }}">
<input type="hidden" id="booking_id" name="booking_id" value="{{ $booking_id }}">
<input type="hidden" id="Price" name="Price" value="{{ $Price }}">
<input type="hidden" id="prime" name="prime"> {{-- To be obtained --}}
<legend>電子發票 & TapPay 付款</legend>
<div class="form-group">
<label for="CustomerEmail" class="col-lg-3 col-md-3 col-xs-4">電子信箱</label>
<div class="col-lg-9 col-md-9 col-xs-8">
<input type="email" class="form-control" id="CustomerEmail" name="CustomerEmail" value="{{ old('CustomerEmail') }}">
</div>
</div>
<div class="form-group">
<label for="CustomerPhone" class="col-md-3 col-xs-4">手機號碼</label>
<div class="col-md-9 col-xs-8">
<input type="number" class="form-control" id="CustomerPhone" name="CustomerPhone" value="{{ old('CustomerPhone') }}">
</div>
</div>
<hr>
<div class="form-group">
<div class="col-md-offset-3 col-xs-offset-4 col-md-9 col-xs-8">
<select class="form-control" id="giveTongBian" name="giveTongBian">
<option value="no" #if(old('giveTongBian') === "no") selected #endif>不需統編</option>
<option value="yes" #if(old('giveTongBian') === "yes") selected #endif>輸入統編</option>
</select>
</div>
</div>
<div class="form-group" id="customerIdentGroup">
<label for="CustomerIdentifier" class="col-md-3 col-xs-4">統一編號</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerIdentifier" name="CustomerIdentifier" value="{{ old('CustomerIdentifier') }}">
</div>
</div>
<div class="form-group" id="customerNameGroup">
<label for="CustomerName" class="col-md-3 col-xs-4">買受人</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerName" name="CustomerName" value="{{ old('CustomerName') }}">
</div>
</div>
<div class="form-group" id="customerAddrGroup">
<label for="CustomerAddr" class="col-md-3 col-xs-4">地址</label>
<div class="col-md-9 col-xs-8">
<input type="text" class="form-control" id="CustomerAddr" name="CustomerAddr" value="{{ old('CustomerAddr') }}">
</div>
</div>
<div class="tappay-form col-xs-offset-1 col-xs-10">
<h4 style="color: darkkhaki;">信用卡</h4>
<div class="form-group card-number-group">
<label for="card-number" class="control-label"><span id="cardtype"></span>卡號</label>
<div class="form-control card-number"></div>
</div>
<div class="form-group expiration-date-group">
<label for="expiration-date" class="control-label">卡片到期日</label>
<div class="form-control expiration-date" id="tappay-expiration-date"></div>
</div>
<div class="form-group cvc-group">
<label for="cvc" class="control-label">卡片後三碼</label>
<div class="form-control cvc"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Pay</button>
</div>
</div>
</form>
I then have a on submit event which does a few things. At the bottom is me updating the hidden input with id = prime.
$('form').on('submit', function (event) {
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
//Begin validation
var numOfNonEmptyFields = 0;
if(document.forms["paymentForm"]["CustomerEmail"].value != "") {
numOfNonEmptyFields++;
}
if(document.forms["paymentForm"]["CustomerPhone"].value != "") {
numOfNonEmptyFields++;
}
if(numOfNonEmptyFields == 0) {
errorMsg += "請輸入至少一個電子信箱或手機號碼.\n";
boolFlag = false;
}
//End validation
//Final steps: overall error message + success or fail case
if(boolFlag == false) {
alert("錯誤:\n" + errorMsg);
return false;
}
//Code for first part of form end
// fix keyboard issue in iOS device
forceBlurIos()
const tappayStatus = TPDirect.card.getTappayFieldsStatus()
console.log(tappayStatus)
// Check TPDirect.card.getTappayFieldsStatus().canGetPrime before TPDirect.card.getPrime
if (tappayStatus.canGetPrime === false) {
bootbox.alert({
title: "錯誤訊息",
message: "取得不了Prime.",
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false
}
$("#prime").val(result.card.prime);
})
})
I've tested the hidden input with alert($("#prime").val()) directly after and it seems updated, however after submission, my Controller receives the value as null while other hidden input values are correct. So I suspect it's something got to do with the on submit event.
Added id attribute to the form element:
<form id="paymentForm" name="paymentForm" action="/parking_302/upload_payment" method="POST" role="form" class="form-horizontal">
Removed type from the button and added id:
<button id="submit-btn" class="btn btn-default">Pay</button>
Introduced a new click listener:
$(document).on("click","#submit-btn", function(event){
event.preventDefault();
validateAndSendForm();
});
Introduced a new function for the final form submit:
function submitForm(){
//do other stuff here with the finalized form and data
//.....
$( "#paymentForm" ).submit();
}
And put all of your old things into a new function as well:
function validateForm(){
//Code for first part of form begin
var boolFlag = true; //Default is submit
var errorMsg = ""; //Initial message
...
...
...
}
// Get prime
TPDirect.card.getPrime(function (result) {
if (result.status !== 0) {
bootbox.alert({
title: "錯誤訊息",
message: result.msg,
buttons: {
ok: {
label: "OK",
className: "btn btn-primary"
}
}
});
return false;
}
$("#prime").val(result.card.prime);
//use when you are ready to submit
submitForm();
})
}
So, basically you will have a "submitForm" function that you can use whenever you are ready to submit the form.
Seems like TPDirect.card.getPrime is something that gets data asynchronously so the $('form').on('submit' function won't wait for it to finish.
I'm getting this error when I try to update a file on my form..."You did not select a file to upload." ...and the problem is that I really am selecting a new file to upload...help me pls, I don't understand what is happening ...here is my code:
FORM
<form class="col s12" id="update_form" required="" enctype="multipart/form-data" aria-required="true" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" required="" aria-required="true" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" required="" aria-required="true" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" required="" aria-required="true" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" required="" aria-required="true" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación/Imagen</span>
<input type="file" name="animation">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" id="animation" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" required="" aria-required="true" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
CONTROLLER
public function update_politic(){
$this->load->model("politic");
$params;
if ($this->input->is_ajax_request()) {
if (empty($this->input->post("animation"))){
echo "first";
$data = $this->politic->get_file_name($this->input->post("update_politic_hide"));
$file = $data->POLITIC_FILE;//recupero el nombre de la imagen
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["section"] = $this->input->post("section");
$params["animation"] = $file;
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
else {
echo "second";
$config['upload_path'] = "./public/uploads/";
$config['allowed_types'] = "*";
//$config['overwrite'] = "true";
$config['max_size'] = "500000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
//$file = "animation";
if (!$this->upload->do_upload("animation")) {
$data['uploadError'] = $this->upload->display_errors();
echo $this->upload->display_errors();
}
else {
$file_info = $this->upload->data();
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $file_info['file_name'];
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
}
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
"POLITIC_FILE" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
JAVASCRIPT
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
$.post(baseurl + 'admin/update_politic', chango,
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
function update_politic(id, name, lastname, section, side, charge, file) {
$("#update_politic_hdn").val(id);
$("#update_name").val(name);
$("#update_last_name").val(lastname);
$("#update_side").val(side);
$("#update_charge").val(charge);
$('[name=section]').val(section);
$("#animation").val(file);
$('select').material_select();
}
There are two name attributes having the same value animation.
<input type="file" name="animation">
and
<input class="file-path validate" id="animation" name="animation" type="text">
The second name attribute is overriding the first one. You need to give it a different name.
Change your Ajax code :
$("#update_politic_btn").click(function(event) {
var chango = new FormData($("#update_form")[0]);
// try this if above one not work
//var chango = new FormData($("#update_form"));
$.ajax({
url: baseurl + 'admin/update_politic',
type: 'POST',
data: chango,
async: false,
success: function (data) {
console.log(data);
list_politic();
},
cache: false,
contentType: false,
processData: false,
error : function() {
}
});
event.preventDefault();
});
I have created a Ajax form to handle the errors in my login form, but instead of showing errors in the form area, it directs me to another page with the json error response
<div class="container-fluid bg-primary" id="login">
<div class="row">
<div class="col-lg-3 text-center">
</div>
<div class="col-lg-6 text-center">
<h1> </h1><h3> </h3>
<h2 class="section-heading">Login to your profile</h2>
<hr>
</div>
<div class="col-lg-3 text-center">
</div>
<h2> </h2>
<h2> </h2>
<h2> </h2>
</div>
<div class="col-md-4 col-md-offset-4 ">
<form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
{% csrf_token %}
<fieldset >
<div class="form-group">
<input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
</div>
</fieldset>
<button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
<span class="login-error"></span>
<h1> </h1><h1> </h1>
</form>
</div>
My ajax code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login-ajax/";
$.ajax({
type: "POST",
url:url,
data: $("#loginform").serialize(),
success: function(data)
{
console.log(data);
var result = JSON.stringify(data);
if(result.indexOf('errors')!=-1 ){
console.log(data);
if(data.errors[0] == "Mobile number and password don't match")
{
$('.login-error').text("Mobile number and password don't match");
}
else if(data.errors[0] == "Entered mobile number is not registered")
{
$('.login-error').text("Entered mobile number is not registered");
}
}
else
{
window.open("/users/profile/");
}
//var result = JSON.stringify(data);
// console.log(result);
}
})
});
My code for the action in views.py
def login(request):
if request.method == 'POST':
mobile_number = request.POST.get('mobile_number', '')
password = request.POST.get('password', '')
data = {}
user_queryset = User.objects.filter(mobile_number=mobile_number)
if len(user_queryset) == 0:
data['error'] = []
data['error'].append("Entered mobile number is not registered")
# return JsonResponse(data)
elif len(user_queryset) == 1:
email = user_queryset[0].email
user = auth.authenticate(email=email, password=password)
if user is not None:
auth.login(request, user)
else:
data['error'] = []
data['error'].append("Mobile number and password don't match")
return JsonResponse(data)