A href load database items onClick - javascript

i'm developing a simple Content Management System that allow users to create categories and subcategories. This is the code.
$categories = mysql_query("SELECT * FROM categories");
while($row = mysql_fetch_array($categories)) {
$text = $row['text'];
$id = $row['id'];
echo "<li><a href='?category=$id'>$text</a></li>";
}
Now, all works fine as expected but i would like that when a user click on <li> items the system loads subcategories related to the selected category. In PHP i can't do this so i need to use JavaScript but i don't understand why. I wrote this code.
<script type="text/javascript">
function loadSubCategories() {
<?php
if(isset($_REQUEST['category'])) {
echo "Hello";
}
?>
}
</script>
and obviously
echo "<li><a href='?category=$id' onClick='javascript:loadSubCategories()'>$text</a></li>";
This not works because nothing appear when i click on a link. How can i solve?

Pass id attribute in function call like this:
echo "<li><a id="$id" onClick='javascript:loadSubCategories(this.id)'>$text</a></li>";
Then you can use jQuery/Ajax, try something like this:
$( document ).ready(function() {
function loadSubCategories(id){
$.ajax({
url : Class/Method-Name,
type : 'POST',
data : form_data,
success : function(msg){
// Action
}
}),
}
});

Related

How to put PHP script in JS?

I have a page that allow users to access it. This page have certain things that not allow user to see that particular thing, For my case, user is unable to edit edit() or view this function, so I want to hide it by putting below code in JS because I am using function on this link.
I already enabled Session in PHP page like this <?php session_start(); ?>
And I try this putting this PHP in JS inside Datatables function. The dataTable function is working fine. Just the PHP is not working.
{ data : "project_id",
render: function(data) {
return "<span onclick='view()'></span> "+ // This is allow to user and admin level
"<?php
if ($_SESSION['user_privilege'] == 'Admin') { ?>
<span onclick='edit()'</span>
<?php } ?>"; // This is allow for admin level only
}
}
Check the following
<?php
if(isset($_SESSION["user_user_privilege"])){
echo "<script>
let button = '<span onclick='edit()'></span>';
</script>";
}else{
echo "<script>
let button = '';
</script>";
}
?>
Now check the button is empty or not.
{ data : "project_id",
render: function(data) {
return "<span onclick='view()'></span> "+ ((button!="") ? button : "");
}
}

Trying to dynamically add, and name, div to page using javascript/php

I am new to php and javascript. I want to dynamically add a div to a page with php. In the end what I want is to be able to call a php function that adds a div. I want to call the function multiple times for a single page - so I want to add multiple divs via multiple function calls.
That doesn't seem to be difficult, but... I want each of the dynamically added divs to have the same class name, but a unique id and, for various reasons, I want the id to be based on the number of divs of that class already on the page (e.g. the first div added might have id = 0. the second id = 1, third id = 2 etc.).
I have looked a stackoverflow but haven't found any clues. I'd really appreciate any help.
I have tried the following, but it doesn't work (this is a very simplified version):
function getCount() {
?><script>
$(document).ready(function(){
var elems = $('body').find('.mydiv');
$.ajax({
type: 'POST',
url: '',
data: {count: elems.length},
cache: false,
success: function(response) {
console.log(response);
}
});
});
</script><?
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="../jquery-3.2.1.js"></script>
</head>
<body>';
$count = -1;
getCount();
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
if (!empty($key) && !empty($value)) {
echo 'key = '.$key.' value = '.$value;
if ($key == 'count') {
$count = $value;
}
}
}
}
if ($count > -1)
echo "<div class = 'mydiv' id = 'mydiv".$count."'></div>";
echo "</body></html>";
you dont want to mix js and php here, you can achieve this using php alone, here is the code sample
<?php
echo 'your headers and layout tags go here';
function addDiv($count){
echo "<div class = 'mydiv' id = 'mydiv".$count."'>current div id is ".$count."</div>";
}
$count=0;
addDiv($count++);
addDiv($count++);
addDiv($count++);
?>

