jQuery Ajax POST save delete submit - javascript

Here is my code
<form method="post" role="form" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="submit" id="save" name="save" value="Simpan Data Client" class="btn" style="font-size:0.7em; letter-spacing:1px; color:#666666" /> //For save
<input type="submit" id="delete" name="delete" value="Delete Client" class="btn-delete" style="font-size:0.7em; letter-spacing:1px; color:#666666; padding:8px 15px" /> //For Delete
</form>
<script type="text/javascript">
$("#form").on("submit",function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax(
{
url:'Master/Database/Client/RunClient.php',
type: 'POST',
data: formData,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
beforeSend:function()
{
document.getElementById("loading").style.display = "";
},
complete:function()
{
//document.getElementById("loading").style.display = "none";
},
success:function(result)
{
document.getElementById("info").innerHTML = result;
var n = result.search("error");
if(n < 0) /*document.getElementById("form").reset();*/ $(".input").val('');
}
});
});
</script>
I can get all data from inside my form except from Input type submit i make.
I can't use isset($_POST["save"]) and isset($_POST["delete"]) at my RunClient.php

Create separate function for a submit and pass "submit type" depending on what button is clicked;
$('#save').click(function() {
submitForm('save');
});
$('#delete').click(function() {
submitForm('delete');
});
function submitForm(submittype) {
var formData = new FormData();
//push your form data to formData and add the submittype
formData['type'] = submittype
}
in your php file
$submittype = $_POST['type']; // 'save' or 'delete'
if($submittype == 'save') {
//do save action
}
if($submittype == 'delete') {
//do delete action
}

I use to avoid submit inputs and change by buttons.
<button type="button" id="save">SUBMIT</button> //For save
<script type="text/javascript">
$("#save").on("click",function (e)
{
});
</script>
So, if anyone deativates javscript form will not submit.
And you can send the data like this:
data: {
foo: 'var'
foo2: 5
},
EDIT. Sorry missunderstood your question.
Just control with javascript what button is clicked and assign a value with a hidden field.

'$("#form").on("submit",function (e)' replace the function with
$("#save").click(function() {
});
$("#delete").click(function() {
});

Related

Form is Submitting Although Error Handled on Blank Fields

