jQuery calls a PHP file to get data from mysql database? - php

Ok so I have found a number of tutorials online and have followed each of them step by step. My problem is that I know javascript/jQuery much better than I know PHP and I cannot figure out how to even debug what is going wrong in that section. Basically I have a bunch of buttons and a from and when a button is pressed it determines what the default values are in the form.
jQuery Side
$(document).ready(function(){
// CSPC and ADDUPDATE TOGGLE ARE DEFINED GLOBALLY
$('ul#parts').on('click', 'button', function(){
ADDUPDATETOGGLE = "ADD";
CSPC = $(this).attr("data-cspc");
var form = $('div.sidebar form'),
sr = 0;
form.find("#cspc").val(CSPC);
$.ajax({
type: "GET",
url: "getRate.php",
data: "pid=A5843",
dataType: "json",
success: function(data){
sr = data;
}
});
form.find("#strokeRate").val(sr);
showForm();
});
});
PHP side
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_connect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid=$_GET["pid"];
if (empty($pid)){
echo "1"; //default rate
}
else{
$db=mysql_pconnect("localhost");//connect to local database
mysql_select_db("movedb", $db);//select the database you want to use
if (!$db){
echo ("error connecting to database");
}
else{
//connection successful
$sql = "SELECT 'Processing Rate (ppm)' FROM 'part parameters' WHERE 'Part Number' LIKE '" . $pid . "'";//sql string command
$result=mysql_query($sql);//execute SQL string command
//result contains rows
$rows = mysql_fetch_row($result)
echo json_encode($rows["Processing Rate (ppm)"]);
}
}
?>
Any ideas why sr is not getting set?
Am I way off base?
I will also shamelessly note that I do not know what $user and $pass should be set to. I cannot find that explained anywhere
Thanks in advance!
EDIT: I followed most of the directions below and now when I run
http://localhost/getRate.php?pid=A5843
it says "No database selected." Also, I dont have access to our original MS Access file now (one of my team members has it) but once I get it I will make all the headers into one word headers. This is our first job with web programming/database management so we are constantly learning.

$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.
If you're still having trouble then (as long as it's not a production server) put this at the top of your php file:
error_reporting(E_ALL);
ini_set('display_errors', '1');
This will output any errors and should help you work out what's going wrong.

