SyntaxError: in javascript php session - javascript

I am using the following code in a seperate js file to use a php $_SESSION variable. However, I am getting a syntax error of SyntaxError: missing ; before statement. I have tried putting the ; in the usual place, but still the same.
What is the correct way to use a php session in js file. Thanks
var companycode = '<?php echo $_SESSION['ls_idcode_usr']?>';

There may be special characters in the value of the session variable. Use json_encode() to output a valid Javascript literal:
var companycode = <?php echo json_encode($_SESSION['ls_idcode_usr']);?>;

You can only use PHP in files ending in .php, otherwise the web server won't parse them looking for code to execute, and it'll just get passed down to the client.
You can certainly make a whatever.js.php file, where PHP will be involved in the production of the Javascript file that is passed down to the browser.

Related

JS $.post > dump PHP $_POST data to file

I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?
You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.

JS: Uncaught SyntaxError: Unexpected token '<' in browser console when using <?php echo json_encode($_SESSION['

I have an array defined in PHP:
$outofstock = array ( 0, 0, 0, 0, 0, 0, 1, 0 );
$_SESSION['outofstock']=$outofstock;
I try to pass it to a JS script this way:
var outofstock = <?php echo json_encode($_SESSION['outofstock']); ?>;
and I get an error with execution stop:
Uncaught SyntaxError: Unexpected token '<' VM563 newhed14.39.js:1
The same statement works in another script within an HTML file.
What am I doing wrong?
Thank you!
The fact that your file is named newhed14.39.js suggests to me that you're serving this particular file as a .js file statically, rather than through PHP. This means that PHP will not run - the PHP commands will end up literally in the file and will thus obviously end up as syntax errors. It's easy enough to check if this is the case - just open up the developer console on your browser and take a look at the file which threw the error; the PHP commands should be visible there (whereas they shouldn't be if PHP had processed the file).
The solution would be to move the variable into the dynamic output generated by a PHP script in a <script> tag, and to edit your JS to consume that variable (for example, by having the <script> tag call a function defined in the .js file).
the reason is that "PHP scripts do not run in .js files". you need to do this:
in your HTML document:
<input type="hidden" id="myArray" value="<?php echo json_encode($_SESSION['outofstock']); ?>">
then you can access this array in js like this:
var array = document.getElementById('myArray').value;
console.log(array)
from this way you access your PHP array in your js. hope it helps ...

Moving php array to javascript

I have a php array of products that I want to move to javascript but when I json_encode it errors out giving me
Uncaught SyntaxError: Unexpected token ;
The debugger is giving me
var phpPro=;
and the code reads
var phpPro=<?php echo json_encode($pro)?>;
I have also encoded the array in the php script and tried to assign to js variable from there.
php =
$jpro=json_encode($pro);
js =
var phpPro=<?php echo $jpro;?>;
This code was actually working and now that I'm trying to copy it to another site it is not working. All the products are in the php recordset when displayed so I know they are there.

passing php variable to separate javascript file

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.
My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it
You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

CodeIgniter function breaks with Javascript

I'm using CodeIgniter form helper, and this is what it does:
Uncaught SyntaxError: Unexpected token ILLEGAL
The code:
jQuery('#window-1').append('<?= form_dropdown('hfdata', $hf_arr, set_value('hfdata'), 'class="span3"') ?>');
As you can see, I'm using a PHP inside of a JS, when I do <?= 'Test' ?> it works.
So it seems like its related with the CodeIgniter function.
As far as i know this error message can be caused by unknown/wrong characters in the code, and from what I saw in the firebug, this CI function is generating text with tabs and line breaks... and that is my problem I guess.
I may be wrong, so please correct me if so.
I will appreciate any solution for this problem.
Chances are you're screwing up your quotes and you need to change the way you're passing that last parameter to the dropdown.
$class = 'class="span3"';
jQuery('#window-1').append('<?= form_dropdown("hfdata", $hf_arr, set_value("hfdata"), $class) ?>');
To explain how PHP and Javascript works: Php is executed on the server, this give html output. You browser will get that output and can do anything with it. From this point javascript can do his job.
You are echoing the php function call to the users browser. Javascript can't call the php function. If you want to do this, then you need to make a php file call that returnes the result you want. But I guess there is an other problem. ( if you want to do this, escape the ' characters)
You need to execute the PHP code on the server. This will give a result. You send this result to the client. On the clients PC javascript will execute your javascript code.
If you want to generate with PHP the javascript code, then you can do something like this ( in PHP on the server!):
jQuery('#window-1').append('<?= form_dropdown('hfdata', $hf_arr, set_value('hfdata')); ?> ');
If this isn't what you want, then you are working on a design problem. Then it's a kind of dead end.
I found the answer myself... As I said, it was caused by the HTML output that was returned from the from_dropdown.
The solution is simple, remove all unwanted characters like line breaks:
<?php
$prepare = preg_replace('/^\s+|\n|\r|\s+$/m', '', form_dropdown('hfdata', $hf_arr, set_value('hfdata'), 'class="span3"'));
?>
jQuery('#window-1').append('<?= $prepare ?>');

Categories