I am trying to submit a form with a little error handling. when the fields are empty there will be a warning and it shouldn't be saved on DB. if the fields are filled there should be a success alert. My case is still the empty value is being saved.
HTML
<input type="submit" id="add" onclick="emptyHandling();" name="_add" class="btn btn-primary btn-size" value="Add"/>
//FORM SUBMIT
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>'); // REPONSE MESSAGE
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling(){
var inv = $("#inv").val();
if(inv == ''){
var message = "Field Left Empty";
alertMessage(message);
}else{
successMessage();
}
return false; // THIS IS BEING RETURNED FALSE
}
//WARNING ALERT
function alertMessage(titleMessage){
swal({
title: titleMessage,
text: "Mandatory Fields are Required to be Filled",
type: "warning",
confirmButtonClass: "btn btn-danger"
});
}
The return is made false on error handling which should stop the next processes. I am not really sure of where the mistake is made.
You can remove onclick from your submit button and move that function call inside your form submit handler . Then , inside this check if the validation function return true/false depending on this execute your ajax call.
Demo Code :
$(document).ready(function() {
$("#form").on('submit', function(e) {
e.preventDefault();
//call function..
if (emptyHandling()) {
//your ajax...
console.log("inside ajax....")
}
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling() {
var flag = true
var inv = $("#inv").val();
if (inv == '') {
var message = "Field Left Empty";
alertMessage(message);
flag = false
} else {
successMessage();
}
return flag; // return flag//
}
//WARNING ALERT
function alertMessage(titleMessage) {
//swal...
console.log(titleMessage)
}
function successMessage() {
console.log("All good...")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="form">
<input type="text" id="inv">
<input type="submit" id="add" name="_add" class="btn btn-primary btn-size" value="Add" />
</form>

form validation through javascript - error alert coming but saving the data

here I am comparing the location name whether its already entered or not, In my code I am getting alert when I click submit button but also data submitted. onchange function not working as I expected, can anyone help me how stop the data not submitting when I get alert?
When submitting time validation should be done, why because in our test server we are getting some delay after click button, so only data submitting after alert also. do you have any idea on this? Thanks in advance
<form class="form-inline" id="desgForm" accept-charset="UTF-8" method="post" action="../locationSubmit.htm" enctype="multipart/form-data">
<input type="text" id="locationName" autocomplete="off" name="locationName" class="form-control validate[required]" onchange="desgCheck();" onkeyup="firstToUpperCase1();" value="">
<button type="submit" class="btn btn-primary" >Save</button>
</form>
Javascript:
<script>
function desgCheck()
{
var locationName = document.getElementById('locationName').value;
$.ajax({
type: "POST",
url: "../designation/locationName.htm",
data: {
locationName: locationName
},
dataType: "text",
success: function (data)
{
if ($.trim(data) !== 'Data available')
{
alert("This Location already exist!!");
document.getElementById("locationName").value = "";
return false;
}
},
error: function (error) {
document.getElementById("locationName").value = "";
}
});
}
function firstToUpperCase1() {
var str = document.getElementById("locationName").value;
var a = str.toUpperCase();
$("#locationName").val(a);
}
jQuery("#desgForm").validationEngine();
</script>

How to save textarea data when click outside the textarea using ajax

I am using froala editor and i want text in text area of editor saved when user clicks outside that textarea using Ajax i am new in ajax id of content editor is #id_content
This is my form part in django
<form method="POST" id="froala_form" class="PageForm _inputHolder">
{% csrf_token %}
<div class="_alignRight posR _saveBTNOut">
<button type="submit" class="_btn btnPrimery">Save as Draft</button>
</div>
</form>
This is what i have tried but not getting any proper logic
function loadDoc(){
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function{
if(this.readyState==4 && this.status==200){
var x = document.getElementById("id_content");
x.addEventListener("click", ajaxsavefunc);
}
};
xhttp.open("GET",'url', true);
xhttp.send();
}
function ajaxsavefunc(xhttp) {
document.getElementById("froala_form").innerHTML = editor.html.get()
}
This is a example of how to use blur(when user click outside of field) in Jquery.
Basically this example will return a alert with the value of input when user click in the field and click out of the field.
<form method="post" action="" >
<input type="text" id="test" value="123">
<input type="submit">
</form>
$(function () {
$('#test').blur(function (e) {
e.preventDefault();
var x = document.getElementById("test").value;
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: {input: x},
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
});
});

The page got through Ajax cannot use the input type = "file" label?

I get form page through Ajax.
The following is a form of code:
enter code here
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group" style="margin-left:0px;">
<label for="file">注:选择头像文件尽量小于2M</label>
<input id="headPortraitFile" type="file" name="portrait">
</div>
<button id="headPortraitSubmit" type="button" class="btn-sm btn-primary">上传头像</button>
</form>
But the form of the input type = "file" in the browser cannot selected file directly, not to mention the submitted documents. I do not know what reason be? This two days have not been solved, for a great god!!!!!!
here is the Ajax code:
1.I get the form page by this:
$(Document).on("click", '#headPortrait', function() {
$.get("/headPortrait", function(data) {
$(".bodyPart").children().remove();
$(".bodyPart").html(data);
})
})
2.and then I post the form by this:
$(Document).on("click", '#headPortraitSubmit', function() {
var formData = new FormData();
formData.append("portrait", $('#headPortraitFile').get(0).files[0])
$.ajax({
url : "/headPortraitSubmit",
type : 'POST',
data : formData,
processData : false,
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
if (data = "success") {
$(".bodyPart").children().remove();
$(".bodyPart").load('/coding');
}
},
});
})
for attribute value should match id of <input type="file"> if expected result is for change event to be called for <input type="file"> element when <label> element is clicked. Substitute "submit" for "button" at type attribute of <button>.
Document is a function, not html document. Substitute document for Document at parameter passed to jQuery() : $().
if condition within success should use == or === to compare value of data to "success", instead of assigning "success" to data identifier.
$(document).on(/* event, selector, eventHandler */)
$(document).on("click", '#headPortraitSubmit', function() {
var formData = new FormData();
formData.append("portrait", $('#headPortraitFile').get(0).files[0]);
console.log(formData.get("portrait"));
/*
$.ajax({
url : "/headPortraitSubmit",
type : 'POST',
data : formData,
processData : false,
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
if (data === "success") {
$(".bodyPart").children().remove();
$(".bodyPart").load('/coding');
}
},
});
*/
});
document.querySelector("form")
.onsubmit = function(event) {
event.preventDefault();
}
document.querySelector("input[id=headPortraitFile]")
.onchange = function(event) {
console.log(this.files[0])
}
input[type=file] {
display: none;
}
[for=headPortraitFile]:before {
content: 'Label for #headPortraitFile ';
}
#headPortraitSubmit:before {
content: 'Sumbit form .form-horizontal ';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group" style="margin-left:0px;">
<label for="headPortraitFile">注:选择头像文件尽量小于2M</label>
<input id="headPortraitFile" type="file" name="portrait">
</div>
<button id="headPortraitSubmit" type="submit" class="btn-sm btn-primary">上传头像</button>
</form>

how to get ajax response to trigger click

I have two forms for buy now and for pincode when I click buynow button sending request through ajax and same thing is done for pincode form also.
HTML
<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>
<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
In the same buynow click event I need to trigger a pincode submit button, so I did this
(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....
});
the above trigger event is successfully calling pincode click event
$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});
but I need to get ajax response back to trigger event so that I can do some operation is it possible?
something like
(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....
});
You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.
Note, included event.preventDefault() to prevent submission of <form>, as pointed out by #IsmailRBOUH
var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
e.preventDefault();
....
....
$("#pinCheckTest").trigger('click');
if (dfd) {
dfd.then(function(output) {
// do stuff with output
console.log(output)
})
}
....
});
$('#pinCheckTest').click(function (e) {
e.preventDefault();
dfd = $.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {}
else{};
}
})
});
var dfd;
$("#first").click(function() {
$("#second").trigger("click");
if (dfd) {
dfd.then(function(data) {
alert(data)
})
}
})
$("#second").click(function() {
// do ajax stuff
dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>
Since you are binding the click event to a button inside form you have the prevent the default behaviour which is 'submit the form'. Change you code to :
$('#pinCheckTest').click(function (e) {
e.preventDefault();
//Your ajax call
});
Here is a demo to clarify the difference https://jsfiddle.net/qvjjo3jk/.
Update1:
Add an id to your form:
<form action="#" id="pinCheckForm">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
Then:
$('#pinCheckForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: url,
data: $(this).serialize(), //Sends all form data
success: function(output) {
if (output == 'true') {} else {}
}
});
});

Categories