AJAX PHP Is Not Working in Node.js - javascript

The Problem:
When I put a PHP file link in the browser, it works perfectly fine and updates my database as expected.
When I call it with ajax from node.js, it echoes the success message but the DB does not update.
The Session variables are undefined, so when I changed them to real numbers the code still did not work. What is going wrong?
My PHP Code:
subtract5.php:
<?php
header('Access-Control-Allow-Origin: http://cashballz.net:3000', false);
include 'mysql.php';
session_start();
$cash_amount = $_SESSION['cash_amount'];
$userid = $_SESSION['id'];
$_SESSION['cash_amount'] -= 0.05;
$mysql = new Mysql();
$result = $mysql->setCashAmount($cash_amount,$userid);
if($result)
{
echo $cash_amount;
}
else
{
session_start();
session_unset();
session_destroy();
}
?>
mysql.php:
<?php
class Mysql
{
protected $dsn;
protected $username;
protected $password;
public $db;
function __construct()
{
//change this to your info (myDBname, myName, myPass)
$this->dns= 'mysql:dbname=cashball_accounts;host=localhost;charset=utf8';
$this->username= 'myUser';
$this->password= 'myPass';
$this->db = new PDO($this->dns, $this->username, $this->password);
}
public function setCashAmount($cash_amount, $id)
{
$sql = "UPDATE users SET cash_amount = :cash_amount - 0.05 WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':cash_amount', $cash_amount, PDO::PARAM_STR);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$result = $stmt->execute();
return $result;
}
}
?>
My node.js (app.js) AJAX:
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: {},
success: function (data) {
alert(data);
}
});
Recap:
PHP File works from site.com with the same AJAX code, and by putting its link in the browser.
PHP File is executed from node, but does not update the DB
PHP File has undefined $_SESSION variables but when replaced, the DB still does not update
Possible solutions:
Is there extra code i can put in AJAX to tell it to "pipe" the call to site.com to call the file instead of calling it straight from node?
Extra Info:
No errors in error logs or console
I need to use AJAX to input data into the file later on
Solution must be secure
Thanks for the help!

Related

Using AJAX to get an SQL WHERE query into javascript

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
?>

POST-GET session variable (javascript-php) -javascript takes the previous variable but not last created

From the selected value (from the form) I create a variable (var parcela).
var parcela;
$(document).ready(function(){
parcela = localStorage.getItem("parcela");
if (parcela !== '') {
$('#parcela').val(parcela);
}
$("#parcela").on('change',function() {
selectBoxVal_1 = $('#parcela').val();
if (typeof(Storage) !== "undefined") {
localStorage.setItem("parcela", selectBoxVal_1);
} else {
alert('Sorry! No Web Storage support..');
}
location.reload();
});
});
From the created variable (parcela), I create a session variable in PHP.
$.post("phpscripts/session.php", {"parc_id": parcela});
PHP (session.php)
<?php
session_start();
$parcela = $_POST["parc_id"];
$parcela_int = (int)$parcela;
if($_POST){
$_SESSION['parcela_id'] = $parcela_int;
}
?>
After that, the created session variable urge to another php script
query.php
<?php
session_start();
require("common.php");
$user_id = htmlentities($_SESSION['user']['id_korisnika']);
$parc = $_SESSION['parcela_id'];
try
{
$stmt = $db->prepare("SELECT y_cent, x_cent FROM parcele WHERE id_korisnika='$user_id' AND id_parcele='$parc' ");
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
....
This all works perfectly!
However, when I call a php script with query (query.php) in javascript, there is a problem. JS takes the previous session variable instead of the last selected.
$.ajax({
url: 'phpscripts/query.php',
type: 'GET',
success : function(data) {
chartData = data;
//console.log(chartData);
...
Does anyone know what the problem is? I'm trying for two days to solve this ...
Note: The javascript code is contained in a single script.
I solved the problem. I had to extract part of javascript code that calls the php script into a separate script. I called the new JS script with jQuery getScript() Method.
Thank you #knets.

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)

my ajax call is returning html with json data

I am having a weird problem, I am trying to populate the datatable using ajax call to my php program which internally gets data from database.
php:
<?php
require_once('config.php');
$query = mysql_query("select * from productdetails");
while($fetch = mysql_fetch_array($query))
{
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output, JSON_FORCE_OBJECT);
?>
Html(ajax call):
$.ajax({
url: 'process.php?method=fetchdata',
data: "json",
success: function(s){
console.log($(s).text());
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
This generates the output as
( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\datatableone\process.php on line 2
Call Stack
#TimeMemoryFunctionLocation
10.0010242552{main}( )..\process.php:0
20.0010242840http://www.php.net/function.mysql-connect' target='_new'>mysql_connect
( )..\process.php:2
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
But my required output should be: (only json)
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas
Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
any suggestions please.
Thanks
Sai
Solution:
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
try {
$conn = new PDO("mysql:host=$servername;dbname=holt", $username, $password);
$statement=$conn->prepare("SELECT * FROM productdetails");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Thanks for suggestions.
As noted in the comments, you should turn off warnings, or better yet, write your code in a manner that doesn't produce warnings.
On turning off warnings:
Turn off warnings and errors on php/mysql
You can suppress errors inline with the # symbol, which is the error control operator in php. Putting # at the beginning of your mysql_connect() line should get rid of it, but you should switch to PDO!
On PDO (which I recommend and use):
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PDO protects you against SQL injection and allows queries to be sent to the database and constructed beforehand, and you send the inputs afterwards via "placeholders".

Using ajax to display new database inputs without refreshing the page

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?

Categories