I am trying to update an included PHP file and get the refreshed results and variables from that file. The file getmssg.php is included in the foreach loop because I need in that file a row value. The variable $ergebnis1 I get from the file getmssg.php.
How can I call/refresh the query values of the included PHP file without reloading the page?
<?php
include("chatmain.php");
?>
<?php foreach ($result2 as $key => $row): ?>
<?php include("getmssg.php"); ?>
<li data-icon="false" name="listi5" class="listitem5">
<a type="button" class="ui-btn" id=5">
<?php if ($ergebnis1 > 0) {
echo '<span class="ui-li-count">'.$ergebnis1.'</span>';
} ?>
</a>
</li>
<?php endforeach; ?>
What I have now:
function getmsg() {
$.ajax({
url: 'getmssg.php',
type: 'post',
success: function(output) {
//alert(output);
}
});
}
var timer;
function docount() {
timer = setInterval(function(){
getmsg();
}, 3000);
}
docount();
Try to put the php forEach inside a php function and call that function in the success callback of the ajax .It will update the contents without pageload
Related
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);
I need to return the data-id from an ul on click, the data-id needs to go to a .php file and I want to use javascript(jquery ofc) I'm really new with java-script so I have no experience please someone help.
Here is my ul:
<ul id="zones">
<?php foreach ($data as $id => $name): ?>
<li data-id="<?= $this->e($id) ?>"> <?= $this->e($name) ?> </li>
<?php endforeach; ?>
</ul>
the name of my html file is dashboard_zones.html and the php file I want to acess the data-id is dashboard.php
Here it is a generi Ajax call, with a $.each() loop like:
var ids = [];
$('#zones li').each(function(){
let current_id = $(this).data('id');
// you can eventually test for undefined id
if(typeof current_id === "undefined"){
return; //acts like "continue;"
}
ids.push(current_id);
});
$.ajax({
url: your_url,
type: 'POST',
data: {your_ids: ids},
dataType: 'json',
success: function (theResponse ) {
...
}
});
I didn't tested it, but I assume you can start from this code to do what you need
I want to send id of element to php and create session for this.
This is piece from php file:
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['p_id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php
}
?>
And in this file javascript code:
$(document).on('click', '.open_item', function(event){
var data_item = this.getAttribute("data-id");
$.ajax({
url: 'get_id.php',
type: 'POST',
data-type: 'json',
data: { id: data_item },
contentType: 'application/x-www-form-urlencoded',
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
This is get_id.php:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
?>
I have tried also without content types and without json. "var data_item" prints id correct, but php doesn't create session and in console also clear(nothing).
The reason that you are not getting data in session is, you are not assigning proper value to session. Also it should be json_decode not json_encode.
replace
$_SESSION['item_id'] = json_encode($_POST);
with
if (!empty($_POST['id'])) {
$_SESSION['item_id'] = json_decode($_POST['id']); // use json_decode
}
It seems to me that you are making some small mistake in your code like you are echoing $row['p_id'] while your query should return id instead p_id also you are making mistake in ajax you are sending data-type JavaScript assuming your code is subtracting so try to use this code i code below.
// modify your php code
<?php
$sql = "SELECT id FROM products";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr class="table-manufacture-tr">
<td class="table-manufacture-td-statys">
<div class="warehouse-window-content-dropdown-plus2 plus">
<a class="open_item" data-id=<?php echo "\"".$row['id']."\"";?>
style="text-decoration: none; color: #D3D3D3;">Click</a>
</div>
</td>
</tr>
<?php } ?>
// modify your jQuery
$(document).on('click', '.open_item', function(event){
var data_item = $(this).data("id");
$.ajax({
url: 'get_id.php',
type: 'POST',
dataType: 'json',
data: { id: data_item },
success: function(data){
console.log(data);
},
error: function(){
console.log("not working");
}
});
});
<?php
session_start();
header("Content-Type: application/json", true);
$_SESSION['item_id'] = json_encode($_POST["id"]);
echo json_encode(['data_id' => $_SESSION['item_id']]);
?>
You can use
$_SESSION['item_id'] = json_encode($_POST['id']);
instead of
$_SESSION['item_id'] = json_encode($_POST);
this will work fine.
I don't know what you are trying to do, but from your JS, it looks like that you are expecting that the PHP script --which you post some data to it-- to return a json with the data you have just posted in it. In that case, try this, change your get_id.php to be like:
<?php
session_start();
$_SESSION['item_id'] = json_encode($_POST);
header("Content-Type: application/json", true);
echo $_SESSION['item_id'];
?>
I'd troubleshoot this by making sure the click handler is actually going off. Put alert("clicked"); as the first thing in the in the click handler to make sure.
For the meantime, remove the contentType in the json call. Also remove the dataType (data-type) entirely. On the php side, replace the header() line so (as mentioned) the php is just:
session_start();
$_SESSION['item_id'] = $_POST["id"];
echo $_SESSION['item_id'];
Do not use json_encode/decode right now. From your code, it is not needed.
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.
I don't know how to make a script for sending multiple variables from external php to javascript (jQuery)
For exemple:
<?php
$test = "tets"; -->this, I want something this, no echo
$dock = "dock"; --
echo $test; -->no, I don't want echo in PHP script
echo $dock; -->no, I don't want echo in PHP script
?>
and JS
<script>
function(){
$.post("url", {Some_Thing: "Some_Thing"}, function (data) {
alert(data); --> no, I don't want echo in PHP script
alert($test); --> this, I want something this, no echo
alert($dock);
}
}
</script>
Use a data structure, e.g:
<?php
$data = array('test', 'dock');
echo json_encode($data);
Then in your JS
$.post('url', {...}, function (data) {
alert(data[0]);
}, 'json');
^^^^^^^^--- tell jquery you're expecting back some json
you can just output your data in JSON format and then load the data to JavaScript using ajax like so:
<?
$arrayWithData = array('data1' => 123, 'data2' => 555);
echo json_encode($arrayWithData);
then call load the data using ajax:
$.ajax({
'url' : 'php-data-script.php',
'method' : 'get',
'dataType' : 'json'
}).done(function(data) {
// do whatever you want with the data
console.log(data);
});