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

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.

Related

How do I run a php function and display the contents on page using javascript/jquery?

I have a php script which gets all my movies from a specific category and echos the html output using foreach loop placed inside of a function.
Instead of displaying the entire library at once I'd like to display it one category at a time by clicking a button (without page refresh) for example:
User clicks "Action" button:
<li>Action</li>
Which activates Action();
function Action()
{
jQuery.ajax({
type: "POST",
url: 'index2.php',
dataType: 'json',
data: {functionname: 'Movies', arguments: ['Action']},
success: function (returnData) {
data = returnData;
document.getElementById("Action").innerHTML = returnData;
console.log(data);
}
});
}
Action Div:
<a id="Action"></a></div>
<h3><span>Action</span></h3></center>
<div id="detail[19]">
</div>
The PHP function is Movies($var) when passing "Action" into it, it runs fine. So what do I do in order to get "Movies(Action)" to print to "detail[19]"
The PHP function:
function Movies($category){
$movies = glob('./uploads/Videos/Movies/'.$category.'/*/*.{mp4,m4v}', GLOB_BRACE);
global $images,$temp,$emtyImg,$actual_link,$dir,$rmvd;
foreach ($images as $image) {
$lookup[pathinfo($image, PATHINFO_FILENAME)] = $image;
}
foreach ($subs as $sub) {
$lookup2[pathinfo($sub, PATHINFO_FILENAME)] = $sub;
}
echo '<div id="detail['.$rmvd.']">';
include($_SERVER['DOCUMENT_ROOT']."/scripts/amzn.php");
foreach ($movies as $movie) {
*Lot's of useless code that echos div's with videos in them* }
echo '</div>';
$rmvd++;
}
I know I'm missing what I need for the PHP side and likely messed up the jquery bit. I'm at a loss at how to continue successfully.
You need to return a json object in php so that javascript can read it. For example:
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

A href load database items onClick

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
}
}),
}
});

How using ajax can update mysql database from dropdown menu

As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>

PHP inside js ajax function diffuculties

I have button let's say like this:
<button id= $id onClick="popup($id)">button</button>
Now I am trying to use it with ajax function
<script>
function popup(id){
alert(" ");
document.write(" ");
}
</script>
All I want to do is to make this js function execute the php code.
I think puting it into alert of document.write would be good but this code looks like this below and i have big problems with quotations and everything. I have no idea honestly how to make it all work.
Could someone help me match it up please?
echo "<div id='element_to_pop_up'>
<a class='b-close'>zamknij</a>";
$messages = mysql_query('SELECT * FROM msg WHERE id = "'.$messageid.'" ');
$fetchmessage = mysql_fetch_assoc($messages);
echo $fetchmessage['message'];
echo "</div>";
PHP is processed on the server side. So you can not run PHP-code client side.
What I'd do is (here done in jQuery, you could do it with other frameworks as well) to set a data-id="" attribute on your button with the ID echoed from PHP. Then when you click the button, you call a PHP script via AJAX that does something. Like:
HTML:
<button class="clickme" data-id="<?=$row['id'];?>">button</button>
jQuery
$('.clickme').click(function(){
$.post( "test.php", { msgId: $(this).data('id') }).done(function( data ) {
alert("Data loaded: " + data);
});
});
You need something like this:
HTML
<button class="clickButton" data-id="<?php echo $id; ?>" id=""<?php echo $id; ?>">button</button>
jQuery
$(function() {
$('.clickButton').click(function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "ajax.php",
data: {id: id}
success: function(data) {
alert(data);
}
});
});
});
ajax.php
//Set up a mysqli connection here
echo "<div id='element_to_pop_up'><a class='b-close'>zamknij</a>";
$result = mysqli_query($link, "SELECT * FROM msg WHERE id = '" . mysqli_real_escape_string($link, $_POST["id"]) . "'");
$fetchmessage = mysqli_fetch_assoc($result);
echo $fetchmessage['message'];
echo "</div>";
Avoid to mysql injection
Use mysqli or PDO instead of mysql function since mysql functions are deprecated.
PHP runs on the server. JS runs in the browser. You will not run one from the other directly.
You can run PHP on the server that echoes a string that will be run as JS in the browser.
You can run JS that uses AJAX to call back to the server to run PHP on the server.
You cannot run PHP in the browser.
You cannot run browser JS on the server (for purposes of this discussion, ignoring all the ways you can).

Executing javascript in an an AJAX response - Codeigniter

I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>

Categories

Resources