I am currently working on a Wordpress project and I have a issue during an ajax request:
On my view, I have this button for displaying more articles on my page :
<input type="hidden" name="nbPages" value="<?php echo $nb_pages;?>">
<input type="hidden" name="pageActive" value="1">
<input type="hidden" name="termSlug" value="<?php echo $term_query->slug;?>">
.
.
.
<div class="product-bottom">
<img src="<?php echo get_template_directory_uri();?>/img/ajax-loader.gif" alt="" id="ajax-loader" style="display:none;">
<button class="btn btn-site-1" id="loadmore_bt">See more</button>
</div>
On my js file, I have this part that is called when the button is used
add_action('wp_ajax_ajax_loadmore', 'ajax_loadmore');
$(function () {
'use strict';
//AJAX LOAD MORE PRODUCTS
jQuery('body').on('click', '#loadmore_bt', function (e) {
e.preventDefault();
$('#ajax-loader').fadeIn(500);
var nbPages = jQuery('input[name="nbPages"]').val();
var activePage = jQuery('input[name="pageActive"]').val();
var termSlug = jQuery('input[name="termSlug"]').val();
jQuery.ajax({
type: 'POST',
dataType: "JSON",
data: {
'action': 'ajax_loadmore',
'nbPages': nbPages,
'activePage': activePage,
'termSlug': termSlug
},
url : ajaxurl,
success : function(response){
console.log('cool!');
console.log(response.newPageToDisplay);
}
})
In function.php , I have this function which is called :
function ajax_loadmore(){
.
.
// set query arg as $args_products
.
.
$products = new WP_Query($args_products);
$rendering = '';
if ($products->have_posts()) {
foreach ($products->posts as $key => $prod) {
$rendering .= "
<div>
<h2 class="card-title main-title-2">' . $prod->post_title . '</h2>
<p class="card-subtitle">' . get_field('reference', $prod->ID) . '</p>
</div>
<div class="card-txt">' . get_field('desriptif_court', $prod->ID) . '</div>
<button class="btn btn-site-1">More info</button>
</div>";
}
$json = array(
'reponse' => 'success',
'newPageToDisplay' => $rendering,
'pageloaded' => $pageToLoad,
'activePage' => $activePage,
);
echo json_encode($json);
}else{
echo "error";
echo json_encode(array(
'reponse' => $reponse
));
}
die();
}
My issue is: $rendering has not the same value than in the js response (as response.newPageToDisplay).
For exemple, on the first element of $rendering is $prod->post_title = 'PA80MP' , while the first element of response.newPageToDisplay is 'PA95'. Both are indeed existing values in my database.
TLDR : Ajax doesn't have the same value of variables as in the php file function that it calls.
Hope I explain well my problem ...thank you for helping!
Related
I have been following a few tutorials online for how to do this, and I do not know where I missed the mark... when I press my submit button, it does nothing but reload the page. I do not see any errors in loading my js though in the console of chrome so I think that might be my issue. But still unsure.
Basically, people can provide a new billing_address on their dashboard, and the billing address is associated with a user and sku.
Here is my form with three items (user, sku, address);
$loop = new WP_Query( $args );
echo '<form id="addressform" method = "post">';
echo '<br><select id="sku" name="sku" required >';
echo '<option value="empty">-- Select Coin--</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<option value=' . $product->get_sku() . '>' . $product->get_sku() . ' </option>';
endwhile;
echo '</select>';
echo '<input type="text" placeholder="Insert new address here" id="address" name="address" size="40" required />';
echo '<input type="hidden" id="userid" name="userid" value="' . $userid . '">';
echo '<input type="submit" id="submit" name="submit" value="Submit">';
echo '</form>';
echo '<div class="alert alert-danger display-error" style="display: none"></div>';
here is my javascript file known as address_submit.js
jQuery(document).ready(function($) {
jQuery('form#addressform').on('submit', function(e){{
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: submitaddress_ajax_obj.ajaxurl,
data: {
'userid' : jQuery('form#addressform #userid').val(),
'sku' : jQuery('form#addressform #sku').val(),
'address' : jQuery('form#addressform #address').val(),
'action' : 'submitaddress'
},
success : function(data){
if (data.code == "200"){
alert("Success: " +data.msg);
} else {
jQuery(".display-error").html("<ul>"+data.msg+"</ul>");
jQuery(".display-error").css("display","block");
}
}
});
e.preventDefault();
});
});
and lastly, I knew I needed to add it to my functions.php for my child theme so I created a second file (address_verifier.php) and included it like this in my themes functions.php :
require_once( __DIR__ . '/include/address_verifier.php');
And lastly, here is what is in the address_verifier.php
function submitaddress_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_register_script('submitaddress-ajax-script', get_stylesheet_directory_uri() . '/js/address_submit.js', array('jquery') );
wp_enqueue_script('submitaddress-ajax-script');
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script('submitaddress-ajax-script','submitaddress_ajax_obj',array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'loadingmessage' => __('Submitting Address...') ));
}
add_action( 'wp_enqueue_scripts', 'submitaddress_ajax_enqueue' );
add_action( 'wp_ajax_submitaddress', 'submitaddress' );
add_action( 'wp_ajax_nopriv_submitaddress', 'submitaddress' );
function submitaddress() {
global $woocommerce,$wpdb,$product;
$errorMSG = [];
//check if data is present
$user = $_POST['userid'];
//check sku selected
if (empty($_POST['sku'])) {
$errorMSG .= "<li>Please select a product.</li>";
} else {
$sku = $_POST['sku'];
}
//check address input
if (empty($_POST['address'])) {
$errorMSG .= "<li>Please enter an address.</li>";
} else {
$address = $_POST['address'];
}
if(empty($errorMSG)){
$updateaddress = $wpdb->query( $wpdb->prepare("REPLACE INTO ".$wpdb->prefix."newaddress (user, sku, address) VALUES (%d, %s, %s)", $user, $sku, $address ) );
$msg = "<strong> <i class='fa fa-check' aria-hidden='true'></i> Your <font color='red'>" . $sku . " </font>address has been updated. </strong>";
echo json_encode(['code'=>200, 'msg'=>$msg]);
die;
}
echo json_encode(['code'=>404, 'msg'=>$errorMSG]);
die();
}
move e.preventDefault(); to the top of the function.
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?
Hi i'm currently developing a php page which has an file upload feature. my form sends over 2 hidden values which is an order id and sender id and the file. I have to use ajax as i can't make it refresh after upload. The file upload has to be in my upload/files folder and i need to store the order id , sender id and filename in mysql.My ajax is getting the order id and sender id when i serialize but not the file. i tried seraching on this site for solutions and came acrross FormData object way to no success and also few other methods. the error in my console is always undefined sender_id, file order_id. It doesnt get the values from the html form. Thanks for helping.
MY php, html form
<form method="POST " id="form1" name="form1" enctype='multipart/form-data' >
<input type="hidden" name="sender_id" value="<?php echo $_SESSION['user_session']?>">
<input type="hidden" name="order_id" value="<?php echo $_GET['oid']?>">
<?php //echo var_dump($sellerinfo);?>
<div>
<div>
<textarea name="comments" placeholder="Leave Comments Here..." style="width:800px; height:100px;"></textarea>
<div class="row">
<input type="file" id="file" name="fileupload">
<input type="reset" value="Reset">
<a type="file" href="" class="button" id="fileupload" name="fileupload"> UPLOAD FILE </a>
<br>
<a id="comment" href="" class="button">Post</a>
<input type="reset" value="Reset">
</form>
File.js (ajax file)
$("#fileupload").click(function(e){
alert("inside ajax");
var formData = $("#form1").serialize()
alert(formData);
var formData = new FormData();
var file_data = $('#file').prop('files')[0];
formData.append('file', file_data);
alert(formData);
$.ajax({
url: '../modules/Comment/fileupload.php',
type: 'POST',
dataType:"json",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
error: function (result) {
console.log(result);
alert('ERROR RUNNING INSERTSCRIPT');
},
success: function (result) {
alert(result)
if (result['result'] == true) {
alert("success");
order_id = document.form1.order_id.value;
$('#comment_logs').load("../modules/comment/file_logs.php?",{oid:order_id} );
}
else if (result['result'] == false) {
alert('ERROR');
}
},
});
});
My php script that is supposed to upload and insert data inside database.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require('commentclass.php');
$connect = new connect(); // new connect class OBJECT
$conn = $connect->get_connection(); // getting Connection from Connect Object
$sender_id=$_POST['sender_id'];
$order_id=$_POST['order_id'];
$Filename=basename( $_FILES['Filename']['name']);
define ('SITE_ROOT', realpath(dirname(__FILE__)));
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], '../../uploads/files/' . $_FILES['file']['name'])) ;
{
echo "The file " . basename($_FILES['Filename']['name']) . " has been uploaded, and your information has been added to the directory";
$sql = "INSERT INTO files(order_id,send_by,file_name) VALUES ('" . $order_id . "','" . $sender_id . "','" . $Filename . "')";
$result = mysqli_query($conn, $sql);
$data = array();
if ($result) {
$data['result'] = true;
echo json_encode($data);
}
else
{
$data['result'] = true;
echo json_encode($data);
}
}
}
?>
Sorry for the long post, hope someone can help . Thanks in advance
I have passed an array tree from controller to view and I am using a helper for recurssion to display it in the form of unordered lists. I have a button with each list item to move one step up. My view div is like this:
<div id="div">
<?php
$ordering = count($trees[$grp->id]);
?>
<a href="javascript:Swapit('swapper-first','swap')" onClick="showIFrame('<?php echo site_url('service_group_services/edit/0_' . $ordering . '_' . $grp->id); ?>');">
<button type="button" class="btn btn-default btn-xs btn-label-left">
<i class="fa fa-plus"></i>
</button>
</a>
<?php
display_tree($trees[$grp->id], $grp->id);
?>
</div>
<?php endforeach; ?>
here, display_tree is a helper:
<?php function display_tree($array, $grp) {
foreach ($array as $value): {
$ordering = 0;
if (isset($value->childs[0])) {
$val = $value->childs;
$ordering = count($val);
}
echo "\n<ul>";
echo "\n<li>";
if($value->type != 'SERVICE') {
echo '<span> <i class="fa fa-plus"></i></span>';
}
if($value->ordering != 0) {
echo '<span> <i class="fa fa-sort-up"></i></span>';
}
echo '<span> <i class="fa fa-times"></i></span>'. $value->name .'</li>';
if (isset($value->childs[0])){
$val = $value->childs;
display_tree($val, $grp);
}
echo '</ul>';
}
endforeach;
}
?>`
controller function:
function move_up(){
$parent = $this->input->post('service_parent');
$ordering = $this->input->post('ordering');
$group = $this->input->post('service_group');
$service = $this->input->post('service');
$s_p = $this->session->userdata('service_provider');
$this->Mdl_service_group_services->up($s_p, $parent, $group, $ordering);
$this->Mdl_service_group_services->up1($s_p, $service, $parent, $group, $ordering);
}
n model is:
function up($s_p, $parent, $group, $ordering) {
$data = array(
'ordering' => $ordering
);
$this->db->where('service_provider =', $s_p);
$this->db->where('service_group =', $group);
$this->db->where('service_parent =', $parent);
$this->db->where('ordering =', --$ordering);
$this->db->set($data);
$this->db->update($this->_table_name);
}
function up1($s_p, $service, $parent, $group, $ordering) {
$var = array(
'ordering' => --$ordering
);
$this->db->where('service_provider =', $s_p);
$this->db->where('service_group =', $group);
$this->db->where('service_parent =', $parent);
$this->db->where('service =', $service);
$this->db->set($var);
$this->db->update($this->_table_name);
}
Now I am trying to update the ordering column of database table with ajax.
Ajax code is:
var controller = 'service_group_services';
var base_url = '<?php echo site_url(); //you have to load the "url_helper" to use this function ?>';
function load_data_ajax(parent, ordering, group, service){
$.ajax({
'url' : base_url + controller + '/move_up',
'type' : 'POST', //the way you want to send data to your URL
'data' : 'service_parent='+parent+'ordering='+ordering+'service_group='+group+'service='+service,
'success' : function(data){ //probably this request will return anything, it'll be put in var "data"
var div = $('#div'); //jquery selector (get element by id)
if(data){
div.html(data);
}
}
});
}
But when i click on up button, nothing is happening. Please help me.
There is an problem in your AJAX request. You forgot to add &seprator between each parameters of the data you want to send :
function load_data_ajax(parent, ordering, group, service){
$.ajax({
...
'data' : 'service_parent='+parent+'&ordering='+ordering+'&service_group='+group+'&service='+service,
...
});
}
I have on a controller a function on codeigniter which gets and checks image for my templates.
I have place a id="template" just after my thumbnail bootstrap div id template works with my script code.
Currently when I select theme I get a firebug error
Error Pop Up
SyntaxError: missing ; before statement
OK
{"image":"<img src=\\\"http:\/\/localhost\/codeigniter\/codeigniter-cms\/image\/templates\/default.png\\\" alt=\\\"\\\"\/>"}
Controller Image Function
public function template() {
$this->load->helper('html');
if (file_exists(FCPATH . 'image/templates/' . $this->configs->get('config_template') . '.png') == FALSE) {
$img = addslashes(img('image/no_image.png'));
echo json_encode(array('image'=>$img));
} else {
if($this->input->post('config_template') !== FALSE) {
$img = addslashes(img('image/templates/' . basename($this->input->post('config_template')) . '.png'));
echo json_encode(array('image'=>$img));
}
}
}
View
<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="form-setting" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" for="input-template"><?php echo $entry_template; ?></label>
<div class="col-sm-10">
<select name="config_template" id="input-template" class="form-control">
<?php foreach ($templates as $template) { ?>
<?php if ($template == $config_template) { ?>
<option value="<?php echo $template; ?>" selected="selected"><?php echo $template; ?></option>
<?php } else { ?>
<option value="<?php echo $template; ?>"><?php echo $template; ?></option>
<?php } ?>
<?php } ?>
</select>
<div class="form-group">
<div class="col-lg-4">
<div class="img-thumbnail">
<div id="template"></div>
</div>
</div>
</div>
</form>
<script>
console.log('Jquery is working');
$('select[name="config_template"]').on('change', function () {
var template_name;
template_name = encodeURIComponent(this.value);
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: '<?=base_url('admin/setting/template');?>' + '/',
data: { config_template: template_name
},
complete: function () {
$('.fa-spin').remove();
},
success: function (data) {
$('.fa-spin').remove();
$('#template').html(data.image);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
})
</script>
Found out issue it was addslashes
old
public function template() {
$this->load->helper('html');
if (file_exists(FCPATH . 'image/templates/' . $this->configs->get('config_template') . '.png') == FALSE) {
$img = addslashes(img('image/no_image.png'));
echo json_encode(array('image'=>$img));
} else {
if($this->input->post('config_template') !== FALSE) {
$img = addslashes(img('image/templates/' . basename($this->input->post('config_template')) . '.png'));
echo json_encode(array('image'=>$img));
}
}
}
new
public function template() {
$this->load->helper('html');
if (file_exists(FCPATH . 'image/templates/' . $this->configs->get('config_template') . '.png') == FALSE) {
$img = img('image/no_image.png');
echo json_encode(array('image'=>$img));
}else
{
if($this->input->post('config_template') !== FALSE)
{
$img = img('image/templates/' . $this->input->post('config_template') . '.png');
echo json_encode(array('image'=>$img));
}
}
}
You are outputting JSON. Not JSONP. Change dataType: 'jsonp', to dataType: 'json',
Adding slashes to some HTML will break that HTML. You'll be putting \ characters in your image URLs and making them wrong. Remove all uses of the addslashes function. encode_json will do all the escaping you need.