Send ajax collected data to the current users database Wordpress - ajax

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

Related

wordpress ajax won't send response as array, why?

i have worked for wordpress project which need to call back some result from database via ajax .
the problem is the response will be in string form which is not as i aspect .
here is whats my try :
//The PHP
function edit_something() {
if ( isset($_REQUEST) ) {
global $wpdb;
$ID = intval( $_REQUEST['ID'] );
$query= "SELECT * FROM `TABLE` WHERE `ID` = '$ID';";
$result= $wpdb->get_results( $queryHavadesEnsani, 'ARRAY_A' );
print_r( $resultsHavadesEnsani );
}
}
die();
}
add_action( 'wp_ajax_edit_something', 'edit_something' );
and the endpoint
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myplugin_ajaxurl');
at the end the jquery
function sendAjax( ID ) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
'action' : 'edit_something',
'ID' : ID
},
success:function(data) {
console.log(data)
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
i realy need your guidance
more info :
i also tried json_encode for php and JSON.parse for js but error the response will be Object object .
I guess instead of "echo" you should use wp_send_json_success
https://developer.wordpress.org/reference/functions/wp_send_json_success/
How to call ajax in Wordpress

how to create relational select option ajax in laravel 8

I try to create a relational select option in laravel 8 using ajax but didn't work I get this error in the console: 405 Method Not Allowed
POST http://127.0.0.1:8000/decomptes/%7B%7B%20route(%20'getOperationsChantier'%20)%20%7D%7D 405 (Method Not Allowed)
the route
Route::post('/getOperationsChantier', [DecompteController::class, 'getOperationsChantier'])->name('getOperationsChantier');
the jquery code
$(document).ready(function(){
// When an option is changed, search the above for matching choices
$('#chantiers').change(function(){
$("#mySelect option").remove();
// $("#city option").remove();
var id = $(this).val();
$.ajax({
url : "{{ route( 'getOperationsChantier' ) }}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
type: 'post',
dataType: 'json',
success: function( result )
{
$.each( result, function(k, v) {
$('#mySelect').append($('<option>', {value:k, text:v}));
});
},
error: function()
{
//handle errors
alert('error...');
}
});
}).change();
});
the function in the controller :
function getOperationsChantier( Request $request )
{
$this->validate( $request, [ 'id' => 'required|exists:chantiers,id' ] );
$chantierOperations = ChantierOperation::where('chantier_id', $request->get('id') )->get();
$output = [];
foreach( $chantierOperations as $chantierOperation )
{
$output[$chantierOperation->id] = $chantierOperation->operation_id;
}
return $output;
}
can someone help me this is the first time when I use ajax

Why Ajax response in Wordpress doesn't work?

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!!

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

i got error (Error get data from ajax)

hi i am unable to call my ajax function in codeigniter , below is my script :
whenever i click edit button from my data table i got error (Error get data from ajax) , could u pls help me where i am doing wrong.
<script type="text/javascript">
var save_method;
function edit_question(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
// document.write("test");
//Ajax Load data from ajax
$.ajax({
// document.write("test");
url : "<?php echo base_url('index.php/test_cont/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="question_id"]').val(data.question_id);
// $('[name="cid"]').val("<?php //echo $a; ?>");
$('[name="cid"]').val(data.cid);
$('[name="ques"]').val(data.question);
// $('[name="opa"]').val(data.options);
// $('[name="opb"]').val(data.options);
// $('[name="opc"]').val(data.options);
// $('[name="opd"]').val(data.options);
$('[name="ra"]').val(data.answer);
$('[name="marks"]').val(data.marks);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Questions'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
i have a controller name test_cont , here's code :
public function ajax_edit($id)
{
$data = $this->m->get_by_id($id);
echo json_encode($data);
}
public function question_update()
{
$data = array(
'course_id'=>$this->input->post('cid'),
'question'=>$this->input->post('ques'),
'marks'=>$this->input->post('marks'),
'options' => $options,
'answer' => $this->input->post('ra'),
);
$this->m->question_update(array('question_id' => $this->input->post('question_id')), $data);
echo json_encode(array("status" => TRUE));
}

Resources