I'm working on a child theme, In my-page-template.php I have :
$id_curr= 5; //calculated value through code
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id_curr));
In my_js.js I have an AJAX call :
$.ajax({
//...
type: 'post',
data: {
action: 'ajax_load',
post_id: ajaxload.post_id
}
})
Now in functions.php, I want to edit/update ajaxload.post_id according to a new result. Is there a way to do that? If I try re-calling wp_localize_script() with the same $name as shown below, will this work?
$id_new= 8; //new calculated value
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id_new));
After deep research, I venture to answer my question.
Wordpress have the function wp_send_json() that allows to send a response back to an AJAX request. This function can update ajaxload.post_id.
In functions.php :
$return = array('post_id' => $id_new);
wp_send_json($return);
In my_js.js :
$.ajax({
type: 'post',
data: {
action: 'ajax_load',
post_id: ajaxload.post_id
},
success:function(data) {
var result = $.parseJSON(data);
ajaxload.post_id = result.post_id;
}
});
create an array with IDs.
$ids = array( 5, 8 );
foreach ( $ids as $id ) {
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id));
}
Related
i just learn about Ajax. I am so confused and getting error after following some tutorials. The plan is after we get the id_program, we can change or reload the page to show the data inside the dropdown menu after we clicks it. May someone help me please?
1.1 Database ( Program )
1.2 Inside Payment
1.3 Inside actor
DatabaseController.php
public function data($id)
{
$client = new Client();
$response = $client->request('GET', 'http://localhost:8585/api/v1/tables', [
'query' => [
'limit' => '100'
]
]);
$data = json_decode($response->getBody()->getContents(), true)['data'];
$pay = Payment::get()->all();
$pro = Program::select('nama')->where('name', $id)->get();
$coba = Program::get()->all();
foreach ($pro as $p) {
$name = $p->name;
}
return view('database.index', compact('nama','data','pay','coba','pro','id'));
}
Route
Route::get('program/database/{database}', [DatabaseController::class,'data'])->name('database.data');
database.index
<select id="id" class="form-control" filter>
<option>Pilih Layanan...</option>
#foreach ($coba as $id)
<option value="{{$id->id_program}}">{{ $id->nama}}</option>
#endforeach
</select>
Ajax Script
$(function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')}
});
$(function(){
$('#id').on('change',function(){
number =$('#id').val();
console.log(number)
$.ajax({
type : 'POST',
url : "{{route('database.data',lcfirst($name))}}",
cache : false,
data:function(d){
d.number = number;
return d;
},
success: function(msg){
console.log('success')
},
})
})
})
});
Result (Error)
a. ( id_program = 1 ) Correct data output & Method Not Allowed error
b. ( id_program = 2 ) Incorrect data output & Method Not Allowed error
Thank you for the helps
Route::get('program/database/{database}', [DatabaseController::class,'data'])->name('database.data');
see the "get" key word? You are declare this route as a GET route, but your AJAX method:
$.ajax({
type : 'POST',
url : "{{route('database.data',lcfirst($name))}}",
....
is a POST request.
The solution is:
if your request only GET some data (no create, no delete, no update,... any data), then $.ajax({ type : 'GET', ....
if your request do modify data, then Route::post('program....
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
I've created a Custom Post Type in Wordpress called Location/Tour and another one called Itinerary. In my CPT Itinerary, I have some ACF custom fields one of them is a repeater field that has subfields (Relationship field for the CPT Location/Tour, Title field, Description field).
I've created a button that should trigger an AJAX script which job is to get the values from the CPT Location/Tour(Title and Description) and
put them in my input subfields(Title and Description) in my CPT Itinerary.
I've created a PHP function that gets the values from the CPT Location/Tour and now I'm trying to run the PHP function using AJAX.
I was able to get the AJAX working and I get the values in my console log under ResponseText.
Now the part I'm struggling with. I need to set each value as a separate variable in JS so that I can replace the input field values with the new ones but unfortunately I don't know how.
I've tried almost everything and I think that I'm close to the answer but I'm missing something. :(
Here is my post-value-loader.php
<?php
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader($field) {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) : while ( $location->have_posts() ) : $location->the_post();
$title = the_field('title'); //The Title field value that we need
$description = the_field('description'); //The Description field value that we need
wp_reset_postdata();
?>
<?php endwhile; endif; ?>
<?php add_action('acf/prepare_field/name=default_tour', 'post_loader'); ?>
<?php }
// BUTTON TO RUN AJAX
function my_acf_prepare_field($field) {
echo '<div class="acf-field"><button type="submit" id="data_fetch" class="button acf-load-default-tour-values">Load default value</button></div>';
return $field;
}
add_action('acf/prepare_field/name=default_tour', 'my_acf_prepare_field');
// ADD SCRIPT TO WORDPRESS ADMIN AJAX
function js_data_fetch() {
wp_enqueue_script ("ajax-data-fetch", get_stylesheet_directory_uri() . "/inc/assets/js/data-fetch.js", array('jquery'));
//the_ajax_script will use to print admin-ajaxurl in data-fetch.js
wp_localize_script('ajax-data-fetch', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
}
add_action("admin_enqueue_scripts", "js_data_fetch");
?>
And here is my data-fetch.js (Note: I'm not a JS guy :( )
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
},
error: function(error){
console.log(error)
},
});
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(description); //This is replacing the description field - but the variables are missing
});
Also here are two images from the CPT Itinerary editor (https://imgur.com/kFImdpe) with the fields and my console log (https://imgur.com/wwxKXQP). Hope that this helps.
You have to return the data as JSON from post_loader function. I've cleaned up a little, but still, it's a mess.
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader() {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) :
while ( $location->have_posts() ) :
$location->the_post();
$title = the_field('title');
$description = the_field('description');
// You have to return data as json
wp_send_json([
'title' => $title,
'description' => $description
]);
//wp_reset_postdata();
endwhile;
endif;
// Why do you need this inside this function?
// add_action('acf/prepare_field/name=default_tour', 'post_loader');
}
JS
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(data.title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(data.description); //This is replacing the description field - but the variables are missing
},
error: function(error){
console.log(error)
},
});
});
I know it's a commun question and I red nearly all the subject about it, but i can't find an answer who fit my case.
I wrote a plugin to add country and languages related (USA->English|Sapnish for example) I am using Class and constructor for the plugin's functions. It is fully working expect the following function :
I get a select in front with all the country, and on change of this select action another function with ajax, the data passed are ok but the response is always returning 0, connected as admin or not.
Here is my ajax :
$('#sel-country-back').change(function(){
var post_id = $(this).val();
change_status(post_id);
})
function change_status(id) {
$.ajax({
url: window.location.origin + '/wp-admin/admin-ajax.php',
data: {
action: 'wmu-display-lang-select',
post_id: id,
},
type: 'post',
success:function(data){
$('#lang-back').html(data);
},
error: function(errorThrown){
$('#lang-back').html('<select name="langBack" id="sel-lang-back"><option value="default" class="no-lang-option">Aucune langue associée</option></select>');
}
});
}
and my function
public function wmu_display_lang_select()
{
if ($_POST['post_id']) {
$id = sanitize_text_field($_POST['post_id']);
$lang = self::getLang($id);
if ($lang !== false) {
$response = array(
'status' => 200,
'content' => $lang
);
}
else {
$response = array(
'status' => 201,
'message' => __('Le fichier demandé n\'existe pas', 'cadwork')
);
}
die(json_encode($response));
}
}
with the action added to the constructor
public function __construct()
{
add_action('admin_menu', array($this, 'wmu_add_menu'));
add_action('wp_ajax_wmu_display_lang_select', 'wmu_display_lang_select');
add_action('wp_ajax_nopriv_wmu_display_lang_select', 'wmu_display_lang_select');
}
I tried to place the add_action outside the class after the class instantiation
$wmu = new WB_MultiLang_URL();
add_action('wp_ajax_wmu_display_lang_select', 'wmu_display_lang_select');
add_action('wp_ajax_nopriv_wmu_display_lang_select', 'wmu_display_lang_select');
but it doesn't seem to work,
Do you have any ideas why ? I think it's a dumb error or mistake somewhere but I can't find it...
Change action: 'wmu-display-lang-select', in your JS request to action: 'wmu_display_lang_select', and it should work.
This is what I have right now which works, but I need quotes around the numbers of the id and total subscript of the array. I need it to look like this:
{"id":"528", "total":"5280"}
Here's my PHP code that generates the json array:
else if(strcmp($_GET['action'], 'update') == 0)
{
$cart = $_SESSION['cart'];
$array = array(
'id' => $cart->count(),
'total' => $cart->total()
);
echo json_encode($array);
}
What it currently echos out:
{"id":528, "total":5280}
I've tried adding quotes around $cart->count() and $cart->total() manually by doing '$cart->count()' and '$cart->total()' but it literally returns the string the quotes are around. The reason I need quotes around the id and total because when I try to display them in javascript, it says undefined.
EDIT:
here's my javascript code:
$.ajax({
type: 'GET',
url: 'includes/actionhandler.php',
data: { action: 'update'},
success: function (data) {
var json = jQuery.parseJSON(data);
var obj = jQuery.toJSON(json)
alert(obj['total']);
},
});
$array = array(
'id' => strval($cart->count()),
'total' => strval($cart->total())
);
It is a workaround but will work :P
Are you outputting it using ajax? If yes, set the return dataType attribute to json using -
$.ajax({
type: "POST",
data: {},
dataType:"json",
url: '',
});
$array = array(
'id' => '"'.strval($cart->count()).'"',
'total' => '"'.strval($cart->total()).'"'
);