How to pass a String variable from PHP to Javascript [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I'm trying to pass a string variable from PHP to Javascript and it is giving me troubles.
I actually pas a number variable as per the code below and it works, but once I introduce (or uncomment) the line var cityname = <?=$city;?>; in my javascript code then it doesn't work. I believe it has something to do with the type of data because if I introduce a number like Scity = 3 in my PHP then it works.
Thank you
I have the following PHP:
<?php
$get_total_rows = 0;
$city = "London";
$db = pg_connect("$db_host $db_name $db_username $db_password");
$query = "SELECT * FROM table";
$results = pg_query($query);
$get_total_rows = pg_numrows($results);
?>
and I have the following javascript:
<script type="text/javascript">
$(document).ready(function() {
var track_load = 0; //total loaded record group(s)
//var cityname = <?=$city;?>;
var total_rows = <?=$get_total_rows;?>;
$('#results').load("autoload_process.php", {'rows':total_rows}, function() {track_load++;}); //load first group

In the case of strings, the content must be between quotes (ex.: val = "content"). Try to do something like this:
var track_load = 0; //total loaded record group(s)
var cityname = "<?php echo $city; ?>"; // string
var total_rows = <?php echo $get_total_rows;?>; // number

Related

Can't use JSON.parse() to import array from PHP [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 8 months ago.
So I've got a form where I can create multiple datalist-text-inputs of the same type that is later (onclick) put into an invisible input before submitted.
These datalist-text-inputs is created onload so that I can add more with an "+" button with the same function.
The options are imported from my PHP-database, and it worked fine. But suddenly it stopped working and I don't know why. I've tried a thousand things but can't figure it out.
I'm quite new to PHP. I think the problem has to do with JSON.parse() since the code breaks on that line.
script.js
var ajax = new XMLHttpRequest();
ajax.open("GET", "fetch data.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var html = "";
for (var a = 0; a < data.length; a++) {
var firstName = data[a].name;
html += "<option value='" + firstName + "'></option>";
};
document.getElementById(type+"list"+addnumber).innerHTML = html;
};
};
type+"list"+addnumber it the name of the input-text-box. Type is an argument and addnumber an variable/integer.
fetch data.php
<?php
$host = "localhost"; $user = "root"; $pass = ""; $db = "collection";
$conn = mysqli_connect($host, $user, $pass, $db);
$result = mysqli_query($conn, 'SELECT name FROM musicians ORDER BY name');
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
};
echo json_encode($data);
?>
Also, I might add that this function creates objects in three places on the same page but the value is added/moved to three different invisible inputs.
Based on the exception you're seeing, ie:
JsonException: Malformed UTF-8 characters, possibly incorrectly encoded in C:\wamp64\www\collection\fetch data.php on line <i>11</i>
My guess is that the data you are reading is not encoded in a way which json_encode expects.
The simplest (NOT RECOMMENDED) approach is to pass in the JSON_INVALID_UTF8_IGNORE or JSON_INVALID_UTF8_SUBSTITUTE flags, which will cause bad data to be silently skipped over (or replaced with the unicode REPLACEMENT CHARACTER \0xfffd), rather than treating it as an error. See the documentation for json_encode and predefined JSON constants.
If you want to get to the root of the problem so that all data is correctly encoded as JSON, however:
You can try to force the encoding by setting the mysql character set using PHP's mysqli_set_charset function, eg:
<?php
$host = "localhost"; $user = "root"; $pass = ""; $db = "collection";
$conn = mysqli_connect($host, $user, $pass, $db);
if (!mysqli_set_charset($conn, 'utf8')) {
throw new \Exception("failed to set mysql charset");
}
$result = mysqli_query($conn, 'SELECT name FROM musicians ORDER BY name');
...
?>
The most common charsets in my experience are utf8, utf8mb4. If you know your data to contain some other specific character set, you may need to translate it into utf8 before trying to encode it into JSON using PHP's mb_convert_encoding function.
Finally, it could be that the issue has occurred earlier in your application, resulting in bad (mixed-encoding) data. If this is the case, you'll need to detect the bad data row-by-row, perhaps outputting where exceptions were raised in a separate error report, and manually correct the encoding of that data. This can be prevented by ensuring the data is validated and correctly encoded as utf8 before it reaches your database. Note that ensuring the mysql character set is correctly set for all connections is also potentially a part of this solution. It may be that you'll want to configure your database to do this automatically.
example of detection and logging:
<?php
$host = "localhost"; $user = "root"; $pass = ""; $db = "collection";
$conn = mysqli_connect($host, $user, $pass, $db);
if (!mysqli_set_charset($conn, 'utf8')) {
throw new \Exception("failed to set mysql charset");
}
$result = mysqli_query($conn, 'SELECT name FROM musicians ORDER BY name');
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
try {
// detect rows which cannot be encoded
$discard = json_encode($row, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
// keep track of failed rows so we can correct them later
my_custom_logging_function($row);
// and skip the row so we don't try to encode it later
continue;
}
$data[]=$row;
};
echo json_encode($data, JSON_THROW_ON_ERROR);
?>
OK just change "fetch data.php" to "data.php"

Send a javascript var to php [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I try to assign a string type javascript variable to a php variable and retrieve a table from database, I wrote all the code in a file.
I read date from input:
<input type="date" id="myDate" >
and by a listener I run myDate function, it produce sql1 that is a string, it should pass sql1 to $sql, I tried that users explain in other Q's but I don't get the right answer :
<script>
var dateBut = document.getElementById("myDate")
function myDate() {
var x = document.getElementById("myDate").value;
document.getElementById("demo3").innerHTML = x;
// sql1 string
var sql1 = "SELECT * FROM TSE(" + document.getElementById("demo3").innerHTML +")";
document.getElementById("demo2").innerHTML = sql1;
var tbl = document.getElementById("demo");
tbl.innerHTML = "";
var ch = document.getElementById("checkerWork");
<?php
// sql1 should pass to $sql;
$sql = ?>"SELECT * FROM TSE(" + document.getElementById("demo3").innerHTML + ")"<?php
mysqli_set_charset($conn, "utf8");
$result = $conn->query($sql);
?>
}
dateBut.addEventListener("change", myDate, false );
all of the code is in a php file.
thanks
I would send the contents of the variable to a PHP page via Ajax with jquery, then I would assign the data sent via get or post to the PHP variable, execute the query and return the result to the myDate () function. I'm not a native English speaker so if the answer is not clear tell me and I'll give you an example.

Using PHP string in SQL query works when typed in but not when generated via javascript

$query = "
select * from tablename where userid = :uid AND date = :date
";
$query_params = array(
':uid' => $_SESSION['user']['uid'],
':date' => $date
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
I am trying to run this simple SQL query via PHP. When I hard-code a string of a date like $date = '2016-07-29'; then I get the proper number of results. When I dynamically generate the same string using javascript like
$date = '<script> var currentdate = new Date();
document.write(currentdate.getFullYear()+"-"+
("0"+(currentdate.getMonth()+1)).slice(-2)+"-"+
("0"+currentdate.getDate()).slice(-2));
</script>';
then I get 0 results. Any ideas? Echoing $date in both instances produces the same result (type = string).

inserting integer variable into Database

How can I put this int value in our database? I've tried putting (int) and intval before $_POST but it still doesn't work? Everything else works except the conversion(?) of that int value so it can be placed in our database. Did we miss anything in the code? Thank you in advance.
function computeScoregrammar(){
// code for computing the score here
aver = 5;
<?php
//db connection here
$avegs = $_POST['aver'];
$qidScores = 4;
//below part is not yet complete for we are only trying to update a sample data in the database
if($qidScores == 4){
$qs = "UPDATE scores SET GrammarScore = '$avegs' WHERE applicantID = '$qidScores'";
mysqli_query($conn,$qs);
mysqli_close($conn);
}
else {
//else statement here
}
?>
Try it:
$qs = "UPDATE scores SET GrammarScore = $avegs WHERE applicantID = '$qidScores'";
$avegs without using ''. If you use '', $avegs will be treated as string.
WARNING: SQL injection, do not put this online! Use PDO or escaping (mysqli_escape_string()) and remove the ''.

How to get the same result with PHP and CryptoJS using SHA256?

I'm trying to decode Firefox Sync data using javascript, porting one php library which does it (https://github.com/mikerowehl/firefox-sync-client-php). The idea is to decode sync data without sending sync key to the server. This is just context, the problem I have is much more specific.
One portion of code requires using sha256 to obtain certain key. I would like to replicate it in javascript. The approach I've tried, with CryptoJS, is this:
PHP code:
$key = hash_hmac("sha256",'OLA K ASE','CLAVE', false);
print $key;
Equivalent Javascript code (previously, I've included http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/hmac-sha256.js):
var hash = CryptoJS.HmacSHA256("OLA K ASE", "CLAVE");
console.log(hash.toString());
This works fine. In each case, output is 9591d44df0c8e2d7a1f400f41117c536e10f58d7e28bdc1cad9d81e70290bc1b, which I suppose is correct.
But, when I'm trying to encode non-ascii strings, results differ. For example, with this PHP code:
function hexstring($str){
return preg_replace('/\\\\x([0-9a-f]{2})/e', 'chr(hexdec(\'$1\'))', $str);
}
$text = hexstring('\x00\x44\xb0\x2c\x0b');
$key = hexstring('\xd6\xf8\xb0\x2c\x0b');
$hash = hash_hmac("sha256",$text,$key, false);
print $hash;
I get 0697f5528c996006ffeb09b9130bf8e9056563245656d405e233bcafdbffb645. But with the 'equivalent' javascript code:
var text = "\x00\x44\xb0\x2c\x0b";
var key = "\xd6\xf8\xb0\x2c\x0b";
hash = CryptoJS.HmacSHA256(text,key);
console.log(hash.toString());
I get 13c983b69f82c277815c03d13e90b1ec1e9cbca2b6912ad1f8224f3de8b82130, a different value.
I thought it could be caused by non-ascii character, so I did a quick test:
$text = '';
for($i = 0;$i < 10; $i++){
$text .= chr($i);
}
$key = '';
for($i = 0;$i < 10; $i++){
$key .= chr($i*2);
}
$hash = hash_hmac("sha256",$text,$key, false);
print $hash;
And, javascript equivalent:
var text = '';
for(i = 0;i < 10; i++){
text += String.fromCharCode(i);
}
var key = '';
for(i = 0;i < 10; i++){
key += String.fromCharCode(i*2);
}
var hash = CryptoJS.HmacSHA256(text, key);
console.log(hash.toString());
In both cases, output is c5d7adbbabcec5416c6b7a1f01e17e42d95a529f5bcc805d9b04b93f33994c9d.
This is a big WTF? for me. Could somebody give me a piece of advice of how to continue with this?
Solved. It was a problem with character codes. Instead of this:
var text = "\x00\x44\xb0\x2c\x0b";
var key = "\xd6\xf8\xb0\x2c\x0b";
hash = CryptoJS.HmacSHA256(text,key);
I should indicate CryptoJS that they were Latin-1 encoded strings:
var text = CryptoJS.enc.Latin1.parse("\x00\x44\xb0\x2c\x0b");
var key = CryptoJS.enc.Latin1.parse("\xd6\xf8\xb0\x2c\x0b");
hash = CryptoJS.HmacSHA256(text,key);
I don't know clearly why is this happening, so if somebody could explain it with a little bit of detail it would be great.
Try that:
$text = "\x00\x44\xb0\x2c\x0b";
$key = "\xd6\xf8\xb0\x2c\x0b";
$hash = hash_hmac("sha256",$text,$key, false);
print $hash;
It's proabably because the preg_* functions have a problem with these special characters.
And PHP supports \x12 hex-encoding without any function.

Categories