JSON not encoding as json or UTF-8? - php

I am having some headaches with JSON not returning as JSON. I get no errors, just no data. The browser shows the data in the response.
I know it's not returning as JSON because setting the dataType in the AJAX section causes it to display nothing. If I remove the dataType statement, it displays the data.
I've played around with encoding in the connection string, in the queries, as a header, and in the AJAX section all to no avail. My database is in UTF-8, general_ci.
AJAX:
$.ajax({
contentType: 'application/json; charset=UTF-8',
data: {'career' : $career},
dataType: 'json',
url: 'functions.php',
success: function(data) {
$("careerdata").html(data);
},
PHP:
if (isset($_GET['career'])) {
require_once 'config.php';
$query = $dbconnect->prepare("select * from jobs where Category = :category");
$query->bindParam(':category', $category);
$category = $_GET['career'];
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
$dbconnect = null;
return;
} else {
echo 'No career data found.';
};
Connection file:
try {
$dbconnect = new PDO("mysql:host=$host;dbname=$database", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
};
If any more info is needed, please let me know.
Working page is https://www.shardsmith.com/career.php and the actual query is https://www.shardsmith.com/functions.php (but it won't work independently because of the GET variable).

It seems that the MySQL (php) client does assume another client encoding than UTF-8. You can request the correct encoding using
$dbhconnect->exec("SET NAMES utf8");
directly after you connect to the database.
Alternatively, you can use PDO::MYSQL_ATTR_INIT_COMMAND (see http://php.net/manual/de/ref.pdo-mysql.php) in your connection config:
$dbconnect = new PDO("mysql:host=$host;dbname=$database", $user,
$pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
And be careful with unchecked frontend parameters: this is an open door for SQL injections. Either use a prepared statement like this:
$query = $dbconnect->prepare("select * from jobs where Category = :cat");
$query->execute(array(':cat' => $_GET['career']));
or escape the input paramerers first:
$cat = $dbhconn->quote($_GET['career']);
$res = dbhconnect->query("select * form jobs where Category = {$cat}")->fetchAll();

I ended up figuring it out myself. The json itself was fine. At some point I completely forgot about each-looping through the key-value pairs in order to actually display them. For example:
$.each(data, function(key,value) {
var $itemid = value.ItemID;
var $db = value.DB;
var $job = value.Job;
var $recipe = value.Recipe;
var $level_range = value.Level_Range;
var $level = value.Level;
var $grade = value.Grade;
var $rarity = value.Rarity;
var $complete = value.Complete;
$("careerdata table").append("<tr class=\"recipe\" id=\""+$recipe+"\">"
+"<td>"+$level+$grade+"</td>"
+"<td class=\"icon\"><img style=\"background: url(\'/images/items/"+$job+"/"+$itemid+".png\') 0 1px/42px 42px;\" src=\"/images/items/reflection.png\" /></td>"
+"<td class=\""+$rarity+"\">"+$recipe+"</td>"
+"<td><input class=\"complete\" type=\"checkbox\" value=\""+$complete+"\"></td>"
+"</tr>");
});

Related

Ajax call with DB Connection 'include' gives POST 500 error

Does anyone know why when I move a database connection 'include' out of a function and place it at the beginning of the PHP file that I get a POST 500 error? The exact same database connection 'include' works perfectly within the function. Here is the code that causes the error:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/phpscripts/set_path.php'); // DB Connection Path
include 'mysqli_connect_sa.php'; // DB Connection
if(isset($_POST['row']))
{
$uid = $_POST['row'];
$response_bdls = getBDLs($uid);
$response_cg = getCompetencyGaps($uid);
echo json_encode(array($response_bdls, $response_cg));
}
Just in case you want to see the Ajax call:
$.ajax({
type: "POST",
url: '/phpscripts/ss_scbdls.php', //
data: {row : row},
success:(function(response){
response = JSON.parse(response);
loadSC_bdls(response[0]);
loadSC_cg(response[1]);
})
});
Thank you for any insights or direction you can provide.
Requested Information #1
Here is the mysqli_connect_sa.php Content:
// SA Database access information
$hn = 'localhost';
$db = 'xxxxxxxx';
$un = 'xxxxxxxx';
$pw = 'xxxxxxxx';
// Connect to DB
$dbc = new mysqli($hn, $un, $pw, $db);
// Set the Encoding
mysqli_set_charset($dbc, 'utf8mb4');
Function:
function getBDLs($candidate_id)
{
$sc_bdls = [];
$sql_query_bdls = "SELECT bdl_increment AS id, learn_load, start_date, target_date, completed_date, bdl_20, bdl_10, bdl_70, cg, cg_orn, cg_tit, cg_lj FROM bdls INNER JOIN competency_gaps USING (cg_id) WHERE bdls.candidate_id = $candidate_id";
$result_bdls = $dbc->query($sql_query_bdls);
while($bdls = mysqli_fetch_assoc($result_bdls)) {
$sc_bdls[] = $bdls;
}
mysqli_free_result($result_bdls);
return $sc_bdls;
}

Retrieve ID number from MYSQL using AJAX & PHP then hashchange URL using retrieved ID

I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});

PHP/JSON/ANDROID - why my JSONArray getting error

i try to displaying value of my table in android, and i put my code into hosting,
but when i try to running my app, my link doesn't work,
and i tried to create new link that displays the same output , and its works fine,
this is my code to encode json
send_data.php
<?php
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select id,ask from pertanyaan";
$result = mysqli_query($con, $query);
while ($r = mysqli_fetch_array($result)) {
extract($r);
$rows[] = array(
"id"=>$id,
"ask"=>$ask
);
}
header('Content-Type: application/json');
echo json_encode($rows);
mysqli_close($con);
?>
did I'm doing something wrong??
because I want to set the output from the database
This is just a suggestion without seeing your AJAX code:
Add this code to the top of your PHP code:
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
And use this code as an example of AJAX:
var poutput = $('.itemsHolder');
$.ajax({
url: 'https://yourdomain.com/php/YOUR-PAGE.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(pi,item){
str = item.id;
var products = '<div id="'+item.id+'">'+
'</div>';
poutput.append(products);
});
},
error: function(){
//alert('There was an error loading the data.');
}
});
Don't forget to add an element with the class name of itemsHolder to your page.

