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' ); ?>
Related
I am new to wordpress, i make a ajax request on click button and it print the data, but ajax is not giving me any response. Please help me to find out the error.
Here is my code
add_action("wp_ajax_delivery_options", "delivery_options");
add_action("wp_ajax_nopriv_delivery_options", "delivery_options");
function delivery_options()
{
echo json_encode(array('type' => 'success'));
wp_die();
}
wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/js/custom.js", array('jquery'));
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
Ajax
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});
})(jQuery);
Any solution appreciated!
you have to pass "callback function name" in data: { action: 'delivery_options', delivery_option: data },
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { action: 'delivery_options', delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});})(jQuery);
I am facing on problem, I have made a CRUD code with AJAX for my CI page, it is working fine on XAMPP server but when I uploaded it to Live Server (Godaddy), it's not fetching data from database and showing 405 Method not Allowed error.
http://www.fenxteksolutions.com/admin/metalinks
Here is my Code.
<script>
$(function(){
showAllEmployee();
//Add New
$('#btnAdd').click(function(){
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Add New Meta Detail');
$('#myForm').attr('action', '<?php echo base_url() ?>admin/addEmployee');
});
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var meta_tag = $('input[name=txtMetaTag]');
var meta_desc = $('input[name=txtMetaDesc]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1';
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2';
}
if(meta_tag.val()==''){
meta_tag.parent().parent().addClass('has-error');
}else{
meta_tag.parent().parent().removeClass('has-error');
result +='3';
}
if(meta_desc.val()==''){
meta_desc.parent().parent().addClass('has-error');
}else{
meta_desc.parent().parent().removeClass('has-error');
result +='4';
}
if(result=='1234'){
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('News '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
//edit
$('#showdata').on('click', '.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Employee');
$('#myForm').attr('action', '<?php echo base_url() ?>admin/updateEmployee');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>admin/editEmployee',
data: {id: id},
async: false,
dataType: 'json',
success: function(data){
$('input[name=txtEmployeeName]').val(data.page);
$('textarea[name=txtAddress]').val(data.title);
$('input[name=txtMetaTag]').val(data.meta_tag);
$('input[name=txtMetaDesc]').val(data.meta_desc);
$('input[name=txtId]').val(data.id);
},
error: function(){
alert('Could not Edit Data');
}
});
});
//delete-
$('#showdata').on('click', '.item-delete', function(){
var id = $(this).attr('data');
$('#deleteModal').modal('show');
//prevent previous handler - unbind()
$('#btnDelete').unbind().click(function(){
$.ajax({
type: 'ajax',
method: 'get',
async: false,
url: '<?php echo base_url() ?>admin/deleteEmployee',
data:{id:id},
dataType: 'json',
success: function(response){
if(response.success){
$('#deleteModal').modal('hide');
$('.alert-success').html('Employee Deleted successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Error deleting');
}
});
});
});
//function
function showAllEmployee(){
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>admin/showAllEmployee',
async: false,
dataType: 'json',
success: function(data){
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr class="odd gradeX">'+
// '<td>'+data[i].id+'</td>'+
'<td>'+data[i].page+'</td>'+
'<td>'+data[i].title+'</td>'+
'<td>'+data[i].meta_tag+'</td>'+
'<td>'+data[i].meta_desc+'</td>'+
'<td>'+
'Edit'+
'</td>'+
'<td>'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function(){
alert('Could not get Data from Database');
}
});
}
});
</script>
This code is working very well in XAMPP Server and giving all data from database and all functions are working very well, but on hosting it is not fetching data and when I inspect the page in console it gave 405 method not allowed error.
Your error is in type parameter in ajax. Remove it or set it to GET. It is actually request method
$.ajax({
type: 'GET',
url: '<?php echo base_url() ?>admin/showAllEmployee',
async: false,
dataType: 'json',
success: function(data){
.......................
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
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
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
});