views:

166

answers:

3

I am trying to pass a variable frm php to a javascript function, however a space keeps getting appeneded, and I can not see how.

The relevant php code snippet:

<p><a href='#' onclick=\"makewindows(" . $html . "); return false;\">Click for full description </a></p>".$brand."
     <p><a href=\"#\" onclick=\"deleteRec('".$ARTICLE_NO."', '".$brand."', '".$pg."', '".$nextArticleNo."')\">DELETE</a>

$brand is what I want to pass, and deleteRec is the name of the function.

At the end of the first line I am echoing out brand before the link to deleteRec, and it contains no space. In my test case, it is set to simply 'o'.

The link that is genereated for deleteRec however, clearly contains a space, and I don't know where it is coming from.

<a href="#" onclick="deleteRec('190274380300', ' o', '2', '250343889611')">DELETE</a>
+1  A: 

Change:

<p><a href=\"#\" onclick=\"deleteRec('".$ARTICLE_NO."', '".$brand."', '".$pg."', '".$nextArticleNo."')\">DELETE</a>

to:

<p><a href=\"#\" onclick=\"deleteRec('".$ARTICLE_NO."', '".trim($brand)."', '".$pg."', '".$nextArticleNo."')\">DELETE</a>

and tell us how it goes.

Click Upvote
"At the end of the first line I am echoing out brand before the link to deleteRec, and it contains no space"
bzlm
@bzlm, debugging is all about not trusting such assumptions. He hasn't posted enough code to be sure that no space is in the variable.
Paul Dixon
Either way if you do a trim on $brand it should fix it. Without access to all of your code it's not possible for us to tell why exactly there is a space added to $brand :)
Click Upvote
why and where is the space coming from however? The contents of $brand right before the call to deleteRec contains no space, how is one getting added in between?
Joshxtothe4
Without seeing the code that's setting $brand, how are we supposed to answer that?
ceejayoz
+2  A: 

Do var_dump($brand) and look closely - there's almost certainly a space in it!

In which case, you can guard against it with trim

$brand=trim($brand);
Paul Dixon
var_dump($brand); returns string(1) "o" , definitely no space.
Joshxtothe4
+1  A: 

Try do echo the following:

echo "--$brand--";

This way you'll be able to see if there are any spaces in the variable.

As a general matter of style, I would change second link from:

<a href=\"#\" onclick=\"
      deleteRec('".$ARTICLE_NO."', '".$brand."', '".$pg."', '".$nextArticleNo."')\">DELETE</a>

to:

<?php
$deleteRecArgs = "'$ARTICLE_NO', '$brand', '$pg', '$nextArticleNo'";
?>
<a href="#" onclick="deleteRec(<?php echo $deleteRecArgs?>)">DELETE</a>

It's easier to read and maintain.

ya23
Yep, echoing out like that shows there is no space!
Joshxtothe4
Then it's just bizarre :) Bug in php or browser caching something?
ya23