I'm making a website with different products. When a product is clicked, AJAX call gets the product data from the database. After this, I want to go to a new page, where product-data will be displayed. But there is the problem, when the new page is loaded, the data won't be displayed, because the data were loaded at the previous page.
Javascript:
$('#products').on('click', 'li', function(){
document.location.href = "product.html";
var datapk = $(this).attr('data-pk');
console.log(datapk);
$.ajax({
type: 'POST',
url: 'connection.php',
data: {
'function': 'get_product_data',
'datapk': datapk
},
success: function(data) {
var productData = JSON.parse(data);
displayProductData(productData);
}
});
});
PHP:
function get_product_data(){
$datapk = mysql_real_escape_string($_POST['datapk']);
$query = "SELECT * FROM Products WHERE prod_id = '$datapk'";
$result = mysqli_query($GLOBALS['dbc'], $query) or die('Error querying database.');
$json = array();
if (mysqli_num_rows($result)){
while ($row = mysqli_fetch_row($result)){
$json[] = $row;
}
}
echo json_encode($json);
mysqli_close($db_name);
}
Data-pk is the unique ID in database.
As Rory said..
Either it's document.location.href = "product.html"; or $.ajax({ ... })
However, what's the difference between document.location.href = "product.html and <a href='product.html'>, you might ask yourself.
Related
I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.
How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.
I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});
I've read and tried many solutions, none are working. Here is my latest. As you can see all I'm trying to do is display an alert box on screen with the data retrieved from the MySQL using PHP.
My HTML looks like this:
...
<td $brbCols class=\"editCS1\" oncontextmenu=\"getLastLogin('$row[callsign]');return false;\" id=\"callsign:$row[recordID]\" style=\'text-transform:uppercase\'> $row[callsign] </td>
...
Right clicking on the above code runs this,
The getLastLogin javascript looks like this:
function getLastLogin() {
$('tr').on('contextmenu', 'td', function(e) { //Get td under tr and invoke on contextmenu
e.preventDefault(); //Prevent defaults'
var idparm = $(this).attr('id');
var arparm = idparm.split(":");
var id = arparm[1];
id = id.replace(/\s+/g, '');
var call = $(this).html();
call = call.replace(/\s+/g, '');
$.ajax({
type: "GET",
url: "getLastLogIn.php",
data: {call : call, id : id},
success: function(response) {
alert(response);
},
error: function() {
alert('Not OKay');
}
});
});
}
The PHP:
<?php
ini_set('display_errors',1);
error_reporting (E_ALL ^ E_NOTICE);
require_once "creddtls.php";
$call = $_POST['call'];
$id = $_POST['id'];
$sql2 = "SELECT recordID, id, Fname, Lname, grid, creds,
email, latitude, longitude, tactical, callsign, logdate, netID, activity
FROM NetLog
WHERE callsign = '$call'
ORDER BY netID DESC
LIMIT 1,1 " ;
$stmt2 = $db_found->prepare($sql2);
$stmt2->execute();
$result = $stmt2->fetch();
$recordID = $result[0]; $email = $result[6];
$id = $result[1]; $latitude = $result[7];
$Fname = $result[2]; $longitude = $result[8];
$Lname = $result[3]; $creds = $result[5];
$tactical = $result[9]; $grid = $result[4];
$callsign = $result[10]; $netID = $result[12];
$logdate = $result[11]; $activity = $result[13];
$msg = "<b>Last Check-in::</b>
<br>$callsign, $Fname $Lname
<br><b>eMail::</b>$email
<br><b>Was on::</b> $logdate
<br><b>Net ID::</b> $netID, $activity
<br><br>
$recordID
";
echo "$msg";
?>
You are trying to access the data passed via ajax with the wrong superglobal.
You are looking at POST data, but your ajax call is using GET
Change $_POST to $_GET
Wrong or not the code writes to the lli DIV. So I added $("#lli").modal(); to the Javascript to open it in a modal dialog.
All is now well.
I'm trying to create upvote/downvote buttons on a list of articles that I get from a MySql database. The buttons work in the sense that you press on the button and it gets the id of the article. However I can't get the id from article page to the php voting page. When I press the button the database doesn't register the vote. What am I doing wrong?
<script type="text/javascript">
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
alert('you upvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
else
{
alert('you downvoted on '+ dataString);
$(this).fadeIn(200);
$.ajax({
type: "POST",
url: "weblectureupvote.php",
data: dataString,
cache: false,
});
}
return false;
});
});
</script>
This is the php file:
<?php
$pid = $_POST['id'];
try {
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result=mysql_query("SELECT * FROM database WHERE pid = '$pid' ") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// temp user array
$lecturelist = array();
$lecturelist["pid"] = $row["pid"];
$lecturelist["upvote"] = $row["upvote"];
$lecturelist["downvote"] = $row["downvote"];
$lecturelist["vote"] = $row["vote"];
}
$upvote= $row["upvote"];
$downvote = $row["downvote"];
$vote = $row["vote"];
$upvote = $upvote + 1;
$query = $db->prepare('UPDATE database SET upvote = :upvote WHERE pid = :pid');
$query->execute(array(
':upvote' => $upvote,
':pid' => $pid
));
$query = $db->prepare('UPDATE database SET vote=:vote WHERE pid = :pid');
$query->execute(array(
':vote' => $vote,
':pid' => $pid
));
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
data: {id: id}
this will get to your php file a "id" variable ( this is the first id ) and with some value ( from the second id )
now
$pid = $_POST['id'];
this should work, as you weren't sending "much" to the server