Wordpress ajax request not working properly - php

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);

Related

how to clear text boxes after a work have been done?

i wrote a code that will add records to data base then return the message to a specific div
now I need to know how to clear text boxes after I get the result to the div?
$(document).ready(function() {
$('#message').submit(function(e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function(resp) {
$('#error_msg').html(resp);
}
})
})
})
$(document).ready(function() {
$('#message').submit(function(e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function(resp) {
$('#error_msg').html(resp);
$('#FullName').html("");
$('#Email').html("");
$('#PhoneNumber').html("");
$('#Message').html("");
}
})
})
})
$(document).ready(function() {
$('#message').submit(function(e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function(resp) {
$('#error_msg').html(resp);
let frm = document.getElementsById('#message')[0];
frm.reset(); // Reset all form data
}
})
})
})
if it's a regular html form then from.reset();
$(document).ready(function () {
$('#message').submit(function (e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function (resp) {
$('#message')[0].reset();
}
});
});
});

Function doesn't echo variable

I'm currently learning basic php and jQuery.
I've created script which is getting url on mouse hover, and sends it to php.
The problem is, if I want to pass this data to php variable, it seems like it doesn't work because it echos only "'This is our JS Variable :'"
Script:
<script type="text/javascript">
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
console.log(hrefValue)
});
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
});
</script>
functions.php:
function our_tutorial(){
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
echo 'This is our JS Variable :'.$testing;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'lms_enroll',
[
'ID' => $testing
]
);
}
die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');
Solution:
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
type: 'post', // define type
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
functions.php:
// post to et value
$test = $_POST['php_test'];
The problem was - when page loaded, value of a variable was empty. So solution is to call ajax in the moment of mouseover.
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
//console.log(hrefValue)
$.ajax({
url: frontendajax.ajaxurl,
type: 'POST',
data: {
'action': 'image',
'php_test': hrefValue
},
success: function(data){
$('#featured-image').html(data);
//console.log(data);
}
});
});
});

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' ); ?>

POST mywebsite/wp-admin/admin-ajax.php 400 (Bad Request)

I am using ajax for handling filters in my custom post type but getting a Bad request on both POST & GET methods don't know why. Here is my Ajax code,
(function($) {
$(document).ready(function(){
$(document).on('submit', '[data-js-form=filter]', function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
var ajaxscript = { ajax_url : '//localhost/experiencecamping/rv-sales/wp-admin/admin-ajax.php' }
$.ajax({
url: ajaxscript.ajax_url,
type: "POST",
data: data,
success: function(result) {
console.log(result);
},
error: function(result) {
console.warn(result);
},
});
});
});
})(jQuery);
add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');
For this wp_ajax request to work we need to specify action = filter in the data array we send via POST
Also we need filter_ajax() function
Maybe you have it here but you haven't copy it to your question.
Try this version of the code
(function($) {
$(document).ready(function(){
$(document).on('submit', '[data-js-form=filter]', function(e){
e.preventDefault();
var data = $(this).serialize();
console.log(data);
var ajaxscript = { ajax_url : '//localhost/experiencecamping/rv-sales/wp-admin/admin-ajax.php' }
$.ajax({
url: ajaxscript.ajax_url,
type: "POST",
data: {
query: 'test',
action: 'filter'
},
success: function(result) {
console.log(result);
},
error: function(result) {
console.warn(result);
},
});
});
});
})(jQuery);
add_action('wp_ajax_nopriv_filter', 'filter_ajax');
add_action('wp_ajax_filter', 'filter_ajax');
function filter_ajax(){
echo 321;
wp_die();
}

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>

Categories