Special characters with Ajax and MySQL

I have a MySQL database encoded with the default characterset UTF8. I have also a PHP code encoded with the same charset meta charset="UTF-8".
My connection to the database is configured to use UTF8 too
new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
But I have a problem when I use Ajax to get the content of a textbox and insert it into the database.
If I do not use special characters it works fine but when I use a quote or something everything stops working.
I tried to use UTF8_encode and UTF8_decode but nothing changed
EDIT
PHP
...
<meta charset="UTF-8">
...
<textarea class="commentBox" id="<?php echo $id_case;?>"></textarea>
<button class="saveComment" id="<?php echo $id_case;?>"> Save comment </button>
//id_case is different for each textarea
Javascript
$('.saveComment').click(function()
{
var idComment = this.id;
var content = $('#'+idComment+'.commentBox').val();
add_comment(idComment, content);
});
function add_comment(case_id, content)
{
$.post("../functions/ajax/add_comment.php",
{
id_case: case_id,
content: content
},
function(data,status)
{
alert("It worked !");
console.log("Function add_comment : "+status);
});
}
add_comment.php
<?php
if(isset($_POST['id_case'], $_POST['content']))
{
$case = $_POST['id_case'];
$content = $_POST['content'];
}
else
{
echo "Error during sending data to [add_comment.php]";
}
if($db != null)
{
try
{
$sql = ("UPDATE cases SET progress_remarks = '$content' WHERE id_cases = $case");
$result = $db->exec($sql);
echo $content;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
else echo "Erreur interne (fill_progress.php)";
?>
My database connection is done somewhere else but looks like this
$this->con = new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
when I use a quote or something everything stops working.
It is unclear whether the problem is (1) just an escaping issue, or (2) also a utf8 issue.
Since PDO has a builtin way to take care of escaping, use it:
$sql = ("UPDATE cases SET progress_remarks = ? WHERE id_cases = $case");
$result = $db->exec($sql, $content);
This is probably the preferred way to set the charset with PDO: $db = new PDO('dblib:host=host;dbname=db;charset=UTF-8', $user, $pwd);
meta charset="UTF-8" refers to the tag in HTML, not PHP or MySQL.
SHOW CREATE TABLE -- Is the column in question declared CHARACTER SET utf8?

Converting PHP query to PDO query

I have some php that is receiving a variable from jquery and querying the DB. I recently learned that I need to use PDO to prevent SQL Injections and such so I have been trying to convert my query to it. I am new at php anyway so this is turning out to be more difficult than I thought (even though all the articles I read looked quite straightforward)...The DB connection is working and 'name' is receiving the right value but it is not updating the page like it used to. I am guessing it has to do with my loop that contains the json_encode. Below is my old php and then my attempt at turning it into PDO format.
Old PHP:
$dbstylename = $_POST['name'];
$result = mysql_query("SELECT * FROM style where stylename like '$dbstylename'");
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_close($con);
?>
New PDO attempt:
<?php
include 'db.php';
try {
$dbConnection = new PDO('mysql:host=$dbhost;dbname=$dbhost;', $user, $pass);
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#Prepare the query
$dbstylename = $_POST['name'];
$result = $dbConnection->prepare('SELECT * FROM style where stylename like :dbstylename');
#bind
$result->bindParam(':dbstylename', $dbstylename, PDO::PARAM_STR);
#execute
if ($result->execute(array($dbstylename))) {
while ($row = $result->fetch()) {
json_encode($row);
}
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
================UPDATE==============================
In addition to #MadaraUchiha great answer and follow up help I had to change my jQuery from this (which worked before PDO):
$.ajax({
url: '../test.php',
type: 'POST',
data: {'name' : target},
dataType: 'json',
success: function(data) {
var styleid = data[0];
var stylename = data[1];
var stylecss = data[2];
$('#codeTest').html("<b>id: </b><br />"+styleid+"<br /><b> stylename: </b><br />"+stylename+"<br /><b> stylecss: </b><br />"+stylecss);
}
});
To this:
$.ajax({
url: '../test.php',
type: 'POST',
data: {'name' : target},
dataType: 'json',
success: function(data) {
var styleid = data.styleid;
var stylename = data.stylename;
var stylecss = data.stylecss;
$('#codeTest').html("<b>id: </b><br />"+styleid+"<br /><b> stylename: </b><br />"+stylename+"<br /><b> stylecss: </b><br />"+stylecss);
}
});
Let me start with this, it's great that you're working on improving from the old ext/mysql to PDO. Well done!
Well, first, you don't need to check for errors! Since you've set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, an Exception would be thrown if there's an error! so your if statement on
if ($result->execute(array($dbstylename))) {
Is redundant.
Second, since you've already bound the parameter with bindParam, passing it again with the array is also redundant.
Lastly, if you only expect one result, you can drop the while loop, or even use $result->fetchAll(PDO::FETCH_ASSOC) to fetch all of the result into a single array.
Now for the real problem, you aren't echoing the result of json_encode(), like you used to in the first script (You're just calling it without doing anything with the result).
Corrected code, with all of the above taken into account:
<?php
include 'db.php';
try {
$dbConnection = new PDO('mysql:host=$dbhost;dbname=$dbhost;', $user, $pass);
$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#Prepare the query
$dbstylename = $_POST['name'];
$result = $dbConnection->prepare('SELECT * FROM style where stylename like :dbstylename');
#bind
$result->bindParam(':dbstylename', $dbstylename, PDO::PARAM_STR);
#execute
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
echo json_encode($row);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
Other than that, you're PDO code is flawless, keep it up!
Also sequence of json encoded strings with array elements are not equal to hole json encoded array. Replace while loop with
echo json_encode($result->fetchAll());
In my original post I mentioned my jQuery change. However, I read up a bit more about PDO in the manual (specifically: http://www.php.net/manual/en/pdostatement.fetch.php) and found that if I changed $row = $result->fetch(PDO::FETCH_ASSOC); from #MadaraUchiha answer to $row = $result->fetch(PDO::FETCH_BOTH); I could keep my original jQuery that used the array/bracket notation.

Categories