Validation form with ajax - javascript

This is my submit form code. I want when clicking submit it will be validation form first before it is saved to the database. How can i make script validation form with ajax in function script bellow?
<script>
function simpan_data() {
var url;
save_method == 'add';
url = "<?php echo base_url();?>jurusan/getInsert";
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data) {
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
swal({
title: "Data telah disimpan",
type: "success",
timer: 1000,
showConfirmButton: false,
},
function() {
location.reload();
}
);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
</script>

Related

Display confirmation message before send ajax request

I have written an ajax function where I want to display confirmation meeessage before submitting the form. How should I add with my condition. Below is my code.
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
}
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
})
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
The solution is to use beforeSend ajax property.
beforeSend is a pre-request callback function before it is
sent.Returning false in the beforeSend function will cancel the
request.
beforeSend:function(){
return confirm("Are you sure?");
},
AJAX
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
beforeSend:function(){
return confirm("Are you sure?");
},
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
});
Use ajax beforeSend callback function.
beforeSend: function () {
if(confirm("Are you sure?")){
// do something
} else {
// stop the ajax call
return false;
}
},
See documentation Ajax http://api.jquery.com/jquery.ajax/
Write your ajax into a function like:
function save(){
// something in here
}
After that write a confirmation functionality, if user confirm then call save() function
Maybe this exemple is what you need ?
var r = confirm("Press a button!");
if (r == true) {
// Make your ajax call here
} else {
// He refused the confirmation
}
Call your confirm before ajax call ?
You can try to put your confirmation message in the beforeSend method : http://api.jquery.com/jquery.ajax/
if ( confirm("Do you want to Submit?")) {
// If you pressed OK!";
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
beforeSend:function(){
return confirm("Are you sure?");
},
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
});
} else {
// If you pressed Cancel!";
}
Please check with window.confirm
I ran into this issue recently, so this is my answer, I am using jquery and jqueryconfirm, the "beforesend" callbak only allows the standard "alert" and "confirm" functions.
What I did is placing a "fake" submit button and hide the actual submit one, so it was easy dealing with the response from the custom confirm dialogs, once I got the affirmative answer from the dialog I call the "click" method of the hidden submit button.
...
<button id="confirmSave" type="button">Save</button>
<button id="save" class="is-hidden" type="submit"></button>
<button id="close" aria-label="close" type="reset">Cancel</button>
...

Ajax call not working with onclick

function open_appointment(id)
{
save_method = 'open_appointment';
$('#form_open_appointment')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="pt_id"]').val(data.pt_id);
$('[name="pt_name"]').val(data.pt_name);
$('[name="pt_dob"]').val(data.pt_dob);
$('[name="pt_sex"]').val(data.pt_sex);
$('[name="pt_contact"]').val(data.pt_contact);
$('[name="pt_email"]').val(data.pt_email);
$('[name="pt_address"]').val(data.pt_address);
id=parseInt(id);
var next_id=id+1;
var previous_id=id-1;
//button to call back the function with next id
$('#next_patient').click(function() {
alert("next"+next_id);
open_appointment(next_id);
});
//button to call back the function with previous id
$('#previous_patient').click(function() {
alert("next"+next_id);
open_appointment(previous_id);
});
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed');
}
});
$('#modal_open_appointment').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Open Appointment'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
On click of next button the function is reloaded with the next id (say id 1) But the Problem is On second time click of the next button the function load two time (with current id and with next id say id 1 and 2 ) and for third click it load three time (load id say id 1 id 2 and id 3) . i want it to be only the last id on each click
try
var next_id=1;
var previous_id=1;
function open_appointment(id)
{
save_method = 'open_appointment';
$('#form_open_appointment')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="pt_id"]').val(data.pt_id);
$('[name="pt_name"]').val(data.pt_name);
$('[name="pt_dob"]').val(data.pt_dob);
$('[name="pt_sex"]').val(data.pt_sex);
$('[name="pt_contact"]').val(data.pt_contact);
$('[name="pt_email"]').val(data.pt_email);
$('[name="pt_address"]').val(data.pt_address);
id=parseInt(id);
next_id=id+1;
previous_id=id-1;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed');
}
});
$('#modal_open_appointment').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Open Appointment'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
$(document).on('click','#next_patient',function() {
alert("next="+next_id);
open_appointment(next_id);
});
//button to call back the function with previous id
$(document).on('click','#previous_patient',function() {
alert("previous="+previous_id);
open_appointment(previous_id);
});
I think you should call .unbind() before you bind click event to buttons.
$('#next_patient').unbind().bind('click', function() {
alert("next"+next_id);
...
})
function open_appointment(id)
{
save_method = 'open_appointment';
$('#form_open_appointment')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="pt_id"]').val(data.pt_id);
$('[name="pt_name"]').val(data.pt_name);
$('[name="pt_dob"]').val(data.pt_dob);
$('[name="pt_sex"]').val(data.pt_sex);
$('[name="pt_contact"]').val(data.pt_contact);
$('[name="pt_email"]').val(data.pt_email);
$('[name="pt_address"]').val(data.pt_address);
id=parseInt(id);
var next_id=id+1;
var previous_id=id-1;
// ****************************************
// move out 2 event out function
// set value next_id & prev_id to html tag
$('#next_patient').attr('data-next',next_id);
$('#previous_patient').attr('data-prev',previous_id);
//*****************************************
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed');
}
});
// show bootstrap modal when complete loaded
$('#modal_open_appointment').modal('show');
// Set title to Bootstrap modal title
$('.modal-title').text('Open Appointment');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
//button to call back the function with next id
$('#next_patient').click(function() {
//recevice value & convert to number ***
var next_id = Number($(this).attr('data-next'));
open_appointment(next_id);
});
//button to call back the function with previous id
$('#previous_patient').click(function() {
//recevice value & convert to number ***
var prev_id = Number($(this).attr('data-prev'));
open_appointment(prev_id);
});

