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
});
Related
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' ); ?>
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
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>
problem when upload image MVC with ajax, i have controls_class.php content function upload_img_admin in class settings calling from page c_ajax_img.php
page c_ajax_img.php
include_once('controls_class.php');
$ajax_up_img = new settings;
$ajax_up_img->upload_img_admin(#$_FILES['file_upload']);
function upload_img_admin in class settings
function upload_img_admin()
{
$dir_name=dirname(__FILE__)."/upload/";
$path=#$_FILES['file_upload']['tmp_name'];
$name=#$_FILES['file_upload']['name'];
$size=#$_FILES['file_upload']['size'];
$type=#$_FILES['file_upload']['type'];
$error=#$_FILES['file_upload']['error'];
...
...
if( isset($_FILES['file_upload']) )
{
move_uploaded_file($path,$dir_name.$name);
...
...
echo "ok";
}
else
{
echo "File not found";
}
}
function ajax get data form and send to function previous for upload image
$(document).ready(function() {
$(".btn_upload_avatar").click(function(e) {
$('.msgerror').hide().fadeIn(1000).html( '<div class="loading"></div>');
e.preventDefault();
$.ajax({
type:"POST",
url: "../controls/c_ajax_img.php",
cache: false,
processData:false,
contentType: false,
data:$("#form_up_img").serialize(),
success: function (data)
{
if(data == 0){
$('.msgerror').addClass('msgerror_in2').html(data);
}else{
$('.msgerror').addClass('msgerror_in2').html(data);
}
}
});
});
});
Something like this might help you mate.. :)
$(document).ready(function () {
$('#UploadForm').on('submit',(function(e) {
$('.msgerror').hide().fadeIn(1000).html('<div class="loading"></div>');
e.preventDefault();
var formData = new FormData(this);
formData.append('file', input.files[0]);
$.ajax({
url: '../controls/c_ajax_img.php',
data: formData,
contentType: false,
type: 'POST',
processData: false,
success: function (data) {
console.log("success");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
});
});
});
FYI
FormData
ProcessData is set to false so that it prevents jQuery from automatically transforming the data into a query string
Here is my form
<form name="uploadImg" id="uploadImg" class="profile-image" enctype="multipart/form-data">
<input type="file" name="profile" id="updProfileImg">
</form>
Here is my jquery event
$("#updProfileImg:file").change(function() {
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
})
})
But the change event is not triggering form submit so I tried trigger('submit') but the page is refreshing instead of submitting in ajax.
You are binding the events incorrectly. As you currently have it, changing the field will trigger the binding of the submit. It need to be like this:
// bind the submit event
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
});
});
// bind the change event to trigger a submit
$("#updProfileImg:file").change(function() {
$("#uploadImg").submit();
});
A simple modification works
$("#updProfileImg:file").change(function() {
//$('#uploadImg').submit(function() {
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
//})
})
you should try this code:
$("#updProfileImg:file").on("change", function(){
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {},
success: function() {}
})
});
because i expect the ".change()" will be fired one time in the first change.