How to pass string to javascript funciton which contains special characters - php

I have this little php snippet:
// $test='test';
$test='just a test';
echo "<a href=javascript:myfunction($number,$src_req,\"".$test."\")><img style='z-index:$z; src='images/$src'/></a>";
And i have this little ajax snippet...
function myfunction(param1,param2,param3)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse2(xmlHttp.responseText);
}
}
var p1=param1;
var p2=param2;
var p3=param3;
xmlHttp.open("GET", "config/ajax_pop.php", true);
xmlHttp.send(null);
$( '#ResponseDiv2' ).dialog({
height: 140,
modal: true,
position: [490,140],
title:param3,
});
.....
I like to pass my $test php variable to my javascript function, but unfortunatelly if my $test variable contain space character then the JS script doesnt work. If my $test variable contain only one word, then work well.
In the browser when i check the link i see:
a, if $test variable contain only one word, then: javascript:myfunction(1,1,"test")
b, if $test variable contain more then one words then: javascript:myfunction(1,1,"just
Thank you for the help...

Use json_encode(): http://php.net/json_encode
Update: Here's a usage example:
<?php
$number = 1;
$src_req = 2;
$z = 3;
$src = 4;
$test = 'just a test
with spaces and new lines';
echo "<a href=javascript:myfunction($number,$src_req," . json_encode($test) .")><img style='z-index:$z; src='images/$src'/></a>";
If it doesn't work, try to find out in what exact way it's not working. A "Does not work" question is as useful as a "Then fix it" answer.
In any case, mixing PHP, HTML, JavaScript and CSS in one single line of code is not worth the effort even for quick testing. Separarte stuff in functions and files you'll make your life easier.

You must wrap the href itself with double quotes then the value with single quotes:
href=\"javascript:myfunction($number, $src_req, '".$test."')\"

You can escape the string with php function urlencode and can use javascripts unescape to unescape.
you have to parse the third parameter in your js function with unescape ...
as well you can use json as Álvaro G. Vicario mentioned.

Related

Javascript explode and loop

I have created this script to explode numbers from one data-get via php:
var n_polls=<?php echo $t_random_number;?>;
var myArray=n_polls.split(','); //explode
for (i=0;i<4;i++)
{
$("#t_sl_poll_"+myArray[i).hide();
}
The idea is to give some numbers from php for a random poll system, and I want explode this for close all in loop by the id. The problem is, I see something fail into the explode function for javascript, all time giving me nothing. How can I fix this?
Thank you.
Why explode in Javascript when you could have PHP just insert an array?
<?php
$numbers = array(1,2,3,4);
?>
<script type="text/javascript">
var n_polls = <?php echo json_encode($numbers); ?>;
for (i in n_polls) {
$("#t_sl_poll_" + n_polls[i]).hide();
}
There's further optimizations that could be done, but this'd be one place to start.
Take a look at your source. Your error console would tell you the same thing. You're not putting your array (not a number) in quotes, so it fails to compile during runtime:
var n_polls="<?php echo $t_random_number;?>";
//QUOTES! ^ ^
var myArray=n_polls.split(','); //explode
for (i=0;i<4;i++)
{
$("#t_sl_poll_"+myArray[i]).hide(); //Missing bracket
// ^
}
Now it'd compile to
var n_polls="1, 2, 3, 4";
instead of
var n_polls=1, 2, 3, 4; //Useless non-working code - not enclosed in anything
There are two things wrong here.
First: since you apparently hand over a string and not a number from php to javascript you have to write: var n_polls="<?php echo $t_random_number;?>";
Second: as pointed out in the comments already, you have to write $("#t_sl_poll_"+myArray[i]).hide(); to acutally address and element of your array.
your code should work as
var myArray= [<?php echo $t_random_number;?>];
for (i=0;i<4;i++)
{
$("#t_sl_poll_"+myArray[i]).hide();
}

JavaScript and PHP in code - whats the difference?

I have this code in my JavaScript part:
var opConfig = new Product.Options(<?php echo $this->getJsonConfig(); ?>);
The PHP call returns me some string, to make it easy, lets say the string is abcd. So this code results in:
var opConfig = new Product.Options(abcd);
Now, some lines later, I have this code:
this.opConfig = new Product.Options(opconfig);
The opconfig variable has the same string abcd, but the results are different, this.opConfig does not look like it looked before. So is there a difference in how I use the string as param? Something I am missing? For me, it should always be the same call, namely:
new Product.Options(abcd)
Ideas?
Addition: The full call in the JS code looks like that:
var opConfig = new Product.Options({"16":{"26":{"price":5,"oldPrice":5,"priceValue":"5.0000","type":"fixed","excludeTax":5,"includeTax":5},"28":{"price":8,"oldPrice":8,"priceValue":"8.0000","type":"fixed","excludeTax":8,"includeTax":8},"27":{"price":10,"oldPrice":10,"priceValue":"10.0000","type":"fixed","excludeTax":10,"includeTax":10}},"14":{"price":0,"oldPrice":0,"priceValue":"0.0000","type":"fixed","excludeTax":0,"includeTax":0},"15":{"price":0,"oldPrice":0,"priceValue":"0.0000","type":"fixed","excludeTax":0,"includeTax":0}});
The param reaches the called function as object, no idea why. Calling it the other way, the same string seems to reach it as string. Can anybody help?
Change to:
var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');
opconfig is a string variable, so its fine passing that as a parameter.
Whereas your PHP code will render:
var opConfig = new Product.Options(abcd);
abcd is not a string variable. Therefore you need to put this in speech marks so that it becomes a string object. Your output would now be:
var opConfig = new Product.Options('abcd');
If you have new Product.Options(abcd) then abcd is a variable name, not a string. You need to add quotes so that it ends up as new Product.Options('abcd'):
var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');
// OR
var opConfig = new Product.Options("<?php echo $this->getJsonConfig(); ?>");
Either way you need to be sure your PHP output escapes any characters that might "break" the string literal, e.g., single-quotes (in the first one) or double-quotes (in the second one), or newlines (in either).
I can see you're missing quotes:
var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');
Change the below line
var opConfig = new Product.Options(<?php echo $this->getJsonConfig(); ?>);
to
var opConfig = new Product.Options('<?php echo $this->getJsonConfig(); ?>');

Spliting Text Nicely over Multiple Lines (i.e. for titles)

I'm fighting over a way to have text wrap nicely to fit into set div boxes. Browsers wrap the text if it's too long to fit on one line which is expected, but this can often lead to rather nasty looking presentation.
For example, this looks fine:
This is the title
But if I have a longer title, it may end up wrapped like this:
This is a slightly longer
title
As you can see the second one doesn't really look very nice, what I'm aiming for is something like this:
This is a nicer
wrapped title
I know how big the containing DIV will be, so that's not a problematic variable, but I'm trying to wrap my mind around all the possible ways of achieving nicely formatted titles and their flaws. So the question is, what would be the best way of doing this? I can think of a few ways, but they start to get exponentially more complicated if it wraps over more than 2 lines.
EDIT:
I'm currently using this - https://xnode.org/paste/19 - to try and even out the split lines, although I'm sure it's far from perfect.
You can remove the newlines and then use wordwrap function
Sounds like a job for the wordwrap function http://php.net/manual/en/function.wordwrap.php
Try using wordwrap function and give this CSS for the DIV:
div {
text-align: justify;
}
If http://fittextjs.com/ doesn't do the trick, try something along these lines...
Count the characters in your title and decide if it is going to need 1 line, 2 lines 3 lines, etc. (there will be some trial & error involved)
Replace all the spaces apart from where you want line breaks with (non-breaking spaces) and let the browser do the word wrapping.
In other words, in your This is a nicer wrapped title example, there are 29 letters, so you need a break around half way or just after, so replace the first non-breaking space after position 14 or 15 with a regular space ie between 'nicer' and 'wrapped', and that should do the job. Same thing in thirds or quarters for longer lines.
Sorry no code but from the examples you gave above you should be ok coming up with your own implementation.
I've created this jQuery plugin that does what you want
$.fn.prettyBreak = function () {
return this.each(function () {
var element = $(this);
var elementLineHeight = element.css("line-height").replace("px", "");
var elementContent = element.contents();
element.wrapInner("<span style='white-space: nowrap'>");
element.find("br").remove();
var textWidth = element.find("span").width();
element.html(elementContent);
var elementText = $.trim(element.text());
if (element.is(":visible") && textWidth > element.width() && element.height() < elementLineHeight * 2.1) {
var middle = Math.floor(elementText.length / 2);
var before = elementText.lastIndexOf(" ", middle);
var after = elementText.indexOf(" ", middle + 1);
if (middle - before < after - middle) {
middle = before;
} else {
middle = after;
}
var s1 = elementText.substr(0, middle);
var s2 = elementText.substr(middle + 1);
element.html(s1 + "<br> " + s2); // note the space after the tag
} else {
element.html(elementText);
}
if (element.is(":visible")) {
element.css("opacity", 1);
}
});
}
Usage:
$(document).on("ready", function () {
$(".pretty-break:visible").prettyBreak();
setInterval(function () {
$(".pretty-break:visible").prettyBreak();
}, 1000);
});
Github link: https://github.com/SumoSoft/PrettyBreak

Javascript Issue in Header

I'm trying to call an Aweber form code inside of a function in the head of the document. I'm creating a simple link that, when clicked will open up an Aweber form. But it's not working. I'm using the document.write function and have no clue if it's right at all.
Here's the head section code:
<script type="text/javascript">
function aweber()
{
document.write("<script type="text/javascript"
src="http://forms.aweber.com/form/74/1378551674.js"><\/script>");
}
</script>
And here's what I'm including in my document. It's not working -- I think it's a silly syntax issue.
Aweber Form
document.write("<script type="text/javascript"
src="http://forms.aweber.com/form/74/1378551674.js"><\/script>");
Should be
document.write('<script type="text/javascript" src="http://forms.aweber.com/form/74/1378551674.js"><\/script>');
First, you can't put double quotes in a double quoted string:
// see how the syntax highlighting gets screwy here? that's clue #1
var str = "he said "hello""; // bad
var str = 'he said 'hello''; // bad
// Encapsulate with different quotes
var str = 'he said "hello"'; // good
var str = "he said 'hello'"; // good
// Or escape the quotes
var str = "he said \"hello\""; // good
var str = 'he said \'hello\''; // good
And second, JS strings cannot have line breaks in them. You have to manually insert them to avoid syntax errors:
// bad
var str = "a
b";
// good
var str = "a"+
"b";
// good, if you really need a newline character
var str = "a\nb";
var str = "a\n"+
"b";
The quotes around the attributes in in
document.write("<script type="text/javascript" src="http://forms.aweber.com/form/74/1378551674.js"><\/script>");
are not properly escaped. Change
"<script type="text/javascript" src="http://forms.aweber.com/form/74/1378551674.js"><\/script>"
to
"<script type=\"text/javascript\" src=\"http://forms.aweber.com/form/74/1378551674.js\"><\/script>"
All your aweber() function does is make the JavaScript file, 1378551674.js, available to your document. I'm not familiar with Aweber Forms, but I would imagine you have to actually call some function within that JavaScript file to do something?

Passing parameters to Javascript using PHP

I have the following line of code:
My Tweets!
Now while this is working perfectly fine the following line is not:
My Tweets!
Can anyone help me out why it is not working and suggest any changes? The variable I want to pass to the Javascript function is a PHP variable. I have tried the PHP with single quotes and double quotes but it is not working.
You need quotes for both the php side and the Javascript side. You've only got php quotes there.
My Tweets!
looks weird but it should work, though I'm no php expert. Note that if there's any chance that "myid" (on the php side) might contain user-supplied data (like, something that came from an <input> field at some time), or if it's otherwise unpredictable, then it has to be put through something on the server side to make sure that the resulting tag is "clean".
I usually do as following:
<script>
var jsvar = <?=json_encode($php_var)?>;
</script>
After that I can use jsvar under the javascript codes. And for readability I usually place all those assignments in an own script tag.
What you gain by using <?=json_encode($php_var)?> is that you won't need to go on escaping, and it works for arrays and hashes as well as strings, numbers etc...
For example, following php code:
<?php
$php_string = "hello";
$php_array = array( 'a', 'b', 'c' );
$php_hash = array( 'a' => 1, 'b' => 16, 'c' => 42 );
$php_number = 123;
$php_bool = false;
$php_null = null;
?>
<script type="text/javascript">
var js_string = <?=json_encode($php_string)?>;
var js_array = <?=json_encode($php_array)?>;
var js_hash = <?=json_encode($php_hash)?>;
var js_number = <?=json_encode($php_number)?>;
var js_bool = <?=json_encode($php_bool)?>;
var js_null = <?=json_encode($php_null)?>;
</script>
produces the following result:
<script type="text/javascript">
var js_string = "hello";
var js_array = ["a","b","c"];
var js_hash = {"a":1,"b":16,"c":42};
var js_number = 123;
var js_bool = false;
var js_null = null;
</script>
You forgot to Quote your answer. You are echoing the string OK, but you need to ' ' the response so JavaScript will know it's a string. You can use ' or \"
My Tweets!
Uses short echo thing.

Categories