Why Ajax response in Wordpress doesn't work? - ajax

I have odd (for me) problem with ajax in Wordpress. I do not receive proper response from server. I read Wordpress Codex to find out what I doing wrong, but still I have no clue.
I don't know if it is important or not, but when I tried add a type to ajax syntax, I received an error message.
class databaseClass
{
function __construct()
{
if ( isset($_SERVER['HTTPS']) )
$protocol = 'https://';
else
$protocol = 'http://';
wp_enqueue_script( 'ajaxScript', '/wp-content/themes/bulk/js/ajaxScript.js');
wp_localize_script( 'ajaxScript', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php', $protocol ),
'nonce' => wp_create_nonce( '111')
) );
add_action('wp_ajax_save_sort', 'ajaxFunctionInPHP');
add_action( 'wp_ajax_nopriv_save_sort', 'ajaxFunctionInPHP');
}
function ajaxFunctionInPHP(){
/*check_admin_referrer();
$response['custom'] = "ssss";
$response = json_encode($response);
wp_send_json($response) ;*/
ob_clean();
$response['custom'] = "TEST";
echo $response;
die();
}
}
class ajaxClass extends databaseClass
{
function __construct()
{
parent::__construct();
}
public function ajaxPage()
{
echo '<form name="ajaxTest" type="POST">
<input id="ajaxButton" type="button" value="KLIK"/>
</form>
';
}
}
jQuery( document ).ready( function () {
jQuery('#ajaxButton').click(function() {
var dataFromFunction="";
jQuery.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
success: function (response){
console.log("success message");
console.log(response.custom)
},
error: function (response){
console.log("error message");
}
});
});
} );
success message
ajaxScript.js?ver=5.0.4:15 undefined

Your code seems to be correct but I am sharing my personal approach to doing this in hopes that this might be helpful. Make changes to JS as mentioned below:
jQuery( document ).ready( function ($) {
$('#ajaxButton').click(function() {
var dataFromFunction="Test Data";
$.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
}).done( function (response){
console.log("success message");
console.log(response.custom)
}).fail(function (response){
console.log("error message");
}).always(function(){
console.log('Ajax Completed');
});
});
});
Also for your script localization, it is good to define the scheme parameter in admin_url function but not necessary so 'ajax_url' => admin_url( 'admin-ajax.php') should be just fine.
You seem to have created nonce but haven't used it and a good practice would be to use create nonce function in your form section and not in localization.
I do have a suggestion for your ajax response function but this is just an advice. Change your function to return as follows:
function ajaxFunctionInPHP(){
$response['dataFromFunction'] = sanitize_text_field($_POST['dataFromFunction']);
wp_send_json( $response);
}
Good Luck!!

Related

Larave/Ajax PUT 500 internal server error possible reasons

My console shows this error whenever I try to update my form using my ajax code:
PUT http://127.0.0.1:8000/clinical/bbr-category-configuration-update/1 500 (Internal Server Error)
Route:
Route::put('/bbr-category-configuration-update/{category_id}', [BBRCategoryConfigurationController::class,'update']);
Ajax:
$(document).on('click', '.update_category', function (e){
e.preventDefault();
var cat_id = $('#edit_cat_id').val();
var update_data = {
'category_name' : $('#edit_category_name').val(),
'category_description' : $('#edit_category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT",
url: "/clinical/bbr-category-configuration-update/"+cat_id,
data: update_data,
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400) {
$('#category_formCheckUpdate').html("");
$('#category_formCheckUpdate').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheckUpdate').append('<li>'+err_values+'</li>');
});
} else if(response.status == 404) {
$('#category_formCheckUpdate').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
} else {
$('#category_formCheckUpdate').html("");
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#editCategoryModal').modal('hide');
fetchcategory();
}
}
});
});
Controller:
public function update(Request $request, $category_id) {
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails()) {
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
} else {
$category_update = HmsBbrCategory::find($category_id);
if ($category_update) {
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->update();
return response()->json([
'status'=>200,
'message'=>'Category Edited!',
]);
} else {
return response()->json([
'status'=>404,
'message'=>'Category Not Found',
]);
}
}
}
Things to note:
As you can see, my category_id is being read properly in: url: "/clinical/bbr-category-configuration-update/"+cat_id,. Also, I went ahead and did a console.log to show in my console that the whole table is getting retrieved. My main issue is this 500 internal server error. Not sure if it is by the PUT.
I also tried to change the PUT to POST or GET just to see if there is any change or other errors, but it's still the same 500 internal server issue. PS, my form has csrf.
Your problem is surely $category, you are using $category_update, not $category

laravel- request empty in controller using ajax

I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.

added a new record using ajax and codeigniter.i want to redirect to the view page after adding record. so i want to get the last insert id

