JavaScript and PHP in code - whats the difference? - php

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(); ?>');

Related

firefox complaining about valid json... invisible invalid character?

I'm writing a php script that needs to load a 2D array into a js variable as json. First i make the array then use json_encode to turn it into a string. Then I run a small bit of js to get it accessable on the client side. Like so:
$sBaseData = Filters::$sFilterBaseTypeData;
$sBaseData = str_replace('\r',' ',$sBaseData);
$sBaseData = str_replace('\n',' ',$sBaseData);
$sBaseData = str_replace('\t',' ',$sBaseData);
echo <<<HTML
<script type="text/javascript">
var validation_data = JSON.parse('$sBaseData');
</script>
HTML;
Firefox complains about an unexpected character here:
var validation_data = JSON.parse('{"enumeration":{"js":"","msg":""},"date":{"js":" var parts = widget.value.split('-'); var d = new Date(parts[0],parts[1],parts[2]); PASS = (d.getDay()>=1); ","msg":"Invalid date. Please Enter a date in the format: YYYY-MM-DD"},"text":{"js":"","msg":"what did you do?"},"integer":{"js":"if (isNaN(widget.value)) { PASS = false; } else { intVal = parseInt(widget.value); PASS = (widget.value == intVal); } ","msg":"Please enter an integer value"},"decimal":{"js":"PASS = isNaN(widget.value); ","msg":"Please enter a number"},"group":{"js":"","msg":""},"dealer":{"js":"","msg":""}}')
I tried using http://jsonlint.com/ to find out which character was at fault but it says it's all valid and wonderful. I replaced some characters that were causing issues, is there anything else I should be replacing?
The problem is you have ' in your string while you are using ' to quote the string.
If your json string is valid, you don't need to parse it even. The below will work.
echo <<<HTML
<script type="text/javascript">
var validation_data = {$sBaseData};
</script>
HTML;
Uh...
var parts = widget.value.split('-');
Putting that in a string that uses single quotes will break it. Use a JSON encoder to output your JavaScript literal.
Your JSON is valid but in your js code the simple quote closes the parse function's argument.
Try like this:
"date":{"js":" var parts = widget.value.split(\'-\');

transfer a Variable from php to js

I got really confused when i tried to transfer variables from php to js.
everything is fine when i try to get value using an id
for example:
var name = $("#name").val();
but my question is, if i want to convert for example this variable:
$id = 182938; //the id of the user
to this variable:
var id;
this question might be dumb... maybe easy for you, but not for me :p
I have looked it up and only found something like this anywhere i looked for:
<?php
$number = rand();
?>
<script language="javascript">
var num = <?php echo $number ?>
</script>
Does it have the same affect as passing down the value?
Thanks!!
Not quite. Encoding as JSON will ensure that it is a valid JavaScript literal.
var num = <?php echo json_encode($number) ?>
what the code does is:
<?php
$number = rand(); //assign random number to $number. let's say it's "3"
?>
//then these are printed on the page normally
<script language="javascript">
var num = <?php echo $number ?> //the $number is echoed at this position
</script>
and then the browser receives:
<script language="javascript">
var num = 3;
</script>
You have to generate syntactically VALID javascript. PHP can echo text into ANY part of the page it's generating, but that doesn't necessarily mean it's actually USABLE text. In your case, you've forgotten a ;, so your generated javascript is actually a syntax error:
var num = <?php echo $number ?>;
^--- missing
The same sort of thing occurs when you're outputting text. Consider where you're storing someone's name into a variable:
<?php
$name = "Miles O'Brien"; // <-- note the single quote
?>
<script>
var name = <? php echo $name ?>;
</script>
This LOOKS ok, but it'll actually generate yet another syntax error:
var name = Miles O'Brien;
there's no quotes around the whole string, and the embedded quote will START a string in javascript, leading the JS interpreter to complain about an undefined variable "Miles", an undfined variable "O", and an unterminated string literal.
Instead, the PHP should have been:
var name = <? echo json_encode($name) ?>;
The JSON encapsulation guarantees that you're embedding syntactically valid Javascript values.

how to pass array string in JavaScript function from PHP end as a argument?

I am getting the error missing ) after argument list in my Firebug console.
emissing ) after argument http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc7/s720x720/393131_320846714645076_100001592501599_911297_470580896_n.jpg
My question is how to pass $char_data variable in JavaScript function as a argument
Define php variable:
<?php
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
$div = "graph";
?
Call JavaScript function with define argument
<script>
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
</script>
A function of JavaScript
<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>
Rather than creating an array out of a string in javascript, why not just just get the PHP to output it as an array to start with?
Just add an extra set of [] which javascript reads as an array.
$chart_data = "[['NBA',1],['NFL',2],['MLB',3],['NHL',4]]";
then ditch the quotes on the output (which are responsible for causing the error messages)
dynamicChartArray('<?php echo $div;?>', <?php echo $chartdata;?>);
and then myData can just equal chart data (since its already an array)
var myData = chartdata;
'<?php echo $chartdata;?>'
This is going to echo '['NBA',1],['NFL',2],['MLB',3],['NHL',4]'. Note how there are single quotes inside the single quotes.
new Array(chartdata)
This will just make an array, with one element, the string "['NBA',1],['NFL',2],['MLB',3],['NHL',4]".
Try doing dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
This will make chartdata an array of arrays.
Instead of
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
Use
$chart_data = "[\"NBA\",1],[\"NFL\",2],[\"MLB\",3],[\"NHL\",4]";
Change your call to this:
dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
And function to this:
function dynamicChartArray(div,chartdata){
var myData = chartdata;
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
change this:
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
to this:
dynamicChartArray('<?php echo $div;?>', [<?php echo $chart_data;?>]);
and see if it works
You dont need var myData = new Array(chartdata);.
chartdata is already an array.
Take a look at json_encode.
$chart_data = json_encode(array(array('NBA',1),array('NFL',2)));
which will produce a json string ready to echo into your script
string(21) "[["NBA",1],["NFL",2]]"
You should have a look at the output. I bet it is:
dynamicChartArray('graph','['NBA',1],['NFL',2],['MLB',3],['NHL',4]')
and you can already see that you have problems with the quotes.
Instead of creating a string, I suggest to create an array and use json_encode:
$chart_data = array(
array('NBA',1),
array('NFL',2),
array('MLB',3),
array('NHL',4)
);
and
dynamicChartArray('<?php echo $div;?>', <?php echo json_encode($chartdata); ?>)
JSON happens to be valid JavaScript as well and it gives you more possibilities to process the data on the server side.

How to pass string to javascript funciton which contains special characters

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.

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