.focus() doesn't work on element created by jQuery dynamically

Statement below I had used before to focus on 1st element in a form, and it works very well.
$('form:first *:input[type!=hidden]:first').focus();
But now the problem is when I use it in a form that was empty(without any input element), and I create the elements inside that form by using jQuery .html() after some work, it will not focus on any element.
This is my form:
<form id="edit_marks" method="post">
<div id="display">
</div>
</form>
This is my jQuery AJAX:
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
$('form:first *:input[type!=hidden]:first').focus();
You are triggering the event before you are adding the form, so you need to trigger event after form get added. Add it inside ajax success. Since ajax is asynchronous it may complete at any time, so before completing it will return from the function.
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
Move the focus code inside the AJAX success, because AJAX means it is asynchronous call. So in order to make focus work after AJAX is to add it in the success.
function getData() {
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax({
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {
Semester:Semester,
StudentID:StudentID
},
dataType: 'text',
success: function(data) {
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts) {
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();

JQuery ajaxfileupload with codeigniter

Good morning.
I wanna ask about JQuery ajax fileUpload. I have some issues regarding this.
I want to pass some variable from javascript function
Insert the variables and value from uploading file through jquery ajax
Here are the javascript function :
var baseurl = 'http://fadli.com/';
function upload_item(kode,field,table)
{
$("#upload_item_"+table+"_"+kode).hide(); //hide submit button
$("#loading_image_upload_"+table+"_"+kode).show(); //show loading image
console.log('masuk ke fungsi upload');
$.ajaxFileUpload({
url : baseurl+"admin/level/upload_item/"+kode+"/"+field+"/"+table,
//url :'./admin/level/upload_file/',
secureuri : false,
fileElementId :'userfile_'+table+'_'+field+'_'+kode,
dataType : 'json',
data : {
'title' : $('#sub_modul_title_'+kode).val()
},
success : function (data, status)
{
if(data.status != 'error')
{
// $('#files').html('<p>Reloading files...</p>');
// refresh_files();
// $('#title').val('');
alert('sukses brow');
$("#upload_item_"+table+"_"+kode).show(); //show submit button
$("#loading_image_upload_"+table+"_"+kode).hide(); //hide loading image
}
console.log(data.msg);
},
error:function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
$("#upload_item_"+table+"_"+kode).show(); //show submit button
$("#loading_image_upload_"+table+"_"+kode).hide(); //hide loading image
}
});
return false;
}
And here is the HTML code :
<input type="file" name="userfile" id="userfile_sub_modul_sub_modul_id_<?php echo $sub->sub_modul_id?>" class="styled-finputs">
<button class="btn btn-labeled btn-success btn-xs" type="button" id="upload_item_sub_modul_<?php echo $sub->sub_modul_id; ?>" onclick="upload_item('<?php echo $sub->sub_modul_id?>','sub_modul_id','sub_modul')"><span class="btn-label icon fa fa-picture-o"></span> Upload gambar</button>
<img src="http://fadli.com/assets/img/input-spinner.gif" id="loading_image_upload_sub_modul_<?php echo $sub->sub_modul_id?>" style="display:none" />
The problem is after the first console log, it's not working all way down.
Any help would be appreciate.
Thanks
For ajaxFileUpload, it is starting with capital A, try to change ajaxFileUpload to AjaxFileUpload
You can simply submit the form with ajax(without page reload).
Just use this code.It will submit your files data too.
$(document).on("submit", "form", function(event)//I wrote it for any form.You can change it for specific form
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//make sure your form has action url
type: $(this).attr("method"),//Your form method type GET OR POST
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
Also you can add addition data with FormData. https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
You can modify the above function like this
$(document).on("submit", "form", function(event)
{
var formData = new FormData(this);
formData.append("MORE_INPUT_KEY", "MORE_DATA");
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set any link
type: $(this).attr("method"),//set any metho
dataType: "JSON",
data: formData ,
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});

ajax send form request to the same page to run SQL/PHP queries

<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "menu.php?addnotification=yes",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
$('.overlay').fadeOut();
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
i am trying to run this ajax code to POST data to menu.php page from a submitted form
on menu.php i have
if($_GET["addnotification"] == 'yes') {
//do stuff here
echo 'form submitted';
}
but i cannot see the text form submitted
UPDATE
i have changed to this code:
<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
and put the SQL queries on a different page, but now the please_wait_box shows and does not hide, the queries are not running at all
In your url you've got no blank, but in your php document there is a blank.
menu.php?addnotification=yes
vs
$_GET["add notification"]
You are sending a POST request and then reading the $_GET response, try changing the
type: "POST",
for
type: "GET",
in your ajax call.
and also read addnotification and not add notification (probably a typo)
Check your this part of code:
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
You are searching for success in res whereas i think your res will be a string "form submitted". You can try calling alert(res); or console.log(res) to see what is being returned in your response.
Additional debugging process:
change your code for ajax to below:
var request = $.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString
});
request.done(function( msg ) {
$("#please_wait_box").hide();
$("#message").html(msg);
$('#message').fadeIn('slow');
if(msg.indexOf("success")!=-1)
{
window.location.href = msg.substr(8);
}
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});

Categories

Resources