Your DB query code is incorrect:
$sql = "SELECT 'Processing Rate (ppm)' FROM 'part parameters' WHERE 'Part Number' LIKE '" . $pid . "'";//sql string command
using ' to quote things in the query turns them into STRINGS, not field/table names. So your query is syntactically and logically wrong. Your code is simply assuming success, and never catches the errors that mysql will be spitting out.
The query should be:
SELECT `Processing Rate (ppm)`
FROM `part parameters`
WHERE `Part Number` = '$pid'
Note the use of backticks (`) on the field/table names, and the use of single quotes (') on the $pid value.
Then you execute the query with:
$result = mysql_query($sql) or die(mysql_error());
If this fails, you will get the error message that mysql returns.
And in the grand scheme of things, your code is vulnerable to SQL injection attacks. Better read up and learn how to prevent that before you go any farther with this code.

sr it's outside the success callback function. Start putting it into the success function and see what happens
$.ajax({
type: "GET",
url: "getRate.php",
data: "pid=A5843",
dataType: "json",
success: function(data){
sr = data;
form.find("#strokeRate").val(sr);
}
});
remember that, if data is expected to be a json, it will become a js object, so you will not be able to use data directly

Here is a compilation of the above with up-to-date code.
jQuery
$(document).ready(function(){
...
$.ajax({
type: "GET",
url: "getRate.php", //see note "url"
data: {
pid : "A5843"
//, ... : "..."
},
dataType: "json",
success: function(data){
sr = data;
}
});
...
});
url > test your request-URL including any parameters (eg. http://localhost/XYZ/getRate.php?pid=251) and then enter it here, after removing anything after the '?' symbol (including '?')
data > https://api.jquery.com/Jquery.ajax/
PHP
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$pid=$_GET['pid']; //get the parameter from URL
$con = mysqli_connect($host, $user, $pass, $databaseName);
//$dbs = mysqli_select_db($con, $databaseName);
if (empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'pid invalid.'));
}
else{
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
//if (!$dbs)
//echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
else{//connection successful
$sql = SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //https://www.geeksforgeeks.org/how-to-prevent-sql-injection-in-php/
$result = mysqli_query($con, $sql) or die(mysql_error());//execute query
if($result){
$rows = mysqli_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}
else
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find results'));
}
mysqli_free_result($result);
mysqli_close($con);
}
?>
Please note that I am no PHP-expert. Any comments welcome.

Related

Json/ajax post with numerals works, returns empty if using non-numeric values. What's the proper method for this?

I'm using URL hashes to request data from my database, such as "url.com/content/book.html#132" in this format:
$(document).ready(function(){
var number = window.location.hash.substr(1);
$.ajax({
type:'POST',
url:'./db/db.php',
dataType: "json",
data:{number:number},
success:function(data){
if(data.status == 'ok'){
$('#title').text(data.result.title);
$('#author').text(data.result.author);
$('#genre').text(data.result.genre);
etc...
}
}
});
});
and in PHP:
<?php
if(!empty($_POST['number'])){
$data = array();
//database details
$dbHost = '******';
$dbUsername = '******';
$dbPassword = '******';
$dbName = '******';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Unable to connect database: " . $db->connect_error);
}
$query = $db->query("SELECT * FROM db WHERE id = {$_POST['number']}");
if($query->num_rows > 0){
$userData = $query->fetch_assoc();
$data['status'] = 'ok';
$data['result'] = $userData;
}else{
$data['status'] = 'err';
$data['result'] = '';
}
echo json_encode($data);
}
?>
This works perfectly. However, I'd also like to pull up data on another page based on genre, which I would also like to set with the URL, as in
"url.com/content/genre.html#history"
In my ajax, I simply changed the variable to 'genre' and data:{genre:genre}. In my PHP I'm selecting like this:
$query = $db->query("SELECT * FROM db WHERE genre = {$_POST['genre']}");
but it doesn't work and I even get a blank when testing with print_r ($_POST['genre']); and a console.log(gengre); shows the hash is being read correctly. What am I missing?
For those interested, I found the answer, and of course it was much simpler than I was expecting. JSON.stringify()
So:
var hash = window.location.hash.substr(1);
var genre = JSON.stringify(hash);
This turns the value into a json object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Query json_extract with PDO and SQLIte db

Try to adopt JSON in database because i have data not fixed.
i can query well from terminal, and need to write same query to php script.
i have spent a lot of time before ask.
example:
sqlite> select json_extract(events.interni, '$') from events WHERE id='35';
output
[{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
where id = 35 will become a variable of $ _POST ['id']
what I tried:
$result2 = $db->query("select json_extract(events.interni, '$') from events WHERE id='35'");
var_dump($result2->fetchAll(PDO::FETCH_ASSOC));
return [] <- empty array
i want instead = [{"student_id":"21","student_name":"Rafael Royal"}]
where did I go wrong?
I followed this answer on SO https://stackoverflow.com/a/33433552/1273715
but i need to move the query in php for an ajax call
possibile another help.
Can the result fron $ajax call can be usable as key value or remain string?
in other hands i can convert string to object like students = new Object()?
eaxaple of what i need in js environment
- count objects in array
- and loop key value
var data = [{"student_id":"12","student_name":"Lisa Ochoa"},{"student_id":"21","student_name":"Rafael Royal"}]
consolle.log(JSON.Stringify(data));
here I would like to avoid the backslash
consolle.log(JSON.Stringify(data.lenght));
in this phase the desired data is = 2
any possible help is largely appreciated
UPDATE
leave json_extract() function i have solved the second problem, so now i can work whit object property, and finally important to count objects in array:
<?php
try {
$db = new PDO('sqlite:eventi.sqlite3');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
echo $e->getMessage();
}
$risultato = $db->query("SELECT * FROM events WHERE id = '35'", PDO::FETCH_ASSOC);
$result = array();
foreach ($risultato as $row) {
$result[] = $row;
}
// echo "Results: ", json_encode($result), "\n"; this produced backslash
echo $result[0]['interni'];
?>
js part
var num='';
$.ajax({
url: "sqlitedb/test-con.php",
type: 'POST',
dataType: 'json',
success:function(result){
console.log(result[0].student_id+ " - "+ result[0].student_name); // output here is good: 12 - Lisa Ochoa
counter(Object.keys(result).length);
}});
function counter (numero){
console.log("num2: =" + numero);
}
//out put here: 2
perfect!
odd behaviour:
console.log(result[0].student_id+ " - "+ result[0].student_name);
12 - Lisa Ochoa
outup is right but
console.log(result.lenght);
output is null
You can try something like this. and since you said in the comment about approaching it with ajax. I have included that also.
I also include php mysql backend workability for clarity. so Yo have now two options
1.) PHP WITH MYSQL
2.) PHP WITH SQLITE as you requested
index.html
<script src="jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'get',
url: 'data.php',
dataType: 'JSON',
cache:false,
success: function(data){
var length = data.length;
for(var s=0; s<length; s++){
var student_id = data[s].student_id;
var student_name = data[s].student_name;
var res = "<div>" +
"<b>student_id:</b> " + student_id + "<br>" +
"<b>student_name:</b> " + student_name + "<br>" +
"</div><br>";
$("#Result").append(res);
}
}
});
});
</script>
<body>
<div id="Result" ></div>
</body>
In mysql database you can do it this way.
<?php
$host = "localhost";
$user = "ryour username";
$password = "your password";
$dbname = "your bd name";
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
echo "cannot connect to db";
}
$return_arr = array();
$query = "SELECT id, student_id, student_name FROM events where id='35'";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
?>
So with sqlitedb something like this will work for you
$return_arr = array();
$result2 = $db->query("SELECT id, student_id, student_name FROM events where id='35'");
$result2->execute(array());
//$result2 = $db->query("SELECT * FROM events where id='35'");
//$result =$result2->fetchAll(PDO::FETCH_ASSOC));
while($row = $result2->fetch()){
$student_id = $row['student_id'];
$student_name = $row['student_name'];
$return_arr[] = array("student_id" => $student_id,
"student_name" => $student_name);
}
// Encoding array in JSON format
echo json_encode($return_arr);
You are surrounding you query with double quotes but inside the query there is an unescaped $.
Try escaping it:
$result2 = $db->query("SELECT json_extract(events.interni, '\$') FROM events WHERE id='35'");
var_export($result2->fetchAll(PDO::FETCH_ASSOC));

How to subtract from mysql database after pressing html button?

I am trying to subtract 0.05 from the cash amount of a player in my database once they push a button. Here is what I got so far.
My database:
Database name: accounts
Table: users
The Column I want to affect: cash_amount
Html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'subtract5.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5ยข)</button>
Php file: (subtract5.php)
<?php
UPDATE `accounts`.`users` SET `cash_amount` = '`cash_amount` - 0.05'
Thanks for helping, I am kind of a noob :)
This the following code, however dont exactly copy paste it, read the comments there are a few variables you might have to change and get from the database.
<?php
$servername = "servarname";
$username = "username";
$password = "password";
$dbname = "dbName";
// Create connection
$userid = // You must enter the user's id here.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $previousAmount - 0.05;
$sql = "UPDATE users SET cash_amount = '$newAmount'";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
Try executing that request. That's nothing more than a string without quotes around it. I'm sure that PHP considers it as an error.
You should consider learning PHP and MySQL before attempting to code a project.

My database is not updating

So,
I am a beginning 'nerd' and my job is now to make a kind of schedule where people can put their name in the input. I work with JS with the following code:
var timeoutId; $('form input').on('input propertychange change', function() {
console.log('Invoer bewerking');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
saveToDB();
}, 1000); }); function saveToDB() { console.log('Opslaan naar Database');
form = $('.formulier24');
$.ajax({
url: "ajax.php",
type: "POST",
data: form.serialize(),
beforeSend: function(xhr) {
$('.HowAbout').html('Opslaan...');
},
success: function(data) { console.error(data) ;
var jqObj = jQuery(data);
var d = new Date();
$('.HowAbout').html('Opgeslagen om: ' + d.toLocaleTimeString());
},
}); } $('.formulier24').submit(function(e) {
saveToDB();
e.preventDefault(); });
and the AJAX file is as the following code:
<?php include ('connect.php'); if(isset($_POST['formulier24'])) {
$userName = $_POST['userName'];
$hours = $_POST['hours'];
$sql = "UPDATE evenement SET userName = '$userName' WHERE hours = '$hours'";
mysql_select_db('u7105d15197_main');
$retval = mysql_query($sql, $conn);
if (!$retval) {
die('Could not update data: ' . mysql_error());
}
echo " Updated data successfully\n";
mysql_close($conn); } ?>
The website says it is saving, but the updated information won't show up in the database. Does anybody know what I am doing wrong in this situation? P.S. it is a auto update form without a button.
I suspect your problem is that your UPDATE query is trying to update a row that doesn't exist. A REPLACE query will insert data, or replace it if there is a conflict with a table key.
While you're fixing that, you may as well toss out the code you have above. Give me 30 seconds with that web page and I could erase your whole database. (For example, what would happen if someone posted Hours as foo' OR 1=1 OR 'foo?)
It's a matter of personal preference, but I find PDO much easier to work with. It's less verbose and allows for much easier building of prepared statements, which are an essential security measure for any web application. It also allows you to use modern error handling methods like exceptions.
<?php
/* this block could be in a separate include file if it's going to be reused */
$db_host = "localhost";
$db_name = "u7105d15197_main";
$db_user = "user";
$db_pass = "asldkfjwlekj";
$db_opts = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
);
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass, $db_opts);
if(isset($_POST['formulier24'])) {
$sql = "REPLACE INTO evenement SET userName = ?, hours = ?";
$parameters = array($_POST["userName"], $_POST["hours"]);
try {
$stmt = $conn->prepare($sql);
$result = $stmt->execute($parameters);
$return = "Updated data successfully!";
} catch (PDOException $e) {
$return = "Could not update data! Error: " . $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($return);
}

PHP parsererror ajax get returns array of strings

I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.

Categories