Hello!
I have a problem with my "custom" pagination for component in joomla.
I wanted to do list of user's articles which will shows for an example 3 posts per page. My goal was to make pagination without refreshing webpage. Ajax was the best choice. I'm fighting with it right now and have the most difficult problem so far (I tried to search answer of my problem several hours).
user.php
<div class="userRightContainer">
<div class="blogArticlesBlock">
<div class="userItemTagsBlock"><b>Debaty na forum użytkownika(<?php echo $joomla_rows; ?>)</b></div>
<?//artykuly joomla
?>
<div id="Joomla_block" class="Joomla_block">
<? require_once("Db_joomla.php") ?>
</div>
...
...
...
<script type="text/javascript">
function jm_previous(arg) {
if(arg < 0)
changePagination(0);
else
changePagination(arg);
}
function jm_next(argument) {
changePagination(argument);
}
function changePagination(pageId){
// $("#Joomla_block").html('');
jQuery.ajax({
type: "GET",
// url: "Db_joomla.php",
url: window.location.href,
data: { jm_start: pageId},
success: function(result){
alert(result);
$("#Joomla_block").html(result);
}
});
}
</script>
Db_joomla.php
defined('_JEXEC') or die;
//
$offset_jm=$_GET["jm_start"];
if(empty($offset_jm)) $offset_jm=0;
//
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id', 'title', 'introtext', 'created_by', 'state')));
$query->from($db->quoteName('#__content'));
$query->where($db->quoteName('created_by') . ' LIKE ' . $db->quote(JRequest::getInt('id')));
$query->where('state', '1');
$query->setLimit($joomla_page,$offset_jm);
$db->setQuery($query);
$joomla=$db->loadObjectList();
$joomla_rows = $db->loadResult();
if($joomla_rows > 0){
foreach($joomla as $row) {
if ($row->created_by != JRequest::getInt('id')) continue;
?>
<div class="articlesBlock" style="margin: 5px;">
<!-- Avatar -->
<img src="<?php echo $this->user->avatar; ?>" alt="<?php echo htmlspecialchars($this->user->name, ENT_QUOTES, 'UTF-8'); ?>" style="width:50px; height:auto;border: 1px solid #ccc; float:left;margin: 5px;" />
<div class="blogArticlestTitle" style="padding-left:60px;font-weight:bold;word-wrap:break-word;"><?php echo $row->title ?></div>
<div class="blogArticlesDescription" style="padding: 5px;padding-top:10px;"><?php if (str_word_count($row->introtext) > 100) echo /* Wstawia komentarz i ogranicza tekst do stu znaków, po czym dodaje kropki.*/ substr(strip_tags($row->introtext), 0, 100) . "..."; else echo strip_tags($row->introtext);?>
</div>
<div class="CommentViewMore">
Przejdź do artykułu ›
</div>
</div>
<?php
/*
$item_counting++;
if($item_counting == 5) break;*/
}
//echo $pageNav->getListFooter( ); //Displays a nice footer
?>
<ul class="pager">
<li><<</li>
<li>>></li>
</ul>
<a class ="view_more_link"href="http://konfederaci.pl/index.php/component/komento/profile/id/<?php echo JRequest::getInt('id');?>" title="Artykuły użytkownika">Zobacz wszystkie artykuły</a>
<?php
}
else
{
echo "Ten użytkownik nie posiada żadnych postów na forum.";
}
Now some pictures:
From alert(result)
From google chrome's console
Ps:
If I choose "url : "Db_joomla.php" in this script it won't make anything. still doesn't work (and the same exception).
It's always a better idea to rely on Joomla's Ajax interface rather than implementing yours. It is super simple and very efficient and it works. We have written on how to use it here.
Essentially you will create/modify a simple module that will contain a function (that has the word Ajax at the end of its name) that will be used to process the call.
Then, you will need to add a simple jquery code that will call the module through the com_ajax interface. Note that you will need to make sure to have the module assigned to a menu item because you will need the ID of that menu item for the ajax call.
Simply practics:
Your ajax backend part should be contains only PHP code. (Get DB query).
Next this PHP should return JSON array with results.
You get this JSON for ajax request and push this data for your view.
For simply I use my plugin "plg_ajax" (after install see method onAjaxAjax()).
Example script post for this plugin with com_ajax:
type: "POST",
async: true,
url: "index.php?option=com_ajax&plugin=ajax&format=json",
dataType: "json",
Related
Good Day. I'm trying to develop a plugin for WordPress that manually sends an e-mail (containg the WooCommerce Order details) to a desired supplier's e-mail. I'm having a hard time figuring out on how to load a data when a user select from a drop down list. I would like to load the data using AJAX on multiple fields without leaving the page. Here's some part of the code:
<select id = "dropdown_orders" class = "dropdown_orders" name="dropdown_orders" onchange="myFunction(this.value)">
<option value=""><?php _e( 'Select an Order', 'woocommerce-manual-order-forwarding' ); ?></option>
<?php
foreach($order_details as $details => $value)
{
echo '<option value="' . $value['ID'] . '">' . "Order ID: " .$value['ID'] . '</option>';
}
?>
</select>
That is the code for the drop down list to show all the Orders with "Complete" Status. And here is the AJAX part.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"</script>
<script type="text/javascript">
function myFunction(value)
{
if(value!="")
{
$.ajax(
{
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { experience: value},
success: function(data) {
alert("You have selected the Order ID of: " + value);
//I want to display a div element that contains all the data from the WordPress database.
}
});
}
else
{
alert("Please Select and Order ID first!");
}
}
</script>
What I want to achieve is that, when the user select from one of the options from the drop down list, the page will display a div element that displays all the details about the order. Is it possible to do that? Any help would be appreciated. I know that it's impossible to call a PHP function after the "success" part of AJAX.
EDIT HERE
On display-orders-admin.php
<div id="forward-field" class="wrap">
<h2><?php _e( 'WooCommerce Order Forwarding System', 'woocommerce-manual-order-forwarding' ); ?></h2>
<p><?php _e( '<strong>Note:</strong> This add-on gives you the capability to forward your WooCommerce orders individually on your desired supplier.', 'woocommerce-manual-order-forwarding');?></p>
</div>
<div class="container-box">
<h2><?php _e( 'Order Details', 'woocommerce-manual-order-forwarding' ); ?></h2>
<p><?php _e( '<strong>Note:</strong> Please select an order from the drop down list below to use the order e-mail forwarding feature.', 'woocommerce-manual-order-forwarding');?></p>
<select id = "dropdown_orders" class = "dropdown_orders" name="dropdown_orders">
<option value=""><?php _e( 'Select an Order', 'woocommerce-manual-order-forwarding' ); ?></option>
<?php
foreach($order_details as $details => $value)
{
echo '<option value="' . $value['ID'] . '">' . "Order ID: " .$value['ID'] . '</option>';
}
?>
</select>
<div class="custom-border"></div>
<!-- TRIGGER AN ACTION HERE WHEN THE USER SELECT FROM ONE OF THE ORDER IDS FROM DROPDOWN -->
<!-- EXECUTE A JQUERY | AJAX REQUEST TO PULL OUT ALL THE DETAILS OF THE ORDER WITH THE GIVEN ID -->
<!-- DISPLAY THE ORDER DETAILS USING DIV ELEMENTS ON THE SAME PAGE -->
</div>
How can I achieve those in comments?
First you are using jQuery, yet you are doing things old-school by using onchange. Let's not do that.
Remove onchange attribute and instead attach an onchange event listener to your dropdown using .change() method.
<select id="dropdown_orders" class="dropdown_orders" name="dropdown_orders">
<option value=""><?php _e( 'Select an Order', 'woocommerce-manual-order-forwarding' ); ?></option>
<?php foreach ($order_details as $details => $value) : ?>
<option value="<?php echo $value['ID'] ?>">Order ID: <?php echo $value['ID'] ?></option>
<?php endif ?>
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"</script>
<script>
$(function () {
$('#dropdown_orders').change(function () {
if (this.value != "") {
// fyi: $.getJSON() method is a shorter syntax
$.ajax({
type: "GET",
url: '<?php echo $_SERVER['PHP_SELF'] ?>',
data: { experience: this.value },
dataType: "json",
success: function (res) {
// ...
}
});
} else {
alert("Please Select and Order ID first!");
}
});
});
</script>
Now, regarding your actual problem, make your PHP return back a JSON string using json_encode(). A starter example of how your PHP script would look like:
// first step: check the request parameter
if (isset($_GET['experience'])) {
// get the order detail e.g. $order based on the request parameter
// let's assume $order is an associative array e.g. $order = ['id' => 123, 'price' => 12.40]
// final step: send back a JSON-encoded response
header('Content-Type: application/json');
echo json_encode($order); // only this should be echo'd
}
Back to the HTML/JS code, all you have to do is process the response res once it is received in the success callback. First, it may be a good idea to create and re-use a hidden block element to store your order detail's information. This will be like a template. You will just need to show it once the order information is ready.
So, first add the following to your HTML:
<div id="order-detail" style="display: none;">
<div class="id"></div>
<div class="price"></div>
</div>
Next, change your JS.
$(function () {
$('#dropdown_orders').change(function () {
if (this.value != "") {
// fyi: $.getJSON() method is a shorter syntax
$.ajax({
type: "GET",
url: "<?php echo $_SERVER['PHP_SELF'] ?>",
data: { experience: this.value },
dataType: "json",
success: function (res) {
// load the information from your response into the DIV
var $div = $('#order-detail');
$div.find('.id').html(res.id);
$div.find('.price').html(res.price);
// show the DIV once everything is ready
$div.show();
}
});
} else {
alert("Please Select and Order ID first!");
}
});
});
Instead of having a template to store your order details, you can also build the DIV with the order information within your success callback; however, this may lead to messy code.
I'm trying my best to get this to work. But AJAX is pretty new to me. So hang in there...
Ok, I've asked a couple of questions here about getting this issue that I'm having to work. I (We)'ve come a long way. But now the next issue is here.
I'm trying to echo a session in a div using AJAX.
The AJAX code is working, I can echo plain text to the div I want it to go. The only problem I have is it does not display the title of the item.
I have some items (lets say 3 for this example) and I would like to have the custom save the Items in a Session. So when the customer clicks on save. The ajax div displays the title. And if the custom clicks the 3rd item it show the 1st and 3rd item, etc...
My HTML:
<button type="submit" class="btn btn-primary text-right" data-toggle="modal" data-target=".post-<?php the_ID(); ?>" data-attribute="<?php the_title(); ?>" data-whatever="<?php the_title(); ?>">Sla deze boot op <span class="glyphicon glyphicon-heart" aria-hidden="true"></span></button>
My AJAX code:
$(".ajaxform").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "example.com/reload.php",
success: function(data) {
$(".txtHint").html(data);
},
error: function() {
alert('Not OKay');
}
});
return false;
});
My PHP reload.php:
<h4>Saved Items</h4>
<p>Blaat...</p>
<?php echo "Product Name = ". $_SESSION['item'];?>
I saw this code on here: I'm not using this code. Only wondering if I can use it for my code, and then how?
Change session.php to this:
<?php
session_start();
// store session data
$_SESSION['productName'] = $_POST['productName'];
//retrieve session data
echo "Product Name = ". $_SESSION['productName'];
?>
And in your HTML code:
function addCart(){
var brandName = $('iframe').contents().find('.section01a h2').text();
$.post("sessions.php", {"name": brandName}, function(results) {
$('#SOME-ELEMENT').html(results);
});
}
How I'm getting my title();:
<?php
// Set session variables
$_SESSION["item"][] = get_the_title();
?>
Is this some thing I can use? And could someone help me with the code?
Thanks in advance!
I'm not too sure on what exactly you're trying to accomplish, but here's a quick and dirty example of making an HTTP request (POST) with a name of a product, storing it in a PHP session, and outputting all product names in the session:
HTML
<p>Product A <button class="add-product" data-product="Product A">Add Product</button></p>
<p>Product B <button class="add-product" data-product="Product B">Add Product</button></p>
<p>Product C <button class="add-product" data-product="Product C">Add Product</button></p>
<div id="response">
</div>
JavaScript
$('.add-product').click(function() {
var productName = $(this).data('product');
$.post('addProduct.php', {productName: productName}, function(data) {
$('#response').html(data);
})
});
PHP (addProduct.php)
<?php
session_start();
if (!array_key_exists('products', $_SESSION) || !is_array($_SESSION['products'])) {
$_SESSION['products'] = [];
}
$productName = array_key_exists('productName', $_POST) ? (string) $_POST['productName'] : '';
if ($productName) {
$_SESSION['products'][] = $productName;
}
?>
<h4>Your added products:</h4>
<ul>
<?php foreach ($_SESSION['products'] as $product): ?>
<li><?php echo htmlspecialchars($product); ?></li>
<?php endforeach;?>
</ul>
I need a simple way to retrieve multiple PHP variables into html divs. I searched a lot of posts but I can't found an answer.
I am looking for something like this:
go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
?>
index.php
<div class="name">Your Name is : <?php echo $name; ?></div>
<div class="phone">Your Phone Number is : <?php echo $phone; ?></div>
<div class="details">Your Details are : <?php echo $details; ?></div>
I want instead of echo to get them via AJAX Call.
What is the correct AJAX REQUEST syntax to do that?
UPDATE
My bad I do not noticed before but forgot to say I also need to load the calls one by one. I have too many requests and take a lot of time.
May the query .each() function should work like I want?
In your PHP:
<?php
echo json_encode(Array(
'name' => "John",
'phone' => "1234567890",
'details' => "Details about..."
));
Your HTML:
<div class="name">Your Name is : <span class="name_value"></span></div>
<div class="phone">Your Phone Number is : <span class="phone_value"></span></div>
<div class="details">Your Details are : <span class="details_value"></span></div>
Your jQuery:
$(document).ready(function(){
$.getJSON('user-info.php',function(data){
$(".name_value").html(data.name);
$(".phone_value").html(data.phone);
$(".details_value").html(data.details);
});
});
Note: you'll set the user-info.php string to the URL (relative or absolute) of your PHP script that grabs the user info.
You need a PHP script that will output JSON containing the values you want, and you need a Javascript handler to ask for that data and do something when it gets it. Here's an example:
# File: go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
echo json_encode(
[
'name' => $name,
'phone' => $phone,
'details' => $details
]
);
Then your HTML page:
<!-- File: index.php -->
<div class="name">Your Name is : <span class="container"></span></div>
<div class="phone">Your Phone Number is : <span class="container"></span></div>
<div class="details">Your Details are : <span class="container"></span></div>
<button class="loadMe" type="button">Click here to make things work</button>
And finally your jQuery:
$(document).ready(function() {
$('.loadMe').click(function() {
$.ajax({
// Path to your backend handler script
url: 'go-to-index.php';
// Tell jQuery that you expect JSON response
dataType: 'json',
// Define what should happen once the data is received
success: function (result) {
$('.name .container').html(result.name);
$('.phone .container').html(result.phone);
$('.details .container').html(result.details);
},
// Handle errors in retrieving the data
error: function (result) {
alert('Your AJAX request didn\'t work. Debug time!');
}
});
});
});
You can do this on any event - the button was just an example. You can also use plain Javascript or any other library, just used jQuery since you tagged it in your question.
This question already has an answer here:
How do I use Ajax in a Wordpress plugin?
(1 answer)
Closed 8 years ago.
I want to fetch MySQL table (custom table) data to my admin panel via AJAX. When user click the button get data without page refresh.
I already created it on PHP but where to add AJAX file in WordPress?
This is my code. Note I am trying to make plugin When user click fetchdata button call the AJAX for result.
I added JS file in my plugin
I called js from main plugin file
function school_register_head() {
$siteurl = get_option('siteurl');
$url2 = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/jquery-1.3.2.js';
$url3 = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/script.js';
echo "<script src=$url2 type=text/javascript></script>\n";
echo "<script src=$url3 type=text/javascript></script>\n";
}
add_action('admin_head', 'school_register_head');
script.js file
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "display.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
display.php file
<?php
global $wpdb;
$rows = $wpdb->get_results("SELECT postid from `wp_school_post`");
echo "<table class='wp-list-table widefat fixed'>";
echo "<tr><th>ID</th><tr>";
foreach ($rows as $row ){
echo "<tr>";
echo "<td>$row->postid</td>";
echo "</tr>";}
echo "</table>";
?>
html button
<input type="button" id="display" class="button" value="Fetch All Data" onClick="fetch_data();" />
<div id="responsecontainer" align="center">
If "where to put the AJAX file" means how to include it to the admin page: The easiest way would be to use admin_enqueue_scripts(), for example, if you're implementing it in a theme:
<?php
function load_ajax_script() {
wp_enqueue_script("ajax-script", get_template_directory() . "/scripts/ajax-script.js");
}
add_action("admin_enqueue_scripts", "load_ajax_script");
?>
Add this code to your functions.php within the active theme directory.
Next step would be the jQuery script. Open the .js script file used with wp_enqueue_script() and add the following:
jQuery(document).ready(function() {
jQuery("#fetch-data").click(function() {
var script_url = "http://www.example.com/wp-content/themes/my-theme/display.php";
var response_container = jQuery("#responsecontainer");
jQuery.ajax({
type: "GET",
url:script_url,
success:function(response) {
response_container.html(response);
},
error:function() {
alert("There was an error while fetching the data.");
}
});
});
});
Note that you have to use a URL when calling the .php file, not the absolute path on the server as you would when using PHP's include(). Depending on where you put the script, use either $(...) or jQuery(...).
Now we have to insert the button that is calling AJAX and of course the container where the returned content is being inserted. Since you didn't say where it is being displayed, I just put it in the top of the admin area for now:
function display_ajax_button() {
?>
<input type="button" value="Fetch data" id="fetch-data" />
<div id="fetched-data-content"></div>
<?php
}
add_action("admin_init", "display_ajax_button");
Finally, we create the PHP script itself. I've just copied your code and saved it in the same directory as defined in the jQuery.ajax() URL parameter:
<?php
global $wpdb;
$rows = $wpdb->get_results("SELECT postid from `wp_school_post`");
echo "<table class='wp-list-table widefat fixed'>";
echo "<tr><th>ID</th><tr>";
foreach ($rows as $row ){
echo "<tr>";
echo "<td>$row->postid</td>";
echo "</tr>";}
echo "</table>";
?>
That should be the simpliest approach. Open the admin page and give it a try. Let me know if it worked or not.
The goal for my script is showing list of results from page1.php to page-listes.php
I incluse all method to my ajax call the sucess method was fired but page list not displayed
The ajax call code is :
$.ajax({
type: "POST",
url: "page-listes.php",
data: "name="+name+"&type="+type+"®ion="+region+"&aliment="+aliment+"&periode="+periode,
dataType: 'html'
}) .done(function() {
alert( "success" );
})
fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
And the php result file is :
<?php
try {
$bdd = new PDO('mysql:charset=utf8;host=localhost;dbname=reps-bd', 'tchiko', 'tchiko');
} catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (isset($_POST['name'])) {
$name = $_POST['name'];
$type = $_POST['type'];
$region = $_POST['region'];
$aliment = $_POST['aliment'];
$periode = $_POST['periode'];
// recuperer la liste
$repListe = $bdd->query('SELECT re.libelle libeller, t.libelle libellet, r.nom nom, r.nb_personne nb, r.image image, r.date date
FROM course r
INNER JOIN region re ON r.id_region=re.id_pays
INNER JOIN type t ON t.id_type=t.id_type
WHERE r.nom LIKE "%'.$name.'%"')
or die(print_r($bdd->errorInfo()));
?>
// some html code
<?php
while ($cours= $repListe->fetch()){
$fch_image = 'images/temp/'.$cours['image'].'.jpg';
?>
<div class="offer_list clearfix">
<div class="offer_item clearfix">
<div class="offer_image"><img src="<?php echo $fch_image;?>" alt=""></div>
<div class="offer_aside">
<h2><?php echo strtoupper($cours['nom']);?></h2>
<div class="offer_descr">
<p>...............</p>
</div>
<div class="offer_data">
<div class="offer_price"><?php echo $cours['diff'];?></div>
<span class="offer_miliage"><?php echo $cours['libellet'];?></span>
<span class="offer_regist"><?php echo $cours['date'];?></span>
</div>
</div>
</div>
</div>
<?php
}
$repListe->closeCursor();
}
?>
// some html code
I think the php file was correct,but nothing happen when i call it
The problem is that your code doesn't have any mechanism to actually append the response to your page. For instance, if you had a <p> with an id of myParagraph and want to append the response there, then your done callback should look like this:
.done(function(response){
$('#myParagraph').html(response);
});
Developer tools in your browser is your friend :-) Right click -> Inspect element (Chrome/Firefox), switch to console tab and you will see what is wrong. You forgot dot before fail() method :-)