I am getting user data by passing the id in url and using the select statement where it matches the id in url and display result
But I want this by using ajax. Please help me
<div id="show_data">
<?php
$id=$_GET['id'];
$category=$_GET['category'];
if ($category==Hosted) {
$result = $wpdb->get_results ("SELECT * FROM wp_user_host WHERE user_id=$id");
foreach ( $result as $print ){
?>
<table>
<tr>
<td>Name: <?php echo $print->drive_name;?</td>
<td>Date: <?php echo $print->drive_date;?</td>
</tr>
</table>
<?php
}
}
?>
</div>
<a href="page.php?id=2&category=Hosted:>VIEW DATA</a>
lets say i have an index file like follow
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<button id="testDom">click to load dom</button>
<p id="domOutput"></p>
<script>
document.getElementById("testDom").addEventListener('click', function(){
loadAjax();
});
function loadAjax(){
var xmlHttp = new XMLHttpRequest();
var requestUrl = 'test.php';
xmlHttp.onreadystatechange = function(){
if( this.readyState == 4 && ( this.status > 200 || this.status < 300 ) ){
console.log("ok");
document.getElementById("domOutput").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', requestUrl);
xmlHttp.send();
}
</script>
</body>
lets say if u click the button ajax call made to the php file called test.php
<?php
echo "php file loaded";
ouput will printed in the index.html on p tag.
Related
I have a 'like' button that I have implemented with PHP/MySqL, AJAX and Jquery, which increments likes by +1 each time. It all seems to work fine and updates the database with the new value; however, the response that is returned from the AJAX call is returning all of the html in my .php file that comes before the post handler in my index.php. Other than moving the handler all the way to the top of the page, is there a way of fixing this?
Code below:
index.php
<?php
include './includes/header.php';
?>
<?php
include './includes/title_box.php';
?>
<?php
include './includes/categories_box.php';
?>
<?php
include './includes/roadmap_box.php';
?>
<?php
if(isset($_POST['liked'])) {
$postid = $_POST['postid'];
$query = "SELECT * FROM posts WHERE post_id=$postid";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$n = $row['post_upvotes'];
$query = "UPDATE posts SET post_upvotes=$n+1 WHERE post_id=$postid";
mysqli_query($connection, $query);
echo $n + 1;
exit();
}
?>
<button class="upvote-button" value=<?php echo $id ?>><?php echo $upvotes ?></button>
script.js
$(document).ready(function(){
$(".upvote-button").click(function(){
var postID = $(this).val();
$post = $(this);
$.ajax({
url: './index.php',
type: 'post',
data: {
'liked': 1,
'postid': postID
},
success: function(response){
$post.html(response);
}
});
});
});
console.log(response)
element.style {
}
user agent stylesheet
body {
display: block;
margin: 8px;
}
script.js:14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<title>Product Feedback App</title>
</head>
<body><div class="title-box">
<h1>Frontend Mentor</h1>
<p>Feedback Board</p>
</div><div class="categories-box">
<ul>
<li>All</li>
<li>UI</li>
<li>UX</li>
<li>Enhancement</li>
<li>Bug</li>
<li>Feature</li>
</ul>
</div>
<div class="roadmap-box">
<h2>Roadmap</h2>
View Roadmap
<ul>
<li>Planned - 2</li>
<li>In-Progress - 3</li>
<li>Live - 1</li>
</ul>
</div>
134
Move your if(isset($_POST['liked'])) and all associated code to a separate file and call that file in your Ajax query url.
You will probably need to include the file that connects to your database in the new file as well, but without seeing the contents of your included files it's hard to give specific advice.
I would like to have on my HTML page a simple button allowing me if right clicked one, click activate every time my PHP script.
I tried with this code, without any positive result for the moment:
//My html code
<!DOCTYPE html>
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main>
<button onclick="doTheFunction();">Run the script</button>
<script>
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","script.php",true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
}
</script>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
A part of my php code :
echo "$result";
Your code is doing nothing with the result of Ajax. I suggest starting here as a reference. The most important thing you're missing is:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
Where "demo" is the Id of the element you want to load the Ajax result into. Otherwise nothing will happen with that result.
EDIT
Let's clean up your code so scripts and html are separate:
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
//Set this before sending!!
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
}
//No reason to post
xmlhttp.open("GET","theme/generator/gensent.php",true);
xmlhttp.send();
}
<head>
<title><?php echo $pageTitle; ?></title>
<meta charset="UTF-16" />
<link rel="stylesheet" type="text/css" media="all" href="css.css">
<style></style>
</head>
<body>
<main id="demo">
<button onclick="doTheFunction();">Run the script</button>
</main>
<footer>
<?php echo $footer; ?>
</footer>
</body>
I would put the <script> tag at the end of your html, after closing the body, or include it in the header from another file. Note- I use GET since no sensitive info is transferred, the script should load after the HTML- hence put at the end, and finally you need a tag with the Id for this to actually work.
I'm trying to build a website for school project. I want the schoolResponse() function to happen after clicking the Submit button. If I remove the jQuery function it works but then it shows a default value when I load the page.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>NHG</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="css/normalize.css"/>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
<link type="text/css" rel="stylesheet" href="css/resposive.css"/>
</head>
<body>
<header>
<div id="main-head">
<h2 id="main-heading">sKoolBook</h2>
</div>
</header>
<section>
<div id="container">
<div id="wrapper">
<form method="POST">
<select name="school">
<option value="none" name="none">Please Select a School...</option>
<option value="NHG">New Horizon Gurukul</option>
</select>
<input type="submit" class="button"/>
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
?>
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
</form>
</div>
</div>
</section>
<footer>
</footer>
</body>
</html>
You should use jQuery/AJAX to do this.
<script>
$('.button').click(
$.ajax({
url: 'yoururl.php',
data: $("form").serialize(), //Better to put an ID to the form or something
success: function(data){
//DO something with your data
}
})
);
</script>
There are other functions you should check to properly use ajax requests.
In yoururl.php you should do something like
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
You can't achieve it like this. Here is one solution:
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
if($_POST['school']) schoolResponse();
?>
It would be better if you replace error_reporting(0); with error_reporting(E_ALL); for example, because otherwise php errors will be disabled.
And remove this part:
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
But it is very very basic example.
The Idea
User will select examination date from dropdown list which is populated with data from the database.
After selecting the date, the system will display the list of examiners based on the selected date.
The user can now encode grades per student.
After encoding the grade, the user will click the 'save' button which the system will save to the database. (Multiple update)
This is the code where the user selects the exam date.
<?php
include '../configuration.php';
$queryselect = mysql_query("SELECT examdateno, examdate from tbl_examdate ORDER BY examdate DESC");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SPORT Qualifying Exam System</title>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/component.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "encodeinterviewajax.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<header>
<img src="../images/qes_logob.png" alt="logo">
<button class="hamburger">☰</button>
<button class="cross">˟</button>
</header>
<div class="menu">
<ul>
<a href="encodeinterview.php">
<li>Encode Grades</li>
</a>
<a href="viewinterview.php">
<li>View Grades</li>
</a>
<a href="../index.php">
<li>Logout</li>
</a>
</ul>
</div>
<script>
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
</script>
<div id="content">
<form>
<h1>Exam Dates</>
<select name="examdate" id="examDate" onchange="showUser(this.value)">
<option>Select Exam Date</option>
<?php
while ($row = mysql_fetch_array($queryselect)) {
echo "<option value={$row['examdateno']}>{$row['examdate']}</option>\n";
}
?>
</select>
</form>
</div>
<div id="txtHint">Examinees will be listed here</div>
</body>
</html>
This is where the displaying and the update should happen.
<?php
include '../configuration.php';
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/component.css" />
<link rel="stylesheet" type="text/css" href="../css/style.css">
<link rel="stylesheet" type="text/css" href="../css/grid.css">
</head>
<body>
<?php
$q = intval($_GET['q']);
$sql = mysql_query("select s.sno, s.fname, s.lname, s.examdate, s.interviewgrade, s.gwa from student s inner join tbl_examdate e on s.examdate=e.examdate where e.examdateno=$q");
?>
<div class="as_wrapper">
<div class="as_grid_container">
<div class="as_gridder" id="as_gridder"></div> <!-- GRID LOADER -->
<form method="post" action="">
<table class="as_gridder_table">
<tr class="grid_header">
<td><div class="grid_heading">Student No.</div></td>
<td><div class="grid_heading">First Name</div></td>
<td><div class="grid_heading">Last Name</div></td>
<td><div class="grid_heading">Exam Date</div></td>
<td><div class="grid_heading">Interview Grade</div></td>
<td><div class="grid_heading">GWA</div></td>
</tr>
<?php
while ($row = mysql_fetch_array($sql)) {
?>
<tr class="<?php
$i+=1;
if ($i % 2 == 0) {
echo 'even';
} else {
echo 'odd';
}
?>">
<td><?php $sno[]=$row['sno'];echo $row['sno']; ?></td>
<td><?php $fname[]=$row['fname']; echo $row['fname']; ?></td>
<td><?php $lname[]=$row['lname'];echo $row['lname']; ?></td>
<td><?php echo $row['examdate']; ?></td>
<td><input type="text" size="3" maxlength="3" name="interview[]"></td>
<td><input type="text" size="3" maxlength="3" name="gwa[]"></td>
</tr>
<?php
}
?>
<tr>
<td colspan="6"><button id="btnUpdate">Save</button>
</tr>
</table>
</form>
<?php
if (isset($_POST['btnUpdate'])){
for($i=0;$i<sizeof($sno);$i++){
$interview = $_POST['interview'][$i];
$gwa = $_POST['gwa'][$i];
$sql1= mysql_query("UPDATE student SET gwa='$gwa', interviewgrade='$interview' where fname='$fname[$i]' AND lname='$lname[$i]' ");
header('Location: encodeinterview.php');
}
}
?>
</div>
</div>
</body>
As I mentioned in my comment I'm not sure what exactly is not working for you but I can help you with a couple of things in what I'm guessing to be your homework project.
First, always wrap all jQuery actions that affect DOM elements or add EventListeners to DOM elements in a document.ready function. This function is triggered when all the HTML of the page has been loaded to the DOM. Adding an event listener or trying to ".hide()" and element before it is loaded to the DOM will fail. There is the long way of calling the document.ready function:
$(document).ready(function(){
.... Code to manipulate the DOM goes here ...
});
and the shorthand function call that does exactly the same thing:
$(function(){
.... Code to manipulate the DOM goes here ...
});
If you need to wait until all the additional resources (e.g. images) are loaded you can use:
$(window).load(function(){
.... Your code goes here ....
});
This function is triggered when all resources are loaded. So if you're looking to get the position of an element or size of an element that contains images it's best to wait until the images are loaded. otherwise the position or size may well change once the images are loaded.
So your jQuery block needs to wrapped like this:
<script>
$(function(){
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
});
</script>
And for goodness sake if your using jQuery NEVER type 'document.getElementById'. The jQuery equivalent is $('#id'). Note the '#' means ID where the '.' means CLASS. It's much shorter and it creates the element as a jQuery object which allows you to use all of jQuery's wonderful functions on it.
If you're using jQuery anyway. You should use it for AJAX. It's much easier. Here's your same showUser function done with jQuery including error handling for the ajax call:
function showUser(str) {
if (str == "") {
$("#txtHint").html("");
return;
} else {
$.ajax({
url: "encodeinterviewajax.php?q=" + str,
type: 'GET',
success: function(data){
$('#txtHint').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("Status = " + textStatus);
console.log("Error = " + errorThrown);
}
});
}
I have a page showing a picture of a product. Underneath that I have tabs for the Description, Contact Details and Comments. When you click on the Comments tab a comments page is loaded into the div="info" using Jquery.
products.php:
<html>
<head></head>
<body>
<img src="image.jpg">
<hr>
<a id="det"><h3>Details</h3></a>  <a id="contact"><h3>Contact</h3></a>
 <a id="comments"><h3>Comments</h3></a>
<div id="info"></div>
</body>
<html>
Jquery:
<script>
$(document).ready(function(){
$("#comments").click(function(){
$("#info").load("comments.php");
});
});
</script>
The comments.php page below uses pagination for the comments.
When I click on the pagination links the page refreshes the comments.php?page=* removing it from the div="info".How do I keep the comments in the div id="info" when I use pagination?
comments.php:
<?php
// 1)Set current page
$current_page = ((isset($_GET['page']) && $_GET['page'] > 0) ?
(int)$_GET['page'] : 1);
require 'connect.php';
// 2)Get total amount of rows
$sql = "SELECT * FROM comments";
$result=mysqli_query($conn,$sql);
$totalrows = mysqli_num_rows($result);
// Offset - calculation to skip to the data you want to display
$results_per_page = 10;
$offset = ($current_page-1)*$results_per_page;
?>
/*------- Comments Form -----*/
/*------- Comments from Database ---- */
<?php
//Here is the code for displaying link and page number.
$number_page = $totalrows/$results_per_page;
for ( $page = 1; $page <= $number_page; $page ++ )
{
echo "<a href='comments.php?page={$page}'>{$page}</a>";
}
?>
You know... you could end this problem doing a js making every link inside the #info element update only inside it. Not sure if is that what you need.
$('#info').on('click', 'a', function (e){
e.preventDefault();
$("#info").load($(this).attr('href'));
});
You need to attach a click event to the links that are loaded in the ajax partial.
The simplest way to do that is to add a class property to any of the links you want to load via ajax, then attach your event to that class.
Example:
<?php
// example just increments the page param
if(strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH', FILTER_SANITIZE_STRING)) == 'xmlhttprequest') {
die('<a class="ajaxlink" href="?page='.($_GET['page']+1).'">Goto page '.($_GET['page']+1).'</a>');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h3><a class="ajaxlink" href="index.php">Contact</a></h3>
<div id="info"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).on("click", ".ajaxlink", function(event) {
event.preventDefault();
if ($(this).prop('href').length > 0) {
$("#info").load($(this).prop('href'));
}
return false;
});
</script>
</body>
</html>