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?
Related
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']);
}
}
}
?>
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 posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz
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();
}