Ok so this is the problem I'm facing right now
Actually I've successfully accessed JSON inside php, but with one condition, there is no specific function defined, and right now, I need to access the JSON from specific PHP function
So this is my php looks like
<?php
if(isset($_GET['func']))
{
if($_GET['func'] == "add")
addVisitor();
}
elseif(!empty($_POST['func']))
{
if($_POST['func']=="retrieve"
getData()
}
function addvisitor()
{
$servername = "localhost";
$username = "root";
$password = "@123";
$dbname = "numberofvisit";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE visitor SET count = count +1 WHERE idvisitor = 1 ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function getData(){
$servername = "localhost";
$username = "root";
$password = "@123";
$dbname = "rating";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT avg FROM feedback WHERE idoveralRating=1";
$result = $conn->query($sql);
$pass=mysqli_fetch_assoc($result);
echo json_encode($pass["avg"]);
$conn->close();
}
?>
Ok, So Im trying to send request to server to run specific function, by send func=retrieve to addVisit.php and then after run the function,I catch the JSON that the server Echoed, but it seems like it doesn't work like I expected, here is the part that the code that the part doesn't work for me
var req = new XMLHttpRequest();
req.open("POST", "addVisit.php", true);
req.send("func=retrieve");
var jsonObject = JSON.parse(req.responseText);
So How to access JSON in specific function of PHP using ajax?
PHP is case-sensitiv with its funciton names. You try calling addVisitor()
...
if($_GET['func'] == "add")
add**V**isitor();
}
...
But the function name you've defined is:
function add**v**isitor()
This causes Problems
Which also is pretty helpful for debugging javascript is to use the developer toolkit, often default in your browser (eg Chrome or Opera has it by default) You can dump your javascript variable, calls, returns and debug them by extending your with something like this
console.log(variable_name_goes_here)
try this :- call this getData function on button click
function getData()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "addVisit.php", true);
xhttp.send();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.