I am trying to store php value in my javascript variable. But this code is giving me syntax error. Is the code correct ?
var b = <?php echo $tagValue;?>;
alert("B is " +b);
You have to make sure that your webserver interprets that file as a php file. then you have to adapt your code, because it looks like you could have an error in your js code in the end:
var b = "<?php echo $tagValue;?>";
alert("B is " +b);
(I have added quotes). Does not apply, if you are sure that $tagValue is only numeric.
In case you don't really know what kind of value your $tagValue is or you simply want to make sure you won't fail you should use json_encode($tagValue):
var b = <?php echo json_encode($tagValue);?>;
alert("B is " +b);
Please note that in case $tagValue is an array/object your js-alert won't be very usefull :)
Easiest way i've found to do it without worrying about character escaping or XSS is to convert the contents of the variable to JSON. All it takes is to echo json_encode($tagValue); instead of echo $tagValue;
make a function maybe can help u.
this is an example
// your php code
$tagValue = 'value';
getValue($tagValue);
Related
I am doing the following:
var test = <? echo $variable; ?>
and I want to append test:
$("#div").append(test);
My problem is that $variable might have '' or "" within it self. This means variable can be, for example
$variable = "<div style='some:style;'>Some test</div>"
So, when I put this in javascript it becomes
$("#div").append(<div style='some:style;'>Some test</div>)
without double quotes (throwing an error), which I try to improve:
$("#div").append("'"+<div style='some:style;'>Some test</div>+"'")
which won't work either way with ' ' or " " because it breaks the specials within the string fragment, stopping ' or "... can someone walk me through how this can be done?
EDIT
I'm sorry MY BAD my problem is that $variable actually has a function called inside, so that's how it becomes:
$("#div").append(<div onclick="some_function('string parameter')" style='some:style;'>Some test</div>)
That's it. How exactly can I do this?
Use json_encode:
$variable = json_encode("<div style='some:style;'>Some test</div>");
or with the function:
$variable=json_encode('<div onclick="some_function(\'string parameter\')" style="some:style;">Some test</div>');
I want to generate a JSON array with PHP, but it doesn't work well.
My PHP array looks like this:
protected $resultArray = array("1.0" => 0, "1.3" => 0);
then I do this:
return json_encode($resultArray);
but then i've got this:
var array = [{"1.0":2,"1.3":1}];
Why is " replaced with "?
quot; is a quote character (") encoded as HMTL. json_encode() does not produce HTML encoded sequences.
Replace return with echo in return json_encode($resultArray); and you'll see this for yourself.
Most probably the returned string is passed further to a function that runs it through htmlspecialchars() or htmlentities() and this is the correct way to work with it if you put it into an HMTL context.
Use a different viewer class if you need to output only the json_encode()-ed string. I don't know TYPO3 but I guess you should use JsonView; pass it $resultArray as-is and it will call json_encode() for you.
I think you may using etended library for example in wamp server I tested this code and it's work fine
$str = "<div style='position:relative'><img src='/assets/ui/success.png' /><span
style='position:relative;top:-15px;'>Nachricht empfangen!</span></div>";
echo json_encode(array('prompt' => $str));
//output
//{"prompt":"<div style='position:relative'><img src='\/assets\/ui\/success.png' \/><span style='position:relative;top:-15px;'>Nachricht empfangen!<\/span><\/div>"}
Thanks guys for help!
The solution is (only for typo3). To get a properly correct JSON-Array in the view the JS code has to be improved the following way:
var array = {f:format.htmlentitiesDecode(value:chartarray)};
I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;
Im wondering how to catch mysql row in javascript, i tried to do that this way:
var x = <?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>;
alert(x);
But this is not working. Any solutions? Sorry if this questions seems to be lame but i not the best in php/js, but have few things to do.
You should enclose the output of PHP in single quotes if you want it to be treated as a string in javascript. Like this:
var x = '<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email=\'$email\'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>';
Or alternatively, replace echo $wiersz[0]; for echo "'". $wiersz[0] ."'";
Try this
<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
$w=$wiersz[0];
mysql_close (notimportant);
?>;
<script>
var x =<?php echo $w ?>
alert(x);
</script>
If you want to pass an array from PHP to jquery/javascript, the best way would be using JSON. Pseudocode:
var x=JSON.parse(<?php echo json_encode($array); ?>);
<script type="text/javascript">
setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>
and then creating that function in your .js file to utilize those values and do what you need.
function setVariables(name, id){
var tag_name = name
var client_id = id
//Operations that need these values.
}
write bundles to javascript!
Personally whenever transferring initilisation data from PHP to the client I find it best to combine the data into an array, and use casting and json_encode (as per Helpful's answer) to make a final structure that is nice and easy to use on the JavaScript side. This saves echoing different variables all over the place, and will automatically handle any type and escape syntax that is required i.e. wrapping strings with quotes, or back-slashing internal quotes in strings.
<?php
$export = array();
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
mysql_close (notimportant);
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
?>
var data = <?php echo json_encode((object) $export); ?>;
Obviously the above is a little overkill for just one small value, however, if there ever became more than one value — something that could quite easily happen after further coding — it would be very easy to extend:
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
$export['something_else'] = 54321;
Then all you need do to access these values in JavaScript is:
data.x
data.something_else
why use an array and why cast to an object?
The reason why I use an associative Array on the PHP side is because I find writing to arrays cleaner in PHP than Objects — not a huge fan of the -> notation. Also instantiating an Array is easier and seemingly more native than an Object in many versions of PHP. I then cast to an object before writing to JavaScript because I find the opposite is true in JavaScript, it's easier and nicer to read when accessing objects rather than arrays. This is all personal taste however.
NOTE: When defining your keys in the $export array you should be wary to keep to standard variable naming conventions i.e. either use camelCase/interCaps or convert spaces to underscores. Whilst you can get away with using any characters, even spaces, it will mean accessing the data from the JavaScript side becomes more cumbersome.
another thing to bear in mind
When setting variables in JavaScript it's often seen as a bad thing to pollute the global namespace. This basically means writing variables at the top level of run-time, that attach to themselves to global Object (usually Window), so that they are accessible by every bit of JavaScript code that runs in that execution. It is seen as bad because unless you use a likely unique variable name, collisions with other code can occur i.e. if both bits of code rely on the same global variable.
If you just output your data var at the top of your script it will become part of the global namespace, and using something as bland as data would be a prime example of something to avoid. It may not matter at all for small projects that aren't going to be extended or worked on by multiple coders, but it is always a good idea to get into the habit of avoiding this.
You can of course just use a variable name that is more unique to your project e.g. myProjectData, or if you have an over-arching namespace that defines your project i.e. examples of which would be jQuery, JSON, console; you could attach it to that e.g. Project.data.
However, if you wanted a more general approach you can also do this by wrapping your JavaScript code in an anonymous function.
<?php
$export = array();
$export['random_value'] = 'Where\'s my monkey?';
?>
(function( data ){
/// data will only be available inside this function
/// or to other sub functions defined inside this function.
console.log(data.random_value);
})(<?php echo json_encode((object) $export); ?>);
With the above code you should end up with your JavaScript always having a nice bundle of values to access, properly escaped and formatted, that have come straight from PHP in an easy way, and that doesn't pollute the global namespace.
WARNING: Obviously it should be noted that if you use the above anonymous wrapper method and you call in any other script files within your page, they wont be able to access data unless you pass the object to that code in some way. This is why people often prefer to have an over-arching namespace object for their project i.e. MyProject.data. However you do not necessarily have to do this — due to the benefit of having all your values bundled up in a singular JavaScript object — because passing it to other code is as simple as sending one variable as a parameter to a function i.e. other.code(data)
I have a string that contains php code I am trying to find a way to remove the php code from the string.
text = '<?php // This is a test sample ?> This is a description';
text.replace(/\<\?.*\?\?\>/, "");
I am not the best with regex. Any help is greatly appreciated.
A very naive approach (assuming php code will have no ternary operator, and inner comments will have no question symbol, ;)):
var s = '<?php // This is a test sample ?> This is a description'
s.replace(/<\?php\s*[^\?]+\s*\?>/g, '')
// output: " This is a description"
the php will execute before the javascript ever gets a chance to do it's thing on the php code. You can't use javascript to change php code. (Although it does work the other way around.)