Reputation:
I have the following link;
www.example.com/profile.php?u=aaron
I will like to get the u=
using ajax to echo the details saved with the name aaron
in my database. But when ever I try to achieve this with my ajax code, I end up getting a blank page as my result.
MY AJAX CODE;
$(document).ready(function() {
$.ajax({
type: "GET",
url: "fetch.php",
data: "u=":usr,
success: function(d) {
$("#detail").html(d);
}
});
});
fetch.php;
<?php
// connect to db
include 'db.php';
if (isset($_GET['usr'])) {
$user_query = "SELECT details FROM users_det WHERE name = ?";
if ($stmt = mysqli_prepare($db_var, $user_query)) {
mysqli_stmt_bind_param($stmt, "s", $_GET['usr']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $details);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
// close statement
mysqli_stmt_close($stmt);
}
// echo user details
echo $details;
}
?>
MY HTML CODE;
<div id="detail"></div>
AND THE FOLLOWING PHP CODE IN MY HTML CODE;
<?php
$user = preg_replace('#[^a-zA-Z0-9_.]#i','',$_GET['u']);
?>
I will like to know why ajax is not getting the name from link.
Upvotes: 0
Views: 1732
Reputation: 6130
First get the full url with window.location.href, instantiate a url object, then get its params through searchParams in javascript.
SCRIPT:
var urlString = window.location.href; //www.example.com/profile.php?u=aaron
var url = new URL(urlString);
var usr = url.searchParams.get("u");
$(document).ready(function() {
$.ajax({
type: "GET",
url: "fetch.php",
data: "u="+usr,
success: function(d) {
$("#detail").html(d);
}
});
});
PHP:
<?php
// connect to db
include 'db.php';
if (isset($_GET['u'])) {
$user_query = "SELECT details FROM users_det WHERE name = ?";
if ($stmt = mysqli_prepare($db_var, $user_query)) {
mysqli_stmt_bind_param($stmt, "s", $_GET['u']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $details);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
// close statement
mysqli_stmt_close($stmt);
}
// echo user details
echo $details;
}
?>
Upvotes: 0
Reputation: 4066
There is multiple mistakes in your code
first you should used data: {u: usr},
instead of data: "u=":usr,
$(document).ready(function() {
$.ajax({
type: "GET",
url: "fetch.php",
data: {u: usr},
success: function(d) {
$("#detail").html(d);
}
});
});
second in fetch.php
file you should get parameter $_GET['u']
instead of $_GET['usr']
<?php
// connect to db
include 'db.php';
if (isset($_GET['u'])) {
$user_query = "SELECT details FROM users_det WHERE name = ?";
if ($stmt = mysqli_prepare($db_var, $user_query)) {
mysqli_stmt_bind_param($stmt, "s", $_GET['u']); //also change `usr` in this line
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $details);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
// close statement
mysqli_stmt_close($stmt);
}
// echo user details
echo $details;
}
?>
for debugging you can used console.log(d)
in ajax success response
Upvotes: 1