I am trying to pass a javascript variable from a range slider into a php query.
So when the user slides range slider to '44', the front-page of my wordpress theme shows all posts tagged '44'.
I want to do this without refresh, so decided to try AJAX, which I'm very new to and struggling to see where I'm going wrong.
So my range slider:
<input id="ex2" type="range" min="0" max="360" step="1" />
In my script.js:
var slider = document.getElementById("ex2");
slider.onchange = function() {
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/wordpress/wp-admin/admin-ajax.php",
data: {
action:'get_data',
id: id
},
success:function(data) {
alert("result: " + data);
}
});
};
I am then bouncing this value via my functions.php page.. which maybe I can avoid and go straight to my front-page? Code from my functions.php page:
function get_data() {
echo $_POST['id'];
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And then trying to input into my php query on front-page.php:
<?php
$slider = $_POST['id'];
$query = new WP_Query( array( 'tag' => $slider ) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
I'm very new to PHP and AJAX, not fully understanding the post or echo functions, if someone could help me with my code would be amazing.
Thanks !
It is with the page refresh, but got it working with the POST parameter, don't need any extra code in scripts.js, or functions.php, just on my front-page and for the range slider (in my footer):
My range slider code:
<form action="http://localhost/wordpress/" method="POST">
<input id="ex2" name="ex2" onchange="this.form.submit()"
type="range" min="0" max="360" step="1" />
</form>
On my front-page:
<?php
$slider = $_POST['ex2'];
$query = new WP_Query( array( 'tag' => $slider ) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
And is working !
Try Something like this...
<script src="jquery.js"></script>
<form action="#" method="POST">
<input id="ex2" name="ex2" onchange="this.form.submit()"
type="range" min="0" max="360" step="1" />
</form>
<script>
var slider = document.getElementById("ex2");
slider.onchange = function() {
var id = $(this).val();
var Url = "http://localhost/test2.php?func=myFunc";
$.ajax({
type: "POST",
dataType: "json",
url: Url,
data: {
id: id
},
success:function(data) {
// alert("result: " + data);
console.log(data);
}
});
};
</script>
test2.php
<?php
function myFunc($id)
{
echo $id;
}
if(isset($_GET['func']) && function_exists($_GET['func'])){
if($_GET['func'] == 'myFunc') {
if(isset($_POST['id'])){
$_GET['func']($_POST['id']);
}
}
}
?>
Related
I am creating a simple add to cart function where when the user has successfully added their product to cart they can view their cart and update the quantity using the select option in the cart page, but it seems that i can only update the first product that has been added to cart,if i add a second product i cant update that second product
cart.php
<?php
if(isset($_COOKIE["shopping_cart"]))
{
$total = 0;
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
?>
<?php
foreach($cart_data as $keys => $values)
{
?>
<form id="myForm">
<input type="hidden" name="hidden_id" value="<?php echo $values["item_id"];?>">
<select name="qty" id="qty" class="form-control">
<option style="display:none;" selected><?php echo $values["item_quantity"];?></option>
<?php
for($i=1; $i<=$values["item_qty"]; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
</form>
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#qty").change(function(){
var url = "<?php echo URLROOT; ?>"
var form = $( '#myForm' ).serialize();
$.ajax({
type: "POST",
url: url + '/shops/cookiesave',
data: form,
beforeSend: function() {
//do something here like load a loading spinner etc.
},
})
.done(function() {
window.location.reload(true);
})
});
});
</script>
I have define the URLROOT as define('URLROOT', 'http://localhost/vlake');
cookiesave function
public function cookiesave(){
$cookie_data = stripslashes($_COOKIE['shopping_cart']);
$cart_data = json_decode($cookie_data, true);
foreach($cart_data as $keys => $values)
{
if($cart_data[$keys]["item_id"] == $_POST["hidden_id"])
{
$cart_data[$keys]["item_quantity"] = $_POST["qty"];
}
}
$item_data = json_encode($cart_data);
setcookie('shopping_cart', $item_data, time() + (86400 * 30) ,'/');
}
$("#qty") will only ever identify the first element with that ID. So it just doesn't handle events on any of the others. Having multiple elements with the same ID is invalid in HTML - after all, if an ID does not uniquely identify something, then by definition it's not an ID! So JavaScript / jQuery will simply ignore any duplicates after the first one. You'll have the same problem with $( '#myForm' ) as well.
You need to use a class to identify the <select>, and then traverse the DOM to find the parent form:
<form>
<input type="hidden" name="hidden_id" value="<?php echo $values["item_id"];?>">
<select name="qty" class="qty" class="form-control">
<option style="display:none;" selected><?php echo $values["item_quantity"];?></option>
<?php
for($i=1; $i<=$values["item_qty"]; $i++)
{
?>
<option value="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
</form>
... and ...
$(".qty").change(function(){
var url = "<?php echo URLROOT; ?>"
var form = $(this).closest("form").serialize();
$.ajax({
type: "POST",
url: url + '/shops/cookiesave',
data: form,
beforeSend: function() {
//do something here like load a loading spinner etc.
},
})
.done(function() {
window.location.reload(true);
})
});
N.B. Just as a design point...I note that you reload the page as soon as AJAX has completed. The whole point of AJAX is to allow you to stay on the same page without re-loading. To avoid this unnecessary duplication of HTTP requests, you could either
a) forget about using AJAX for this, and just do a normal postback to update the quantity, or
b) when the AJAX completes, use a little bit of JavaScript just to update the cookie client-side instead.
I'm developing a WordPress plugin and I have added some elements on admin settings using php file. Now I want to execute a php function on button click and after searching on internet, AJAX seemed like a way to go. But I don't know AJAX at all. So here is some code I put together.
And I know this code may seem messed up but please take a look.
echo"<form method='POST' action='temp.php'>";
function slideyglidey_settings_section_callback() {
esc_html_e( 'Plugin settings section description', 'slideyglidey' );
}
function slideyglidey_settings_input_file_callback() {
$options = get_option( 'slideyglidey_settings' );
$file_input = '';
if( isset( $options[ 'file_input' ] ) ) {
$file_input = esc_html( $options['file_input'] );
}
echo '<input type="file" id="slideyglidey_fileinput"
name="slideyglidey_settings[file_input]" value="' . $file_input . '"
onchange="onFileSelected(event)" />';
}
function slideyglidey_settings_img_src_callback() {
$options = get_option( 'slideyglidey_settings' );
$img_src = '';
if( isset( $options[ 'img_src' ] ) ) {
$img_src = esc_html( $options['img_src'] );
}
echo '<img src="" id="slideyglidey_imgsrc"
name="slideyglidey_settings[img_src]" value="' . $img_src . '" width="350"
height="200"/>';
}
function slideyglidey_settings_upload_btn_callback() {
$options = get_option( 'slideyglidey_settings' );
$upload_btn = '';
if( isset( $options[ 'upload_btn' ] ) ) {
$upload_btn = esc_html( $options['upload_btn'] );
}
echo '<input type="button" id="slideyglidey_uploadbtn"
name="slideyglidey_settings[upload_btn]" value="Upload"/>';
}
echo"</form>";
?>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var $checkboxes = $( "form input:file" )
$checkboxes.on("change", function(){
var st="helloHOWAREYOU";
$.ajax({
type: "POST",
url: "temp.php",
cache: false,
data: 'name=' + st,
success: function(res){
$('#result').html(res);
}
});
})
</script>
temp.php
<?php
$name = $_POST['name'];
echo '<script>console.log($name)</script>';
?>
When I execute this code, I get no errors but I don't get the message in console log as well.
Any help is appreciated.
Thanks!
You can use this way to pass data
$.ajax({
...
data : {name : 'helloHOWAREYOU'},
...
});
Assuming this is your button:
echo <button id="handler">click me</button>
Then put the following code in a <script> tag:
document.getElementById('handler').addEventListener('click', AJAX);
function AJAX() {
const req = new XMLHttpRequest();
req.addEventListener("load", (data) => console.dir(data.target.response));
req.open("GET", "https://reqres.in/api/users?page=2");
req.send();
}
<button id="handler">click me</button>
Note I now perform the AJAX request to a website which offers some dummy data. Of course you have to change this to your own requirements.
I am using ajax to send data to a php function. The end goal is to display rows of data based on $tweetdate. Here is my ajax script:
jQuery('#bootstrapModalFullCalendar').fullCalendar({
dayClick: function(date, event, jsEvent, view) {
var date = date.format();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'show_scheduled_tweets',
'tweetdate': date
},
beforeSend: function() {
console.log('before')
},
success: function(){
console.log('success')
},
error: function(){
console.log('error')
},
});
}
});
Here is my php function (add_action is for WordPress usage):
<?php
add_action('wp_ajax_show_scheduled_tweets', 'show_scheduled_tweets');
function show_scheduled_tweets () {
global $wpdb;
$tweetdate = $_POST["tweetdate"];
$query = "SELECT * FROM wp_tweettweet WHERE tweetdate='$tweetdate'";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
$currentDateTime = $result[time];
$time = date('h:i A', strtotime($currentDateTime));
?>
<form class="tweetclass form-inline" action="" method="post">
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
<input class="tweetinput" type="text" name="tweetupdate" value="<?php echo $tweet2; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="timepicker" class="timepicker" value="<?php echo $time; ?>"/>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
}
show_scheduled_tweets();
?>
fullCalendar is a jQuery event calendar. When the user clicks on a day (dayClick) that day is saved to date. That date is what I am trying to save to "tweetdate" in my ajax.
In chrome, when I use the network tab on the inspector I can see the ajax result and the date clicked on is set to "tweetdate". That isn't getting picked up by my php function. In my php "tweetdate" is not getting a value assigned to it.
Now, if I go into my php function and set "tweetdate" to an actual date instead of $_POST["tweetdate"]; e.g. 2016-06-15 than everything works perfectly.
I'm not quite sure what is going on.
To make it work, you need one more essential thing:
add_action('wp_enqueue_scripts', 'my_custom_scripts');
my_custom_scripts(){
// Here you register your script for example located in a subfolder `js` of your active theme
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
// Here you are going to make the bridge between php and js
wp_localize_script( 'ajax-script', 'my_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
See that 'ajax-script' is in both functions wp_enqueue_script() and wp_localize_script()…
Then you will retrieve 'ajaxurl' and 'my_ajax' in your js combined in url:my_ajax.ajaxurl,:
jQuery(document).ready(function($) {
jQuery('#bootstrapModalFullCalendar').fullCalendar({
dayClick: function(date, event, jsEvent, view) {
var date = date.format();
jQuery.ajax({
type: "POST",
url: my_ajax.ajaxurl,// Here 'my_ajax' & 'ajaxurl' from wp_localize_script()
data: {
'action': 'show_scheduled_tweets',
'tweetdate': date
},
beforeSend: function() {
console.log('before')
},
success: function(){
console.log('success')
},
error: function(){
console.log('error')
},
});
}
});
});
Now you can get the $_POST["tweetdate"];in your php!!!
Update: May be you need to add to your php function (for front end):
add_action('wp_ajax_nopriv_show_scheduled_tweets', 'show_scheduled_tweets');
And to and die();at the end inside your function. so you will have:
add_action('wp_ajax_show_scheduled_tweets', 'show_scheduled_tweets'); // backend
add_action('wp_ajax_nopriv_show_scheduled_tweets', 'show_scheduled_tweets'); // fronted
function show_scheduled_tweets () {
global $wpdb;
$tweetdate = $_POST["tweetdate"];
$query = "SELECT * FROM wp_tweettweet WHERE tweetdate='$tweetdate'";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
$currentDateTime = $result[time];
$time = date('h:i A', strtotime($currentDateTime));
?>
<form class="tweetclass form-inline" action="" method="post">
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
<input class="tweetinput" type="text" name="tweetupdate" value="<?php echo $tweet2; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="timepicker" class="timepicker" value="<?php echo $time; ?>"/>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
die(); // very important to get it working
}
Update 2: important! — It should work this time!
I have made a little typing error:
It's add_action('wp_ajax_nopriv_ … instead of add_action('wp_ajax_no_priv_ …
These php codes needs to be on the function.php file of your active theme (or child theme).
Then you will call your function somewhere else or you can hook it with some add_action() hooks.
show_scheduled_tweets();
References:
Wordpress passing ajax value to a specific page using Wordpress
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?
I'm trying to send AJAX data to my wordpress table but all I can get from my PHP is a 0. Its on the admin side. Can anyone help me?
Also all of this code is inside my plugin-admin.php file inside my plugin folder.
<?php
if ( ! defined( 'ABSPATH' ) || ! current_user_can( 'manage_options' ) ) exit;
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<script>
jQuery(document).ready(function($) {
var spostsarray = new Array();
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: "POST",
action: "featured_submit_action",
data: {"posts": spostsarray},
success: function(data){
console.log(data);
}
});
});
});
</script>
I've condensed it a bit but the general idea is that I can grab all the recent posts and the user can select which ones they want to feature, send that to the PHP method and edit the table with it.
The problem is with my AJAX callback I only ever return 0 and not the data sent from the javascript.
SOLVED:
After some help from Rohil_PHPBeginner I figured it out. The reason it didn't work is that I was executing the code from the menu page at at that point it was too late to add a hook. Here is the page I used to solve it:
AJAX in WP Plugin returns 0 always
Below code worked perfectly fine for me:
<?php
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<?php
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
add_action( 'wp_ajax_nopriv_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<script>
jQuery(document).ready(function($) {
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
});
});
</script>
You don't need to pass the AJAX url in that way because when I used your code, it is showing me with PHP. WordPress provides a default url for AJAX so you can use that( ajaxurl which I used in below code).
Other than that You have not added code for no-privilege user (if it is going to use only for privileged user then it is okay otherwise you need to add code for that).
WordPress returns 0 when an ajax call doesn't find a valid callback function (though the 0 could be return from many other things).
WordPress looks for callbacks matching wp_ajax_{callback} when a user is logged in and wp_ajax_nopriv_{callback} when the user is logged out. {callback} is populated with the POST'd value of the "action" hidden input. Note that you're not passing the action into your AJAX call. You should change:
data: {"posts": spostsarray},
to
data: data
Since you're not going to match a callback function without passing in action, WordPress is returning 0
Hi i am developing a plugin in wordpress.
i tried code for create autocomplete text box in my customized form.
Ajax Calling function
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
foreach($result as $dis)
{
$data.=$dis->city."<br>";
}
echo $data;
die();
}
add_action( 'wp_ajax_city_action', 'city_action_callback' );
add_action( 'wp_ajax_nopriv_city_action', 'city_action_callback' );
Shortcode function
function my_search_form() {
?>
<script>
jQuery(document).ready(function($) {
jQuery('#city').keyup(function() {
cid=jQuery(this).attr('val');
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
//alert(response);
});
});
});
</script>
<input type="text" id="city" name="city" autocomplete="off"/>
<?php
}
this code return related results perfectly in variable response.
But i don't know how create a text box look like a autocomplete box.
Please explain me how to do that in wordpress?
Just add a div under the input tag
HTML Code:
<input type="text" id="city" name="city" autocomplete="off"/>
<div id="key"></div>
replace the div after the success on you ajax.
Ajax Code:
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
$('#key').html(response);
});
PHP Code:
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
echo '<ul>'
foreach($result as $dis)
{
echo '<li>'.$dis->city.'</li>';
}
echo '</ul>'
die();
}