javascript url call working randomly - javascript

I have a javascript function which I am calling from php code. The function is not working if the argument passed is text; it works fine for integer argument. There is probably some very basic issue I am missing. Please point that out.
function make_entry(game)
{
window.location.href="generate.php?game="+game;
}
<? echo "<div style='text-align:center'>Click <a onclick='make_entry(".$game.")' style='cursor:pointer'><b>Here</b></a> to download your Certificate.</div>"; ?>
php code is fine in my humble opinion

you have to place the content of $game between quotes in order to work with a string
onclick='make_entry("\".$game.\"")'
keep in mind, of course, that this way you'll be alway passing a string to the function.
And $game must not contain double quotes or again the JavaScript code will fail.
Just consider your JavaScript code when the content of the variable is actually put in place.

You need to escape the double quotes around your $game variable if the argument is to be passed as text.
<?php echo "<div style='text-align:center'>Click <a onclick=\"make_entry('$game')\" style='cursor:pointer'><b>Here</b></a> to download your Certificate.</div>"; ?>
See fiddle: http://phpfiddle.org/lite/code/rq9-x8e

<? echo should be <?php echo

Related

php writing a onkeyup= function

I am writing a php script which generates html with a javascript onkeyup event, as such:
// generate the function text
$fn_text = "checkContentQuizAnswer(\"#".$var_name."\",\"".$equation_solutions_array[0][0]."\",\"{'incorrect_values':[";
for($r=1;$r<count($equation_solutions_array);$r++) {
// THIS ISNT WORKING CORRECTLY, NEED A BETTER WAY TO PASS INCORRECT INFO
$fn_text .= "{'equation':'".$equation_solutions_array[$r][0]."','message':'".$equation_solutions_array[$r][1]."'}";
if(($r+1)<count($equation_solutions_array)) {
$fn_text .= ",";
}
}
$fn_text .= "]}\")";
However this isnt working... the code it generates looks something like this:
onkeyup="checkContentQuizAnswer("#theonlyvariable","27.62*5","{'incorrect_values':[{'equation':'27.62+5','message':'you added 5'},{'equation':'27.62-5','message':'you subtracted 5'}]}")"
however, it hasn't been working... the errors have included complaints about missing }'s, MathJax (an eval() style library) is undefined.
Im sure that it is how I am parsing the onkeyup part of the tag but i cant get the combination/syntax correct.
Can anybody see a glaring problem? :S
Thanks
Alex
Although you are escaping the quotes in the PHP file, the quotes in the javascript parser are not being escaped. Change the quotes inside the onKeyUp to single quotes to fix this. You will also need to escape the quotes in the JSON as well - the json_encode() function can help with that. You need to output something like:
onkeyup="checkContentQuizAnswer('#theonlyvariable','27.62*5','{\'incorrect_values\':[{\'equation\':\'27.62+5\',\'message\':\'you added 5\'},{\'equation\':\'27.62-5\',\'message\':\'you subtracted 5\'}]}')"

Passing Multi-line PHP variable to Javascript function

I'm trying to pass a PHP variable holding a text value (html content) read from SQL database to a Javascript function. I'm trying all different approaches such as json_encode(utf8_encode()) and preg_replace() but none of them seem to work.
Here's my code:
<?php
$db = new PDO('mysql:host=localhost;dbname=ramtin_data;charset=utf8', 'root', '');
foreach($db->query('SELECT * FROM posts') as $row)
{
$qtitle = $row['title'];
$qcontent = $row['content'];
$qpage = $row['page_id'];
$qcontent = json_encode(utf8_encode($qcontent));
echo "<script type='text/javascript'>
displayPost('$qtitle', '$qcontent');
</script>";
}
?>
Just want to mention that when I insert a row in my database with a simple line (including "and /) in the content field, the above code works.
I've also tried the following code and got the same result:
$qcontent = preg_replace('/\v+|\\\[rn]/','<br/>', $qcontent);
The value inside the content field in the database is the following string:
<img src="images/death_truck_titleDisplay.jpg" width="400" height="140" class="globalImageStyle" /><p class="postBodyContentParagraph">The work for another Construct2 game "Death Truck" has been started.</p><p class="postBodyContentParagraph">I've had the idea since a few weeks ago and I'm amazed that how much it had developed into better shapes and more complex gameplay ideas only through the first weeks that I've started working on the graphics and the game codes/logic.</p><p class="postBodyContentParagraph">I'm actually done with the truck and pedestrian graphics and movement codes (plus the interaction code between pedestrians and the truck) and have included the game in the projects page as a Work In Progress. You can check some of the graphics and the idea of the whole game (plus some gameplay ideas) in the projects page.</p>
How should I pass the above value to the displayPost() Javascript function?
UPDATE
The problem was with the single quotes inside the value. The accepted solution suggested all 's to be replaced with \' using $qcontent = str_replace("'", "\'", $qcontent); which worked perfectly.
The result however was quoted by json_encode() which I found the easiest way to remove the wrapping "s to be using content.slice(1, content.length - 2) (content is the second parameter which refers to $qcontent in the PHP section of the code) inside of the Javascript function.
Because you wrap your output in single quotes ' you need to escape those.
$qcontent = str_replace("'", "\'", $qcontent);

My php is not interpreted in my Javascript

I create my HTML this way
$('<form>')
.attr('method',"POST")
.attr('action',"postMetier.php?metier="+"<?php echo $GET['metier'] ?>")
How can I make the echo work ?
$GET variable doesn't exists, correct name is $_GET.
.attr('action',"postMetier.php?metier="+"<?php echo $_GET['metier'] ?>")
^
Of course, you JS code has to be in PHP file (or other which is parsed by server).
it is not $GET['metier'] but $_GET['metier'], if there is value recieved on your page by get method then echo $GET['metier'] will give you some value.
Note: if $GET['metier'] is your defined variable, then it should have some value in it so that it can be echoed.

How to encrypt php variable in javascript?

When I creat a php variable in javascript, I use this method:
var jArray = <?php echo json_encode($myArray); ?>;
It's very good but if i view the source code, ther is my full array in the script area.
My problem is that, my php array contains secret data, and I want to use this data in javascritp.
How can I hide from my sourc code, or what can I do?
I tride javascript obfuscation but it can't work with <?php ?> tag.
Thanks!

PHP - Unable to send JSON correctly

I'm not sure why this isn't working, as a lot of the examples on the internet suggest doing it this way. Anyway, I have a SQL result that I've converted to JSON and now I'm trying to use that with Javascript.
json_encode($test, true); ?>
<script type="text/javascript">
var obj = (<?php echo $test; ?>);
alert(obj.toSource());
</script>
This does not work and Chrome gives me an error of "illegal character" and the Javascript variable somehow displays some x-debug HTML from the PHP server:
If I simple echo the JSON out to display on the webpage that works fine without any errors. What am I doing wrong?
Do it like this:
$test = json_encode($test, true);
json_encode doesn't change the variable in place.
You're doing a couple of things wrong here..
json_encode($test, true);
I think you're probably thinking of json_decode, but the second parameter to json_encode is supposed to be a bitmask of options. Passing true here is probably wrong.
#ElmoVanKielmo is also correct, the variable doesn't change because you call a function, you must reassign the variable to the return value.
You got hmtl that looks line an xdebug error/notice message. Fix that before you proceed! (You cut out the part where the message is put).
Additionally you do not encode $test correctly. json_encode returns the changed value and does not modify it by reference.

Categories

Resources