Log in

View Full Version : Passing php variable as Javascript argument



zomb1e
08-05-2012, 11:34 PM
My question is related to both Javascript and PHP

This is supposed to be a simple task. I'm successfully passing 2 php variables to a javascript function.




PHP:
$a; // this is name of employee
$b; // this is address of employee which multiline and is different for every employee

<a onClick="function('<?php echo $a ?>', '<?php echo $b ?>');">LINK</a>

Javascript:

<script language="JavaScript" type="text/javascript">
function(a,b){

}

</script>




But now i've modified my code, added line breaks through nl2br() in $b after fetching it from db, and trying to pass it to function(). Instead of sending it as JS function argument, it prints the $b.




PHP:
$a; // this is name of employee
$b; // this is address of employee which multiline and is different for every employee
$c=nl2br($b);

<a onClick="function('<?php echo $a ?>', '<?php echo $c ?>');">LINK</a>

Javascript:

<script language="JavaScript" type="text/javascript">
function(a,b){

}

</script>




Can anyone please guide me through this. Thanks a lot in advance!!!!!!!!

keyboard
08-06-2012, 12:43 AM
The code you posted wouldn't work, but you said it did work so there must be more code that you're not showing us...

Could you please provide us with the full script?
Or if not, an example of what $a and $b are and the contents of your js function.



This little test script works fine...

<?php
$a = 'Fatber Christmas';
$b = '27 Sunshine Street /n America';
$c = nl2br($b);
?>
<html>
<head>
<script type="text/javascript">
function test(a,b) {
alert(a);
alert(b);
}
</script>
</head>
<body>
<a onClick="test('<?php echo $a ?>', '<?php echo $c ?>');">LINK</a>
</body>
</html>

zomb1e
08-11-2012, 10:10 PM
The code you posted wouldn't work, but you said it did work so there must be more code that you're not showing us...

Could you please provide us with the full script?
Or if not, an example of what $a and $b are and the contents of your js function.



This little test script works fine...

<?php
$a = 'Fatber Christmas';
$b = '27 Sunshine Street /n America';
$c = nl2br($b);
?>
<html>
<head>
<script type="text/javascript">
function test(a,b) {
alert(a);
alert(b);
}
</script>
</head>
<body>
<a onClick="test('<?php echo $a ?>', '<?php echo $c ?>');">LINK</a>
</body>
</html>
Thanks for your reply!

Let me explain to you what I'm trying to do. I want to take input from users in a textarea which could be a number of paragraphs and save it in MySQL db. Now, that's working fine as I've tried it myself.

