form validation in ajax before submitting form through ajax - php

Im using ajax to submit a form and inserting the values to the database..I tried many ways but validation error check doesnt come out right.
here is my code
$(document).ready(function() {
$('body').on('click', '#Submit', function(e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'formrelay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
document.getElementById('Message').innerHTML = data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
I tried using submithandler (saw in one of the tutorial) but it did not work..pls help..code below
$(document).ready(function(){
$("#relay_form").validate({
rules: {
f_name: { required : true }
},
submitHandler : function (form) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url:'form_relay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
document.getElementById('Message').innerHTML=data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});

This worked for me..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<!-- red color for error message -->
<style type="text/css">
#hardship_form .error {
color: red
}
</style>
<script>
$(document).ready(function() {
$("#relay_form").validate({
rules: {
f_name: {
required: true
}
},
messages: {
f_name: "Please Enter first name"
},
submitHandler: function(form) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'form_relay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
document.getElementById('Message').innerHTML = data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});
</script>
Thanks Milan

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

Fullcalendar Event Add/Edit and Resize.and get sucesscallback without page reload/refresh

When i add new event or update event or change event or drag new time or new user then every time page refreshes. but how to solve this issue for without reloading page and display updated event time or remove event. i'm using calendar version 5 for fullcalendar.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
now: '<?php echo $CurrentDate; ?>',
editable: true,
aspectRatio: 1.8,
scrollTime: '00:00',
timeFormat: 'H(:mm)',
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'resourceTimelineDay,timeGridWeek,dayGridMonth'
},
resources: <?php eventGroups(); ?>,
events: function(info, successCallback, failureCallback) {
successCallback(<?php eventGroupsDetails($fromDate,$toDate); ?>)
},
dateClick: function(info) {
$('#addScheduleEntry').modal('show');
$(document).on('click', '.modal_default_ok', function() {
$.ajax({
url: "calendar_event_create.php",
type: "POST",
data: $("#frmEvent").serialize(),
dataType: 'json',
success: function(response){
if(response.result == 'success'){
// how to get updated event and display in calender without page refresh
}
}
});
});
},
eventClick: function(info, jsEvent, view) {
$.ajax({
url: "calendar_event_update.php",
type: "POST",
data: $("#frmEventUpdate").serialize(),
dataType: 'json',
success: function(response){
// how to get updated event and display in calender without page refresh
}
});
},
editable: true,
eventDrop: function(info, delta, revertFunc, ui) {
$.ajax({
url: "save_drop_event_detail.php",
type: "POST",
data: {EventId:EventId},
dataType: 'json',
success: function(response){
// how to get updated event and display in calender without page refresh
}
});
},
eventResize: function(info) {
$.ajax({
url: "save_resize_event_detail.php",
type: "POST",
data: {EventId:EventId},
dataType: 'json',
success: function(response){
// how to get updated event and display in calender without page refresh
}
});
}
});
calendar.render();
});
</script>
<div class="row">
<div id="msg"></div>
<div class="col-md-12">
<div id='calendar'></div>
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
now: '<?php echo $CurrentDate; ?>',
editable: true,
aspectRatio: 1.8,
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'resourceTimelineDay,timeGridWeek,dayGridMonth'
},
views: {
timeGridWeek: {
type: 'timeGrid',
duration: { weeks: <?php if($searchWeek=="") { echo 1; } else{echo $searchWeek;} ?> }
}
},
resources: <?php eventGroups(); ?>,
events: function(fetchInfo, successCallback, failureCallback) {
var fromDate = "<?php echo $fromDate; ?>";
var toDate = "<?php echo $toDate; ?>";
$.ajax({
url: "ajaxRefresh.php",
type: "POST",
dataType: "json",
success: function(response){
var events = [];
$.each(response, function (i, item) {
events.push({
id: response[i].id,
start: response[i].start,
end: response[i].end,
title: response[i].title,
});
});
successCallback(events);
}
});
},
dateClick: function(info) {
$('#addScheduleEntry').modal('show');
$.ajax({
url: "calendar_event_create.php",
type: "POST",
data: $("#frmEvent").serialize(),
dataType: 'json',
async : false,
success: function(response){
if(response.result == 'success'){
calendar.refetchEvents();
}
}
});
},
eventClick: function(info, jsEvent, view) {
var text = JSON.stringify(info, function (key, value) {
var eventId = info.event._def.publicId;
$("#eventDetail").modal("show");
$(document).on('click', '.removeEvent', function() {
var eventId = $("#event_id").val();
var yes = confirm("Are you sure ?");
if(yes == true){
$("#process_loader").fadeIn();
$.ajax({
url: "calendar_event_remove.php",
type: "POST",
data: {eventId:eventId},
dataType: 'json',
async : false,
success: function(response){
if(response.msg == "true"){
calendar.refetchEvents();
}
}
});
}
});
},
editable: true,
eventDrop: function(info, delta, revertFunc, ui) {
$.ajax({
url: "save_drop_event_detail.php",
type: "POST",
data: {EventId:EventId,oldUserId:oldUserId,newUserId:newUserId,newEventStartTime:newEventStartTime,newEventEndTime:newEventEndTime},
dataType: 'json',
async : false,
success: function(response){
if(response.msg == 'success'){
calendar.refetchEvents();
}
}
});
},
eventConstraint: {
slotMinTime: '10:00' ,
slotMaxTime: '11:00'
}
});
calendar.render();
});
</script>
We used this function "calendar.refetchEvents();" and used an AJAX data source for your events, instead of a static one.

