I have a JQuery on click that sends a php query to MySql and then I want to send the data back 1 by 1 on JQuery.
But I only know how to send back results from php to JQuery as a whole.
my current JQuery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
alert(data);
}
});
});
});
my current php:
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['UserID'];;
echo $row['EmailAddr'];
}
?>
the outputs are both UserID and EmailAddr, I don't know how to just display either the UserID or EmailAddr out only
I tried alert(data[0]), but it only displayed one letter of the result.. Any ideas on how to do this?
UPDATE: After sean's help i have the current updated code
Jquery:
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
PHP
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
In your php, save the results to an array -
<?php
include 'dbAuthen.php';
$array = array(); // create a blank array
$sql = "SELECT * FROM users WHERE Name = 'james'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
// add each result to the array
$array[] = array('UserID'=> $row['UserID'], 'EmailAddr'=> $row['EmailAddr']);
}
echo json_encode($array); // json_encode() the array
?>
Then in your js/ajax you can loop through each value
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
// loop through each returned value
$.each(data, function(){
//alert each result, this is just an example as alert() for each result is not a great idea
alert("UserID:"+ this.UserID + " EmailAddr:" + this.EmailAddr);
});
}
});
});
});
jquery
$(function() {
$(".img_thumb_holder").on("click", function() {
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/retrieveAuthorDetails.php",
success: function(data) {
$.each(data, function() {
var userid = data.userid;
var useremail = data.email;
// i think there something wrong with this as it will keep repeating storing the userid and email for each data.. can someone verify?
});
}
});
});
});
php
<?php
include 'dbAuthen.php';
$sql = "SELECT * FROM users WHERE Name = 'honwenhonwen'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$arr = array(
"userid" => "HonWen",
"email" => "honwen#hotmail.com"
);
}
echo json_encode($arr);
?>
Related
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 am trying to refresh my a page if there is a change in orderStatus from database using Ajax and PHP. I set the current orderStatus as predefined data and then use Ajax to get the current orderStatus from database and finally compare if they are not the same. I want to refresh the page if they are not the same.
PHP (autorefresh.php)
<?php
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
Javascript
<script type="text/javascript" >
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$.document(ready(function(){
setInterval(function(){
$.ajax({
type:"POST",
url:"autorefresh.php", //put relative url here, script which will return php
data:{orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
success:function(response){
var data = response; // response data from your php script
if(predefined_val !== data){
window.location.href=window.location.href;
}
}
});
},5000);// function will run every 5 seconds
}));
The below code should work, Need to mention dataType:"json" else use JSON.stringify(data) to parse response
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct
I have a small script that runs a php file in the background and gets a variable every 3 seconds and put it in a div
script in document with div
<script>
$(document).ready(function() {
setInterval(function () {
$('#statmoney').load('safe.php');
}, 3000);
});
</script>
PHP FILE (safe.php)
$sql = "SELECT * FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$money = htmlspecialchars($row->money);
echo $money;
If i need to add another variable i would need to make a new document is there a easy way to go about it?
UPDATE
menu.php
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['money', 'ore', 'energy']; // array of needed fields
$.ajax({
type: "POST",
url: "menusafe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
console.log(response)
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
<div class="menustats"><img src="graphics/logos/moneylogo.png" class="menustatimage"><div class="menustattext" id='money'></div></div>
<div class="menustats"><img src="graphics/logos/energylogo.png" class="menustatimage"><div class="menustattext" id="energy"></div></div>
<div class="menustats"><img src="graphics/logos/orelogo.png" class="menustatimage"><div class="menustattext" id='ore'></div></div>
PHP(menusafe.php)
<?php
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
?>
Let's imagine that we want to retrieve three fields from users table : firstname, age and money. In such case it would be better to use $.post or $.ajax method:
js part:
<script>
$(document).ready(function() {
setInterval(function () {
var fields = ['firstname', 'age', 'money']; // array of needed fields
$.ajax({
type: "POST",
url: "safe.php",
data: {'fields': fields},
dataType: 'json',
success: function(response) {
// assuming that we already have divs for respective fields
fields.forEach(function(v){
$("#" + v).html(response[v]);
});
}
});
}, 3000);
});
</script>
php part: (safe.php)
if ( isset($_POST['fields']) && !empty($_POST['fields']) && is_array($_POST['fields']) ){
$fields = $_POST['fields'];
$fields = (count($fields) > 1)? implode(',', $fields) : $fields;
$sql = "SELECT $fields FROM users WHERE id='".$_SESSION['user_id']."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$result = [];
foreach($fields as $field){
$result[$field] = $row->{$field};
}
echo json_encode($result);
}
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