passing PHP string to JavaScript: unterminated string literal - php

i am assigning PHP var to my javascript var and sending to PHP file through
ajax-jQuery, but my php variable contains newline chars which
i have replaced with <br>
e.g. $values1 = 'abc<br>pqr<br>xyz'; $values2 = 'xyz<br>lmn';
javascript - var data = 'val1=<?php echo $values; ?>&val2=<?php echo $values2; ?>';
and then ajax script to post data to PHP file
but when i print this data on console it is giving me error- SyntaxError: unterminated string literal.
Can anyone help ?

Your JS code:
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Will give Javascript syntax error if one or more of your PHP variables $values1 OR $values2 contain single quote ' in them.
Make sure your PHP variable don't contain single quotes in them by replacing all single quotes to something else otherwise use double quotes " to create JS var like this:
var data = "val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>";
Provided PHP variables don't contain double quotes.

First of all, you have a typo, that might cause an error:
// --------------------------------v
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Then, I suggest you to use object as data parameter for Ajax request:
var data = {
val1: '<?php echo $values1; ?>',
val2: '<?php echo $values2; ?>'
};
Also it is better to escape single quotes ' in both $values1 and $values2 variables.

Try using <br /> instead of <br>. Just guessing here, no testing.

Related

jquery how to break string and continue string after

im trying to do this to get loop i variable inside my php variable
var monthyear[i] = "<?php echo $startmonth_name"+i+" ?>";
so it will show like:
var monthyear[i] = "<?php echo $startmonth_name1 ?>";
var monthyear[i] = "<?php echo $startmonth_name2 ?>";
can't figure it out and i keep getting error:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';'
Loop in javascript won't work for reasons mentioned in my comment, you can try having a loop in php code, something like below.
Replace this with
var monthyear[i] = "<?php echo $startmonth_name1 ?>";
var monthyear[i] = "<?php echo $startmonth_name2 ?>";
With
<?php
for($i=0;$i<some_value;$i++)
{
echo "var monthyear[".$i."] = ". ${'startmonth_name'.$i} .";"
}
?>
Note: I haven't tested the code. This is just to give an idea.
do this instead:
<?php echo "var monthyear["+i+"] = '"+ $startmonth_name[i]+"';"; ?>;
change these to an array to use them in the loop: $startmonth_name1
Forget about JavaScript right now. JavaScript will be executed later, in another computer, possibly some thousand kilometres away. You are getting a PHP parse error: that means that your PHP code does not even run. And it's clear why—the PHP block contained in this code:
var monthyear[i] = "<?php echo $startmonth_name"+i+" ?>";
... is this:
echo $startmonth_name"+i+"
You might get away with something like this:
var monthyear[i] = <?php echo json_encode($startmonth_name); ?>+i;
Yet I suggest you remember that PHP and JavaScript will simply neither interact nor share variables and rethink your logic accordingly.

parseJson is running into an unexpected error (Unexpected identifier)

This is all in the same script. I know the difference between ajax and serverside code. I have php interwoven in this javascript script as follows:
<script>
<?php
$json_string = json_encode(array("agent_table" => "<span style='float: left;'></span>"));
?>
var response = $.parseJSON('<?php echo $json_string; ?>');
</script>
But parseJson is complaining of an error. The error disappears when I remove the styling from the span.
The error is 'Unexpected identifier'. This is in Chrome.
You have ' characters in your data. These will continue to be represented as literal ' characters in the JSON.
You are embedding your JSON directly into a JavaScript string, and that string is delimited by ' characters. The first ' that appears as data in the JSON will terminate the JS string.
This is a general problem when embedding on data format in another. You are embedding JSON in JavaScript in HTML.
Your options:
Replace every instance of ' in the JSON with \' (so they mean "Apostrophe" instead of "End of JS string")
Treat the JSON as a JavaScript object literal instead of trying to munge it into a string which you run it through a JSON parser.
The latter option is the sane one (so long as your goal doesn't involve proving that PHP can generate valid JSON).
var response = <?php echo $json_string; ?>;
You don't need to worry about further escaping for inserting into the HTML because the only sequence you need to worry about (inside a script element) is </script> and PHP's json_encode will output <\/script> for that anyway.
May be it?
<script>
<?php
$json_string = json_encode(array(
"agent_table"=> '<span style="float: left;"></span>'
));
?>
var response = <?php echo $json_string;?>;
</script>
try it!!!
<script>
<?php
$json_string = json_encode(array('agent_table' => addslashes('<span style="float: left;"></span>')));
?>
var response = $.parseJSON('<?php echo $json_string; ?>');

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.

Inserting a string inside of a javascript defined in PHP

I just found myself in an odd position trying to put a string inside of javascript, that is defined in a php. The code I'm going to post isn't that actual code, but its the situation I'm in.
$script = "
var someVar = \"<input type='text' onchange='callScript('problem here') />' \";
";
so as you see, I'm setting a javascript variable that has html elements in it. the html element has an onchange event that is set to call a function that takes a string as a parameter. How would i insert that parameter?
I think if you call addslashes() on the string before inserting it into the variable, you should be fine as to escaping any possible unsafe characters, so:
$script = "var someVar = \"<input type='text' onchange='callScript(\\\"".addslashes($problem_here)."\\\") />' \";
Use String.fromCharCode:
$script = "
var someVar = \"<input type='text' onchange='callScript(\" + String.fromCharCode(34) + \"problem here\" + String.fromCharCode(34) + \") />' \";
";
Generated JavaScript would be:
var someVar = "<input type='text' onchange='callScript(" + String.fromCharCode(34) + "problem here" + String.fromCharCode(34) + ") />' \";
which evaluates to someVar being the string
<input type='text' onchange='callScript("problem here") />'
Try
$script = "
var someVar = \"<input type='text' onchange='callScript(\"problem here\")' />\" ";
Ideally your JavaScript will be inside a view file, so you won't print it out with PHP, more the other way around:
var jsVar = <?php echo json _encode($phpstring); ?>;
Or the shorter:
var jsVar = <?=json_encode($phpstring)?>;
Json encode will make sure the string is printed in a way that it will be read properly by JS.
http://php.net/manual/en/function.json-encode.php
In general, stay away from addslashes. Do what Robin Winslow said (I'm new here so I guess I can't reply directly) and use json_encode.
However, you'd still need to html-escape your that string in JS. Look into something like jQuery's templating system if you're generating HTML with JS.

Categories