html breaks $.parse.JSON - javascript

So in my website I'm using a TinyMCE window. In the current way PHP fetches an entry from the database, decodes this as JSON. The in-page javascript then parses this. However, if there's a style='color:#fff' or anything similar in there, the javascript can't parse the JSON. Also, spaces or exclamation mark can break it. I don't want to use something so fragile. Is there any other way to solve this?
Javascript
$.ajax({
type: "POST",
url: "Including/php/fetcher.php",
data: { identifier: identifier, page: page }
}).done(function( msg ) {
var data = $.parseJSON(msg);
var text = data["text"];
tinyMCE.activeEditor.setContent(texten);
};
fetcher.php
$conn = mysql_connect($row['ipdb'],$row['usernamedb'], $row['wwdb']) or die("err");
$db = mysql_select_db($row['usernamedb']) or die("err");
$identifier = $_POST['identifier'];
$page = $_POST['page'];
$qry = "SELECT text FROM ".$page." WHERE identifier='$identifier'";
$result = mysql_query($qry) or die("An error occurred ".mysql_error());
$obj = mysql_fetch_object($result);
$text = $obj->text;
echo '{ "text" : "' . $text . '"}';

You could use
echo json_encode( array("text" => $text, "variable2" => $value2) );
to make sure it's valid JSON and escaped correctly, that way it wouldn't break on quotes, spaces etc.

Related

Handling special characters in and out of mysql

I'm building a leaflet web app which stores messages assigned to geolocations.
I add data one line at a time by sending it from javascript to PHP using:
$name = mysqli_real_escape_string($conn, $_POST['NAME']);
$latitude = mysqli_real_escape_string($conn, $_POST['LATITUDE']);
$longitude = mysqli_real_escape_string($conn, $_POST['LONGITUDE']);
$message = mysqli_real_escape_string($conn, $_POST['MESSAGE']);
$sql = "INSERT INTO geoData (NAME,LATITUDE,LONGITUDE,MESSAGE)
VALUES ('$name', '$latitude', '$longitude', '$message')";
I get the data back out using PHP to echo the data back to javascript using:
$conn = mysqli_connect($dbServername,$dbUsername, $dbPassword, $dbName);
if(! $conn ){
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT * FROM geoData';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
} else {
echo "0 results";
}
mysqli_close($conn);
<script type="text/javascript">
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
</script>
This works fine UNLESS the message has special characters such as apostrophes for example 'Dave's dogs's bone'. This creates an error
What is the best practise for such an application which uses PHP and javascript. I think I need some way to encode the special characters which javascript can then decode and display.
The error comes as:
Uncaught SyntaxError: missing ) after argument list
<script type="text/javascript">
var data = JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGITUDE":"-1.3100980520","MESSAGE","Dave's Dog's Bone"}] ' );
</script>
Many thanks
The issue is your JSON.parse() which isn't needed at all in this case.
Change:
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
to
var data = <?= json_encode($rows); ?>;
JSON.parse() is for parsing stringified json. Echoing the result from json_encode() will give you the correct result straight away.
Side note
I would recommend adding $rows = []; before your if (mysqli_num_rows($result) > 0) or json_encode($rows) will throw an "undefined variable" if the query doesn't return any results (since that variable currently is created inside the loop when you're looping through the results).
Side note 2
When making database queries, it's recommended to use parameterized Prepared Statements instead of using mysqli_real_escape_string() for manually escaping and building your queries. Prepared statements are currently the recommended way to protect yourself against SQL injections and makes sure you don't forget or miss to escape some value.
You produce that error yourself by adding ' in json. If you want check that use this:
JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGDITUTE":"-1.3100980520","type":"bad","reason":"Dave\'s Dog\'s Bone","improvement":"","reviewed":"0"}] ' );
And if you want correct that in main code use str.replace(/'/g, '"') for your var data, before parse it to json.

Search form using ajax, php and json

i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>

Return PHP Mysql query using AJAX onclick function

So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}

Saving (with JS Request) and reading (with PHP) XML in MySQL

I'm trying to save some xml content (that I receive as plain text) into my site's database. I read about saving XML content and someone suggested it is not a good idea to save XML in a text field (database), so I decided to do it in a blob. The thing is I'm doing it via CORS, through javascript this way:
var formData = new FormData();
formData.append("name", 'myNewFile');
// THE XML CONTENT
var content = '<a id="a"><b id="b">hey!</b></a>';
var blob = new Blob([content], { type: "text/xml"});
formData.append("file", blob);
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
resultsContainer.innerHTML = (request.responseText );
}
}
request.send(formData);
On the server, I store it with:
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('$name', '$file')";
It seemed to work, the entry was created in the database but I can't see what's inside the BLOB field. So, I tried to read that from server, using PHP, but I'm retrieving just "0" in the file field.
$sql = "SELECT datetime, name, file FROM ProfileFiles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Timestamp: " . $row["datetime"]."<br>";
echo "Name: " . $row["name"]. "<br>";
echo "Content: " + $row["file"];
echo "<br>----------<br>";
}
}
else
{
echo "Nothing";
}
What am I missing? Thanks in advance! I never worked with PHP.
The reason why you don't get anything in $_POST['file'], is that you are sending it as a file. Files that are posted are in the superglobal variable $_FILES not $_POST. $_FILES['file'] will contain an array
array('name' => '...', 'tmp_name' => '...', 'type' => '...', 'size' => '...');
The content will be saved to a temporary file whose name is stored in $_FILES['file']['tmp_name']
You see, you really go astray here... What you have to do is to send the XML data as a POST variable and not a file. When doing this, you can save the data to the database like you tried it, but with prepared statements, it will be something like (assuming you are using mysqli
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES (?, ?)";
$stmt = $mysqli->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param("ss", $name, $file);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
The point of using a prepared statement is this :
If the file contains a ', you get an error in the query. Also your code is vulnerable to sql injection. You need to escape the strings in the query.
I never used mysqli myself, and the code I gave looks a bit clumsy, so here's an alternative :
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('". mysqli_real_escape_string($name)."', '".mysqli_real_escape_string($file) ."')";

How can i add a variable in AJAX URL

I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"
var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.

Categories