what my goal is to use AJAX to call my php function:
function getAns($mysqli)
{
$stmt = $mysqli->prepare('
SELECT `user_id`,`user_name`, `user_ans`
FROM `tbl_user`
WHERE `user_ans` != ""');
$stmt->execute();
$stmt->bind_result($id, $user, $ans);
$O ="";
$x = 1;
$O.="<table><form action=\"#\" method=\"POST\">";
while($stmt->fetch())
{
if($x%2)
{
$O.= "<tr>
<td>".$user."</td><td>".$ans."</td><td><input id=".$id." type=\"submit\" name=\"pts\" href=\"#\" value=\"+\"></td>
</tr>";
$x++;
}
else
{
$O.= "<tr>
<td>".$user."</td><td>".$ans."</td><td><input id=".$id." type=\"submit\" name=\"pts\" href=\"#\" value=\"+\"></td>
</tr>";
$x++;
}
}
$O.= "</form></table>";
// close statement
$stmt->close();
return $O;
}
at a set time interval,say every 5 seconds, using AJAX/jQuery. I am trying to have an answer section, which is in a div, auto grab things from my database and echo them onto the page.
My HTMLthat i was trying to have them put into looks like this:
<div id="ans" class="box3"><!--PHP Students answers -->
<form id="ans" action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<?php echo getAns($mysqli);?>
</form>
</div>
I understand a little bit how it works but I don't understand the code it takes to get there. I am new to JavaScript/jQuery/AJAX but I am trying to use more of it in my code, so if anyone could elaborate it would be much appreciated, thanks!
with this function you can run ajax after every 5 minutes.
You just need to pass user id value in ID variable, which will fetch all answer of that user after every 5 minutes.
And run your sql query in get_data.php file.
$(document).ready(function(){
var timer, delay = 300000; //5 minutes counted in milliseconds.
var ID = $( "td :submit" ).val();
var info = 'userID=' + ID ;
timer = setInterval(function(){
$.ajax({
url: "get_data.php",
type: "POST",
data: info,
success:function(data){
$("#ans").html(data);
}
});
}, delay);
});
You can use ajax to call a php file that includes your php code it will execute it in the server then it will returns the result back to you
$.ajax({
url:"your_php_file_path.php",
success: function(result){
//result is a variable that stores the value sent back from your php
// in your case $O
}
});
You can put this code in a js function, finally you will have to include Jquery library so you can use ajax
Related
I'm trying to refresh data on my web page according to the data stored in the database, so every 2 seconds I call with an ajax request a php file. The called php script is this:
session_start();
.....Connection to the db.......
$prova = pg_query($connect, "SELECT * FROM maxdistance");
$prova2 = "";
while ($row = pg_fetch_row($prova)) {
$prova2 = $prova2.$row[0].$row[1].$row[2];
}
$_SESSION['prova'] = $prova2;
And this is the code in javascript:
var intervalId = window.setInterval(function(){
newPositions();
}, 2000);
function newPositions(){
$(document).ready(function(){
$.ajax({
type: "POST",
url: "realTimePosition.php",
success: function(msg){
provaaa = <?php echo ($_SESSION[prova]); ?>;
}
})
});
The problem is that, when I refresh the page the code run and in the variable provaaa is stored the value 20 (the actual value in the db) but if I modify the value in the db, the value of the variable is the same, why is this happening?
you cant mix JS and PHP like this
problem part
provaaa = <?php echo ($_SESSION[prova]); ?>;
solution
your PHP script have to send back REPLY with "echo"
echo json_encode([ 'data' => $prova2]);
then y have to catch server response inside your "success" callback dunction where param is RESPONSE from server so
success: function(res){
provaaa = JSON.parse(res).data;
}
I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();
I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.
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).
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.