Passing a var in the same php page without refresh

I have a problem with my website. I have a list of products that i get from database. These products have Image and Name camps.
Now i want that, when i click to someone of this products, into my webpage appears a new box where there is the description of the product, the price etc..
This is the code for the products list
<?php
include 'php/dbmanager.php';
$result = DBManager::getInstance()->getProducts();
if($result->num_rows > 0){
$i = 0;
while($row = $result->fetch_assoc()){
echo "<div class=\"wrap effect8 open\" onclick>";
echo "<h1>".$row['product_name']."</h1>";
echo "<div class=\"left\">";
echo "<img src=".$row['product_image']." width=150 height=150 >";
echo "</div>";
echo "<div class=\"right\">";
echo $row['product_description'];
echo "<div class=\"prodSelection\">";
echo '<a href="catalogo.php?prodID=';
echo $row[product_id];
echo '"';
echo 'class="button">Acquista</a>';
echo '<label>';
echo '<select class="selectBoxCat">';
echo '<option selected> 1 </option>';
echo '<option>2</option>';
echo '<option>3</option>';
echo '</select>';
echo '</label>';
echo '</div>';
echo '</div>';
echo '</div>';
}
}
?>
How can i get the ProductID ($row[product_id]) from a single product that i click and use it for a new query for select the database's rows of this single product (and use this query for make another php like that)?
I dont want to refresh the page.
Could i use the pushstate method (HTML5)?
If you want to get additional data when the user clicks, you will need to make an ajax request to update your DOM without refreshing the page.
On the PHP side, you'll want to create a script that returns a json-encoded value.
On the JS side, you'll want to create a click event listener. Inside the listener, you'll want to make an ajax request to your PHP script.
When your data is successfully returned from your ajax call, you'll want to manipulate your DOM to display your product's details.
Example of a click listener:
$("#button").on("click", function(){
// make your ajax request here
});
Example of an ajax call:
$.ajax({
method: "POST",
url: "scriptThatReturnsProductDetails.php",
data:
{
productID: $("#myProduct").attr('id')
}
})
.done(function( msg ) {
// Do some DOM manipulation
});

How to call AJAX in a WordPress plugin? [duplicate]

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.

Insert/Edit records using php and javascript/ajax

I'm trying to make user interface to edit/insert records and i'm having some troubles with my code.
Lists the records :
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$html.="<tr>
<td style>{$row['name']}<input type='hidden' id='id' value='$row[a_id]'></td>
<td>{$row['season']}</td>
<td><a href='edit1/new' id='edit'></a></td>
<tr style='height: 5px;'></tr>
</tr>..
Now the js that i`m having trubles with:
<script type='text/javascript'>
$('#edit').on( 'click', function () {
var x = document.getElementById('id').value;
$.ajax({
type: 'post',
url: 'insert_edit.php',
data: {
id: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>
inside the insert_edit.php
if(isset($_POST['id'])){
$html = Edit();
}else{
$html = Add();
}
For some reason the on click function doesnt seem to work and it doesnt posts datainsert_edit.php`
Any help will be apriciated thank you.
NOTE: I'm not sure even if the posts works I'm using the Java Script the right way since my while loop prints it foreach ID and my guess is even it if it posts the data it will aways posts the value of the first record.
Try this- on click function replace with this-
$(document).on("click", "#edit", function(){
// ..
})
I managed to fix it. Here is how I did it:
I made an array $urlparts wich is my permalinks.
The button code goes like this
..a href='/account/competitions/edit1/update/$row[a_id]'>Edit..
And some php
if (isset($urlparts[4]) && is_numeric($urlparts[4])){
require_once ("insert_edit.php");
$html = Edit();
}
and inside the Edit();
just snach the id with
$id = $urlparts[4];
Thank you for the feeedback guys. Made me realize that I`m looking at the issue from the wrong angle:)

Categories

Resources