Receiving and sending back json data in PHP - javascript

I am sending data from services.js coming in as a json encoded string in the following format to myPhp.php:
{"Name":"alpha"}
I want to gather this data and send back to the services.js as it came back in json form adding beta to the string as in:
{"Name":"alpha beta"}
myPhp.php
<?php
$a = $_POST[data];
$b = json_decode($a);
$c = $b.Name + "beta";
echo ($c);
?>

The "." notation is not used in PHP to access / set properties - more like Javascript and you need to have quotes around the $_POST variable ~ unless data is defined as a constant. I think you could try something like this though.
<?php
$b = json_decode( $_POST['data'],true );
$b['name'].='beta';
echo json_encode($b);
?>

<?php
$a = $_POST[data];
$b = json_decode($a);
$c = $b['Name'] . " beta";
header('Content-Type: application/json');
echo json_encode($c);
?>

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.

'unexpected token: identifier error' - assigning php json array type variable value to a javascript function from php code

I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>

Using PHP to stringify JSON, but having syntax errors

I'm utilizing PHP to stringify input from my form to a JSON. It's currently formatting it like this
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf#asdf","age":"21","gender":"Male","submit":"Submit"},
But it should look more like this, right?
[
{"name":"asfd","username":"awsf","email":"kean","age":"21","gender":"Male","submit":"Submit"},
{"name":"asdf","username":"asfd","email":"asdf#asdf","age":"21","gender":"Male","submit":"Submit"}
]
Here is my current php. What should I do to make it stringify correctly?
<?php
if (isset($_GET['name'])){
$json_data = json_encode($_GET);
// var_dump($json_data);
$file = file_put_contents('data.json', $json_data."," , FILE_APPEND |
LOCK_EX);
?>
<script type="text/javascript">
ChangeName(<?php echo("'".$_GET['name']."'") ?>);
</script>
<?php } ?>
The only way to do this is to read data from the file first, decode it, append the new array to that data and encode it again to json and put it in the file, sort of like this:
<?php
if (isset($_GET['name']))
{
$data = json_decode(file_get_contents('data.json'), true);
$data[] = $_GET;
$json_data = json_encode($data);
$file = file_put_contents('data.json', $json_data);
}

How to preserv php string to javascript

I am trying to copy a string in a php array to localStorage and the string is a date in this format: 2016-06-15
But the string becomes calculated before stored.
How do I preserv it as a string?
Example:
<?php
$test = array('2015-10-05','20151005');
echo $test[0]."<br>";
echo $test[1];
echo '<script>localStorage["test1a"] = '.$test[0].';</script>';
echo '<script>localStorage["test2a"] = '.$test[1].';</script>';
?>
<script>localStorage["test1b"] = "2015-10-05";</script>
<script>localStorage["test2b"] = "20151005";</script>
This will output:
2015-10-05
20151005
And in localStorage:
test1a 2000
test1b 2015-10-05
test2a 20151005
test2b 20151005
<?php
$test = array('2015-10-05','20151005');
echo $test[0]."<br>";
echo $test[1];
echo '<script>localStorage["test1a"] = "'.$test[0].'";</script>';
echo '<script>localStorage["test2a"] = "'.$test[1].'";</script>';
?>
<script>localStorage["test1b"] = "2015-10-05";</script>
<script>localStorage["test2b"] = "20151005";</script>
Note the Additional Quotes added '"' wrapping the array variable.
To explain why it does not store the value but calculate it is because you are throwing a string at browser and it interpretes as HTML or Javascript in this case.

SyntaxError: unterminated string literal var address = "

I've this problem at the var address line, i think to have write all correctly or not?
<?php for ($i = 1; $i <= count($data); $i++) { ?>
var address = "<?php echo $address[$i].','.$city[$i].','.$region[$i] ?>";
alert(address);
<?php } ?>
You're generating javascript with php and the error you get comes from the javascript part, not php. I guess that one of your variables like $address contains something that isn't valid in js strings, like a newline. The best practice is to use json_encode to encode values for use in javascript:
var address = <?php echo json_encode($address[$i].','.$city[$i].','.$region[$i]) ?>;

Categories