before submit and uploadProgress doesnt work in ajax jquery

can any one help me in this problem and i try many ways but beforeSubmit and uploadProgrss doesnt work
$.ajax({
url:"include/ajaxPages/admin/insertNewItem.php",
type:"POST",
data:new FormData(this),
processData:false,
contentType:false,
beforeSubmit:function(){
$(this).find(".progress").width("0%");
},
uploadProgress:function(event,position,total,complete){
$(this).find(".progress").animate({
width: complete+"%"
},{
duration:1000
})
},
success:function(data){
console.log(data);
alert("تم الاضافه بنجاح");
$(".loadingViedo").fadeOut();
window.location = document.URL;
}
})
Try this:
var fd = new FormData();
fd.append('rName', $('#upload-resource .upload').attr('data-name'));
fd.append('rfile', $('#upload-resource .upload').attr('data-file'));
$.ajax({
url: 'include/ajaxPages/admin/insertNewItem.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
xhr: function () { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // if upload property exists
myXhr.upload.addEventListener('progress', function (e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
var percent = Math.round(done / total * 100);
//console.log('xhr progress: ' + percent + '%');
$(this).find(".progress").animate({
width: percent +"%"
},{
duration:1000
});
}, false);
myXhr.addEventListener('load', function (e) {
//upload done
});
$('#upload-resource .cancel').show().click(function () {
//cancel upload
myXhr.abort();
});
}
return myXhr;
},
success: function (data) {
//to do for success result
}
});

How to retrieve textbox value in a controller which is supplied with ajax?

I want to pass value of text box to my controller, i can pass that but i cant retrieve it at controller. Help me to identify my mistake.
Form.php (dept_name is a id of my textbox)
<script>
$(document).ready(function() {
$("#submitbutton").click(function(e) {
var deptname=$('#dept_name').val();
$.ajax({
url: 'http://localhost/finalProjectWork/admin_department_controller/adddept/',
type: 'POST',
method: 'POST',
headers: {'Cache-Control': 'no-cache'},
data: {name:deptname},
contentType: false,
processData: false,
success: function(test) {
alert(test);
},
error: function() {
alert("Already Exists");
}
});
e.preventDefault();
});
});</script>
controller :
public function adddept()
{
$deptname=$this->input->post('name');
$this->load->model('admin_department_model');
$this->admin_department_model->insertdept($deptname);
echo "Successfully inserted";
}
Try this
<script>
$(document).ready(function() {
$("#submitbutton").click(function(e) {
var deptname=$('#dept_name').val();
$.ajax({
url: 'http://localhost/finalProjectWork/admin_department_controller/adddept/',
type: 'POST',
method: 'POST',
headers: {'Cache-Control': 'no-cache'},
data: {name:deptname},
success: function(test) {
alert(test);
},
error: function() {
alert("Already Exists");
}
});
e.preventDefault();
});
});</script>

Upload file via ajax jquery php api

I am having the code with the below format.
PHP file :
<form action="http://clientwebapi.com/createEvent" id="form_createEvent" method="post" enctype="multipart/form-data">
<input type="text" name="image_title" />
<input type="file" name="media" accept="image/*,video/*"/>
</form>
JQUERY file:
$('#form_createEvent').submit(function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
xhrFields: {
withCredentials: true
},
data: form.serialize()
}).done(function () {
showCurrentLocation();
alert('Event created successfully..');
location.reload();
}).fail(function () {
alert("fail!");
});
event.preventDefault();
});
The above Jquery code is submitting. Also While I am submitting the below format, It will redirect to the "http://clientwebapi.com/createEvent" and Event created successfully.
Form Submit and redirect to client page:
$('#form_createEvent').submit(function () {
var fd = new FormData();
fd.append('media', input.files[0]);
$.ajax({
url: form.attr("action"),
data: fd,
processData: false,
contentType: false,
type: form.attr("method"),
success: function (data) {
alert(data);
}
});
event.preventDefault();
});
Here How can I prevent while submit the form and create the event with the given image. Kindly help
You forgot to add event as argument to the submit function:
$('#form_createEvent').submit(function (event) {
I found the Answer for this. I made some mistake here. I resolved by using the below code..
$('#form_createEvent').submit(function() {
var form = new FormData($(this)[0]);
$.ajax({
url: 'http://clientwebapi.com/createEvent/',
type: 'POST',
xhrFields: {
withCredentials: true
},
async: false,
cache: false,
contentType: false,
processData: false,
data: form,
beforeSend: function () {
$("#output_process").html("Uploading, please wait....");
},
success: function () {
$("#output_process").html("Upload success.");
},
complete: function () {
$("#output_process").html("upload complete.");
},
error: function () {
//alert("ERROR in upload");
location.reload();
}
}).done(function() {
alert('Event created successfully..');
}).fail(function() {
alert("fail!");
});
event.preventDefault();
});
you can stop the form submission by return false;
$('#form_createEvent').submit(function () {
// some code
$.ajax({
// some code/objects
});
return false; // here, it will stop the form to be post to the url/action
});

Categories