I am trying to pass a javascript variable into an SQL WHERE query and I keep getting null in return.
On-click of a button, the buttonClick function is ran:
<script>
var var1;
function buttonClick(elem){
var1 = elem.src //this gets the url from the element
var path = var1.slice(48); //this cuts the url to img/art/9/1.jpg
ajax = theAjax(path);
ajax.done(processData);
ajax.fail(function(){alert("Failure");});
}
function theAjax(path){
return $.ajax({
url: 'info.php',
type: 'POST',
data: {path: path},
});
}
function processData(response_in){
var response = JSON.parse(response_in);
console.log(response);
}
</script>
Here is the code stored in the info.php file:
<?php
$path = $_POST['path'];
$result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
$json = json_encode($result3);
echo $json
?>
As you can see, once I click the button, the buttonClick() function is ran and a variable stores the image path or src. That path variable is send to theAjax() function where it is passed to the info.php page. In the info.php page, the SQL WHERE query is ran and returned to the processData() function to be parsed and printed in the developer console. The value printed shows null.
Below is a picture of what I am trying to get from the database:
1.Check that path is correct or not? you can check inside jquery using console.log(path); or at PHP end by using print_r($_POST['path']);
2.Your Php code missed connection object as well as record fetching code.
<?php
if(isset($_POST['path'])){
$path = $_POST['path'];
$conn = mysqli_connect ('provide hostname here','provide username here','provide password here','provide dbname here') or die(mysqli_connect_error());
$result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'");
$result = []; //create an array
while($row = mysqli_fetch_assoc($result3)) {
$result[] = $row; //assign records to array
}
$json = json_encode($result); //encode response
echo $json; //send response to ajax
}
?>
Note:- this PHP query code is wide-open for SQL INJECTION. So try to use prepared statements of mysqli_* Or PDO.
mysqli_query() required 1st parameter as connection object.
$result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'"); // pass your connection object here
I think your issue is that you're trying to encode a database resource.
Try adjusting your PHP to look like the following:
<?php
$path = $_POST['path'];
$result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
$return_data = [];
while($row = mysqli_fetch_assoc($result3)) {
$return_data[] = $row;
}
$json = json_encode($return_data);
echo $json
?>
Related
I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";
i want to get the data from database through ajax but its gives me only one record not other but i want all the records from database i have search too much to understand the problem
but can't get that
that is database image
php code
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "search";
$tableName = "ajax01";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
html
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2></h2>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
// var id = data[0]; //get id
// var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+name); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
You only ever get one row.
$array = mysql_fetch_row($result);
You need to loop that line and keep going until you run out of rows (creating an array of row arrays as you go).
Then json_encode that final array.
THe best way to do this, use 3 different files;
php_page.php
script.js
php_handler.php
In the php_page.php you have have actually the HTML
In the script.js you make the request with ajax
In php_handler.php you give the response and there you can make the connection and take all the data from your database that you need!
php_page.php
<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul id="list">
<!-- In here comes the data! -->
</ul>
<button id="button">Get Data</button>
</body>
</html>
script.js
$(document).ready(function() {
$("#list").on("click", function() {
$.ajax({
url: "php_handler.php"
}).done(function(data){
$(this).empty().append("<li>"+ data +"</li>");
});
});
});
php_handler.php
<?php
$con = mysqli_connect($host, $user, $pass, $db);
$query = mysqli_query($con, "SELECT [FIELD_NAME] FROM [TABLE_NAME]");
foreach($query as $data)
{
echo '<li>' . $data . '</li>';
}
?>
The mysql_fetch_row takes only one record from result of query. You need to store each row of query result in an array, then finally convert the array to its JSON representation.
$records = [];
while( $row = mysql_fetch_row( $result ) ){
array_push( $records, $row );
}
echo json_encode( $records );
Substitute the mysql_fetch_row and json_encode lines of your code with this to achieve it.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)
Right now I have working a DB connection to mysql. The html -> PHP -> query -> data reception works. I show the relevant code:
From the html file matters:
d3.json("http://path/file.php", function(error, data) {
console.log (data);
});
file.php:
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "select * from `mytable`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What I want is to have only 1 .php file instead of 1 php file for every query. That means I need to send from the html a variable inputquery to the php file. I've tried several things such as changing:
`$myquery = "select * from `mytable`; into `$myquery = inputquery`;
And I think that the wrong point is the definition of the function that requests the data from the DB. What I tried (wrong, the following code does not work as expected):
var inputquery = "select * from `mytable`"
d3.json("http://serverhost/path/file.php", function(error, data) {
console.log (data);
});
Maybe this is not working because I am not telling the function I want as an input to the .php file the variable inputquery. I tried to put it inside the function, but got "data is not defined" errors, so I think it is not worth it to show the wrong code.
How can I input that var inputquery to the .php file? It could not be the way I planned it.
Thank you
You have to send the inputquery variable with the http request as POST data,
then in you php file you can do :
$myquery = $_POST['inputquery'];
You surely will find some documentation about sending post data with the request you're sending.
The simplest way is using get parameter in d3.json:
var yourparam = 'mytable';
d3.json("http://path/file.php?query=" + yourparam, function (error, json) {
...
});
You can retrieve the variable from the $_GET array.
Finally don't put mysql commmands into your js, and don't use mysql library. It's very dangerous.
This is a very bad idea, since you become very vulnerable to SQL Injection, even so I will try to help you
I assume you have JQuery if you have so
you can do the following
html.file
var inputquery = "select * from `mytable`";
$.post("relative/path/to/file.php",
{query : inputquery},
function (data) {
alert(data); // See output
},'json);
file.php
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = $_POST['query'];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?