Now I want to display that information (which i've fetched from MySQL db through queries and saved them in php variables, eg, $a) through a javascript (passing php variables) which is called through 'onClick'.

When I print $a without passing it to JS function it display entire string without any linebreaks, but when I try to pass $a to JS function and print it through an OnClikck event, nothing gets printed. (referring to the below code)



<?php
$a = very long string
$b = "Hello People!!!!";
?>
<html>
<head>
<script type="text/javascript">
function test(a,b) {
document.getElementById('div1').innerHTML=a;
document.getElementById('div2').innerHTML=b;
}
</script>
</head>
<body>
<a onClick="test('<?php echo $a ?>', '<?php echo $b ?>');">LINK</a>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>


Is there a way to ensure that I can print that long string through <div id="div1"></div>.
Also I want to pass $a in a way that all the linebreaks are retained in it (like the way it is present in MySQL db).

I also tried using below code, but this code prints $a when I call onClick event rather than passing it to test() function.



<?php
$a = very long string
$b = "Hello People!!!!";
$a=nl2br($a);
?>
<html>
<head>
<script type="text/javascript">
function test(a,b) {
document.getElementById('div1').innerHTML=a;
document.getElementById('div2').innerHTML=b;
}
</script>
</head>
<body>
<a onClick="test('<?php echo $a ?>', '<?php echo $b ?>');">LINK</a>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>


Can you please help. I'd really appreciate any method or suggestion!!!

keyboard
08-12-2012, 01:15 AM
I'm busy at the moment, but I'll have a look at it later... (probably tonight)

bernie1227
08-12-2012, 02:36 AM
how are you inserting the line breaks? you could manually put in <br /> tags or you could generate a brek tag evvery time a line reaches a certain length.

keyboard
08-12-2012, 06:52 AM
Bernie -
nl2br() converts all new lines to <br/> tags...

bernie1227
08-12-2012, 06:54 AM
True, but still it is probably a good idea to try it with actuall br tags in order to see if that changes anything.

keyboard
08-12-2012, 08:46 AM
After looking through your code, I can't see anything wrong.... Would it be possible for you to provide us an example of $a?

bernie1227
08-12-2012, 08:58 AM
Same with myself, I can't seem to see why it would print the $a variable, as there is no code in there which would do that, is this the full code you are using?

@keyboard
Father isn't spelt with a b

traq
08-12-2012, 04:44 PM
zomb1e, as much as is possible, please show us the actual code you are using in your testing. copy-and-paste is a great help. this:
<?php
$a = very long string
$b = "Hello People!!!!";
?>is obviously not any part of the code you're actually using - if it were, you'd be getting a fatal parse error.
Sharing the actual code will help prevent confusion while people are trying to help you figure things out.

One more suggestion:

When you run this, check the output source to make sure PHP is printing what you want it to.

It's very helpful to remember that php and javascript don't actually interact - PHP is just writing text - so, really, you're not "passing variables" - you're just "writing text."

(BTW, the code you posted -after I fixed the $a line - works just fine for me.)

zomb1e
08-12-2012, 09:31 PM
Thank you everyone four your suggestions!!!

I know that $a does not contain the value specified in above example, but I just wanted to give a hint that I'm saving very long string in $a;

One of the examples of $a is in double quotes below (this is just an example and its length can increase vitally as per user input),

"Starbucks being an already established company in the market will offer maximum competition to Costa Coffee. Also Starbucks being a global brand possess enough resources in order to make sure that it is able to retain its identity in the market even if the level of competition rises to a maximum possible extent. It is due to this reason Costa Coffee will have to adopt highly diversified measures in order to make sure that it can capture enough market shares to attain its breakeven point in previously determined time period.

In these conditions Costa Coffee will face enough difficulties because of already present brands, like Starbucks, which do not have to make significant efforts in order to retain market possession. Such companies make direct use of their brand equity. In these conditions, only tactic that will help Costa Coffee to generate income will be through offering quality service to its customer at cheaper rates. As company senses rise in profitability, it may gradually increase its prices. Along with this strategy, Costa Coffee will have to adopt suitable marketing strategy that will help it in attracting more number of customers in pertaining environmental condition.

Another factor that Costa will have to take into account is to act appropriately over return strategy adopted Starbucks after it senses threat over its market possession. This factor will make a deep impact over functioning and planning performed by policy makers of Costa Coffee. Also Costa Coffee will have to deviate substantially from its pre-defined strategic measures that will be highly dependent over external environmental conditions and goals that company has to achieve working under those conditions. "

I want to display this text in this exact format (present in my MySQL db) using <div id="div1"></div>, which I'm calling through Javascript function. And I'm passing this values in Javascript function through php variables.

Also when I modified this string (removed all the linebreaks and keeping it a single line entry) and tried to display this string, it worked absolutely fine. That's why my question is how to display very long text which include linebreaks.

bernie1227
08-12-2012, 09:40 PM
My first suggestion is to try the text with actual <b /> tags, and see if that works. If it doesn't, then we can assume it is a problem with nl2br

zomb1e
08-12-2012, 09:52 PM
Thanks for your quick response!

Can you please elaborate how do I do it. Means what exactly are you suggesting.

A little example would be really helpful.

bernie1227
08-12-2012, 09:57 PM
So when you actually give a value to the $a variable, put <br /> tags instead of actually putting a line break. Eg:


Lorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsum
<br />
Lorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsumLorem ipsum
<br />

zomb1e
08-12-2012, 10:21 PM
Hey bernie1227 you are right, I used your suggestion and its working fine when I use <br> tag within string. But its not working when I try to insert these tags through nl2br() function. That means this is the problem with nl2br() function.

But I can't do this manually all the time as I want php to fetch data from db when OnClick request is sent. Is there an alternative to nl2br() which will solve my problem.

bernie1227
08-12-2012, 10:41 PM
You could trya string replace, ie:


$string = str_replace("\n\n", "<br />", $string);
$string = str_replace("\n", "", $string);

This replaces all line breaks with br tags

traq
08-13-2012, 12:53 AM
Okay - what we're looking at, here, is that nl2br() (http://php.net/nl2br) doesn't (and is not supposed to) replace newlines: it inserts <br> in front of them.

// this:
"This is a string with
a newline."

// turns into this:
"This is a string with <br>
a newline."

// notice the newline is actually still there. What you really want is:
// "This is a string with <br>a newline."
Bernie's got the right approach: get rid of the newlines.
However:

$string = str_replace("\n\n", "<br />", $string);
// this doesn't work unless there are two \n newlines next to each other
// (certainly possible, but not what we're really looking for).

$string = str_replace("\n", "", $string);
// this doesn't work either, as it will leave any \r newlines intact,
// and so still mess up the javascript engine.
I'd recommend still using the nl2br() function, since (as a native php function) it will be faster, and also less fragile
(covers any of \r\n, \r, \n, or \n\r):
$string = str_replace( array( "\r","\n" ),'',nl2br( $string ) );

btw, the reason newlines mess things up (in case you didn't know) is that javascript treats newlines like semicolons: end of a statement. Since they're not intended to be, it causes parse errors.

jscheuer1
08-13-2012, 04:08 AM
This works and should be adaptable to whatever you're trying to do:


<?php
$b = "The quick red fox
jumped over the slow brown dog.";
$brofb = preg_replace('/\n|\r/', '', nl2br($b));
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function assignb2el(b, id){
document.getElementById(id).innerHTML = b;
}
</script>
</head>
<body>
<a href="#" onclick="assignb2el('<?php echo $brofb; ?>', 'tdiv'); return false;">Show b/w linebreaks</a>
<div id="tdiv"></div>
</body>
</html>

Or if you're expecting unescaped quotes in the string:


<?php
$b = "The quick red fox's mother
jumped over the slow brown dog.\n . . . Again -\r wouldn't you know?

The End";
$brofb = addslashes(preg_replace('/\n|\r/', '', nl2br($b)));
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function assignb2el(b, id){
document.getElementById(id).innerHTML = b;
}
</script>
</head>
<body>
<a href="#" onclick="assignb2el('<?php echo $brofb; ?>', 'tdiv'); return false;">Show b/w linebreaks</a>
<div id="tdiv"></div>
</body>
</html>

traq
08-13-2012, 04:45 AM
Or if you're expecting unescaped quotes in the string...

good point.

zomb1e
08-13-2012, 10:41 PM
Thanks guys, it wouldn't have been possible without your support!!

I really appreciate help from all you guys, but I figured out a better way to do this. I used Ajax and now my problem is solved.

But you guys really rock!!!

keyboard
08-13-2012, 10:47 PM
I'm glad you figured it out zomb1e...

Remember -

If this thread is finished, please set it to resolved.
You can do this by editing the first post within the thread - Pressing go advanced - Then where it says no prefix, selecting resolved then save.

hotlikedimes
11-16-2012, 05:29 AM
Hey, I'm sorry to bump this old thread, but this is the only thread I've found in hours of searching that has actually given me the answers I've needed, but when I run my code (I'll link it below) the output that I get is <?php echo $a ?> and then <?php echo $c ?> in another alert window... I'm extremely miffed why this is happening.. Here's muh code :


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<?php
$a = 'Fatber Christmas';
$b = '27 Sunshine Street /n America';
$c = nl2br($b);
?>

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="Kenneth So - Automotive and Nightclub Photography">
<meta name="keywords" content="automotive photography, car photography, nightclub photography, rave photography, club photography, edm photography, car pictures, car images, automotive, cars, nightclub, rave, edm, photographs, digital photography">
<meta name="abstract" content="Kenneth So - Automotive and night club photography.">
<meta name="robots" content="index,follow">
<meta name="resource-type" content="document">
<meta name="revisit-after" content="5 days">
<title>Kenneth So Photography</title>
<link rel="stylesheet" href="kennethsostylesheet.css" type="text/css">
<link rel="shortcut icon" href="Photos/favicon.png" type="image/png">

<script type="text/javascript">
function test(a,b) {
alert(a);
alert(b);
}
</script>

<script type="text/javascript" src="picScript.js"></script>
</head>

<body>

<a onClick="test('<?php echo $a ?>', '<?php echo $c ?>');">LINK</a>



<div id="headerBar">
<div id="logo">
<a href="javascript:void(0)" ><img src="Photos/FinalizedLogo.png" alt="logo" height="100px" width="400px" onclick="setNum(1)"></a>
</div>
<div id="titleBar">
<p>
<a href="javascript:void(0)" onclick="setNum(1)">Home</a> |
<a href="javascript:void(0)" onclick="setNum(2)">Automotive</a> |
<a href="javascript:void(0)" onclick="setNum(3)">Nightlife</a> |
<a href="/about.html">About Me</a> |
<a href="/contact.html">Contact</a>
</p>
</div>
</div>
<div id="imageBox">
<div id="imageView">
</div>

<div id="imagePreview">
</div>
</div>
</body>
</html>


setNum(); is a function in the picScript.js file. TIA!!! (and sorry for bumping the old thread but it's exactly what I needed)