I have 5 different categories of items. I need to make get the count of each item in the categories and update the count on page. I'm making an AJAX call to a PHP function which grabs the data from a MySQL table. I can get close but can't quite get it to work.
AJAX:
$(function(){
$.ajax({
url : '/getItemList.php',
type : 'GET',
dataType: 'json',
success : function(data) {
$(data ).each(function( key, value ) {
console.log( key + ": " + value);
});
},
error : function(request,error)
{
console.log(request);
}
});
})
PHP:
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT itemType, count(*) from `Items` group by itemType");
$stmt->execute();
$results=$stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
}
catch(PDOException $e)
{
$errorMessage = "Sorry, something webt wrong";
}
$conn = null;
?>
Output:
0: [object Object]
1: [object Object]
2: [object Object]
I was hoping for more of:
"itemCategoryOne" : 3
"itemCategoryTwo" : 12
"itemCategoryThree" : 3
Which is what is stored in [object Object] above.
In success call back of ajax request first you'll need to parse the data.
Ex: JSON.parse (data). then you can use each function on parsed item.
fetchAll return array of result that key is column name and value is value of row. So you should convert it to what you want:
Note: for get count(*) in PDO, need to alias count(*).
<?php
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT itemType, count(*) as count from `Items` group by itemType");
$stmt->execute();
$results=$stmt->fetchAll(PDO::FETCH_ASSOC);
$response_array = array();
foreach($results as $result) {
$response_array[$result['itemType']] = $result['count'];
}
echo json_encode($response_array);
}
catch(PDOException $e)
{
$errorMessage = "Sorry, something webt wrong";
}
$conn = null;
?>
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);
}
I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}
My ajax:
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//$(".the-return").html("<br />JSON: " + data["json"] );
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
alert(data);
// window.location='success.php'
}
});
return false;
});
});
I declared a variable to store unique_id like this:
$unique_id=uniqid();
I'm inserting data like this:
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
echo $stmt2->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Now, I want to pass the above unique_id to ajax page but couldn't.
echo $unique_id;
It just doesn't alert anyting, but:
$abc="123";
echo $abc;
this shows the alert box with value 123!
Why is it so? WHy I coudn't pass unique_id value like this?
MY ENTIRE PHP SCRIPT:
<?php
//Function to check if the request is an AJAX request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$return = $_POST;
$return["json"] = json_encode($return);
//below code to store in database
$data = json_decode($return["json"], true);
/*....salting starts........*/
/*..........salting ends..............*/
echo $unique_id=uniqid();
$name=$data['name'];
$phone=$data['phone'];
$email=$data['email'];
$postcode=$data['postcode'];
$a=$data['sub'];
$b=$data['rate2'];
$subject_rate = array_intersect_key($b,$a);
/*...pdo.............................*/
$username="root";
$password="";
try {
//$pdo = new PDO('mysql:host=localhost;dbname=users', $username, $password);
//$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
$stmt = $pdo->prepare('INSERT INTO authsessions (email,useruuid,salt,hashpword) VALUES(:email,:useruuid,:salt,:hash)');
$stmt->execute(array(
':email' => $email,
':useruuid'=>$unique_id,
':salt'=>$salt,
':hash'=>$hash
));
# Affected Rows?
$stmt->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query2
try
{
$stmt2 = $pdo->prepare('INSERT INTO usrinfo (UUID,Name,Phone,Email,Postcode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,Status,IsTuitionCentre) VALUES(:uuid,:name,:phone,:email,:poscode,now(),:reputation,:reviewplus,:reviewneg,:sex,:status,:permission)');
$stmt2->execute(array(
':uuid' => $unique_id,
':name'=>$name,
':phone'=>$phone,
':email'=>$email,
':poscode'=>$postcode,
':reputation'=>78,
':reviewplus'=>65,
':reviewneg'=>3,
':sex'=>$gender,
':status'=>0,
':permission'=>$permission
));
# Affected Rows?
$stmt2->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query3
try
{
$stmt3 = $pdo->prepare('INSERT INTO tutoravailability (uuid,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening) VALUES(:uuid,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening)');
$stmt3->execute(array(
':uuid' => $unique_id,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening
));
# Affected Rows?
$stmt3->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
//query4
foreach($subject_rate as $v=>$k)
{
$key=$v;
$value=$k;
$post_unique_id= uniqid();
try
{
$stmt4 = $pdo->prepare('INSERT INTO posts (PostUUID,subid,date,pricing,post_status,UUID,Name,Phone,Email,Poscode,DateReg,Reputation,ReviewPlus,ReviewNeg,Sex,week_morning,week_afternoon,week_evening,weekend_morning,weekend_afternoon,weekend_evening,Status) VALUES(:PostUUID,:subid,now(),:pricing,:post_status,:UUID,:Name,:Phone,:Email,:Poscode,now(),:Reputation,:ReviewPlus,:ReviewNeg,:Sex,:week_morning,:week_afternoon,:week_evening,:weekend_morning,:weekend_afternoon,:weekend_evening,:Status)');
$stmt4->execute(array(
':PostUUID' => $post_unique_id,
':subid'=>$key,
':pricing'=>$value,
':post_status'=>1,
':UUID'=>$unique_id,
':Name'=>$name,
':Phone'=>$phone,
':Email' =>$email,
':Poscode'=>$postcode,
':Reputation'=>78,
':ReviewPlus'=>65,
':ReviewNeg'=>3,
':Sex'=>$gender,
':week_morning'=>$week_morning,
':week_afternoon'=>$week_afternoon,
':week_evening'=>$week_evening,
':weekend_morning'=>$weekend_morning,
':weekend_afternoon'=>$weekend_afternoon,
':weekend_evening'=>$weekend_evening,
':Status'=>0
));
# Affected Rows?
$stmt4->rowCount(); // 1
} catch(PDOException $e) {
'Error: ' . $e->getMessage();
}
}
/*try
{
$sql = "SELECT *FROM authsessions WHERE useruuid =:uid";
$statement = $pdo->prepare($sql);
$statement->bindValue(':uid', $unique_id);
$statement->execute();
$json = array();
while( $row = $statement->fetch()) {
array_push($json, array("id" => $row['useruuid']));}
header('Content-Type: application/json');
echo json_encode($json);
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}*/
// $unique_id=uniqid();
}
?>
You need to use json_encode because the AJAX call says dataType: "json".
echo json_encode($unique_id);
It worked when you echoed 123 because a decimal number is valid JSON. But uniqid returns a hex string, and this isn't valid JSON. You need to encode it with quotes around it.
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');