Ajax function and controller action is given below.anyone can help to get the last insertid to redirect.the redirection is done in ajax success function. can it do in controller action.its not getting
Ajax function
<script type="text/javascript">
$('#rfqsubmit').click(function () {
//var title = $('#title').val();
var form_data = {
title: $('#txtname').val(),
merid: $('#mermerchant').val(),
userid: $('#customer').val(),
description: $('#txtrequirement').val(),
reqid: $('#requirementid').val(),
shipmethod: $('#shipmethod').val(),
shiplocation: $('#shiplocation').val(),
attachment: $('#txtattachments').val(),
bidclose: $('#txtbidclose').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
success: function () {
window.location.href ="<?php echo base_url() ?>moderator/Employee/manageemployee/";
// window.location.href ="<?php //echo base_url() ?>moderator/RFQ/viewrfq/"+ form_data.reqid;
// alert('added Successfully');
}
});
return false;
});
</script>
Controller action
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
);
$add= $this->requirement_model->forminsert($data7);
}
Your question is not clear anyhow if i got what you need try this.
in your controller action return json response:
$this->load->helper(array('form', 'url'));
$this->load->helper('file');
$data7 = array(
'rfq_title' => $this->input->post('title'),
'rfq_detail' => $this->input->post('description'),
'rfq_merchantid' => $this->input->post('merid'),
'rfq_userid' => $this->input->post('userid'),
);
$inserted_id= $this->requirement_model->forminsert($data7);
//your forminsert method in model should return
//$this->db->insert_id();
$response=array('id'=>$inserted_id,'message'=>"inserted successfully");
echo json_encode($response);
die();
}
Your model function return last_inserted_id:
public function forminsert($data7)
{
$this->db->insert('jil_mrorfq',$data7);
//it will return last id
return $this->db->insert_id();
}
Now in ajax success :
$.ajax({
url: "<?php echo base_url() ?>moderator/RFQ/addoffline",
type: 'POST',
data: form_data,
dataType:"Json",
success: function (data) {
//to access that id
var last_inserted_id = data.id;
window.location.href ="<?php echo base_url() ?>moderator/Employee/manageemployee/"+last_inserted_id;
}
});

Wordpress: AJAX not working

I'm setting up a plugin. Now I'm trying to get an AJAX-PHP code working but I don't get the succeed data and all end with an error.
tracker.php is the main plugin file.
This is the function on my tracker.php that prints the title and some HTML code:
require_once dirname(__FILE__) . '/user-listing.php';
function trez_tracker_user_listing(){
?>
<h1>Tracker - User List</h1>
<div class="clicker">Click here</div>
<div id="printer"></div>
<?php
}//trez_tracker_user_listing
So in user-listing.php I added the following code:
function user_listing_enqueuer() {
wp_register_script( "ajax_user_request", WP_PLUGIN_URL.'/tracker/script/ajax_user_request.js', array('jquery') );
wp_localize_script( 'ajax_user_request', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_user_request' );
}
add_action( 'init', 'user_listing_enqueuer' );
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
add_action("wp_ajax_user_fetcher", "user_fetcher");
And finally the javascript code in /script/ajax_user_request.js:
/* ajax_user_request.js */
jQuery(document).ready( function() {
jQuery(".clicker").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "user_fetcher"},
success: function(response) {
if(response.type == "success") {
jQuery("#printer").html(response)
}
else {
alert("AJAX error")
}
}//success
})//jQuery.ajax
})//Clicker function
})//document ready
When clicking on the <div>, I just get the alert message "AJAX error".
How can I fix it?
Thank you!
You are getting the error because you are not returning the JSON data, you are return string through your user_fetcher function.
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
Change the user_fetcher function so that it will return the JSON data to the AJAX call.
function user_fetcher(){
$result = 'Message to display';
echo json_encode(array('type'=>'success', 'message'=>$result));
die(0);
}//user_listing
And in jquery check the response like this:
success: function(response) {
if(response.type == "success") {
// Add message
jQuery("#printer").html(response.message)
}
else {
alert("AJAX error")
}
}//success
For the hook wp_ajax_user_fetcher, make sure you are using this after logged in, if you are not logged in in the admin section then you have to use wp_ajax_nopriv_user_fetcher. Or you can use both:
// Work if user is login
add_action("wp_ajax_user_fetcher", "user_fetcher");
// Work if user is not login
add_action("wp_ajax_nopriv_user_fetcher", "user_fetcher");

Send ajax collected data to the current users database Wordpress

I am using WooCommerce and added an additional field "location_gps" to collect the location (lat,long) added the ajax call to collect the data. Now I'm stuck getting the data into the current users (user_meta).
Added this in funtions.php
// AJAX - implementation
function add_myscript(){
wp_enqueue_script( 'my-ajax.js', get_bloginfo('template_directory') . "/scripts/my-ajax.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myscript' );
function myAjax(){
global $wpdb;
//get data from our ajax() call
$long = $_POST['long'];
$lat = $_POST['lat'];
$results = "<p>".$lat.", ".$long."</p>"; // this is how it supposed to land in the DB
if($wpdb->insert('location_gps',array(
'long'=>$long,
'lat'=>$lat,
))===FALSE){
echo "Error";
}
else {
echo "Successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
// create custom Ajax call for WordPress
add_action( 'wp_ajax_nopriv_myAjax', 'myAjax' );
add_action( 'wp_ajax_myAjax', 'myAjax' );
Here the JS part..
jQuery(document).ready(function() {
jQuery("#save_loc_button").click(function(){
var long = jQuery("input#long").val();
var lat = jQuery("input#lat").val();
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: { "action": "myAjax", "lat": lat, "long": long },
beforeSend: function(){
jQuery("#test-div").html('processing...');
},
success: function(event, request, settings){
jQuery("#test-div").html('');
jQuery("#test-div").append(event);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});

Resources