CodeIgniter function breaks with Javascript - 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 ?>');

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.

SyntaxError: in javascript php session

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.

How To Pass Arguments to Javascript File From PHP Exec

After a form is submitted from my php file it checks it, and then is supposed to call an exec function that will execute a binary file using the second file listed in the code. Shown below:
if (isset($_POST['admin']) && !empty($_POST['admin'])) {
echo exec('/home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/bin/phantomjs /home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/examples/bigdaddy.js');
}
The problem here is that the preceding javascript file bigdaddy.js has to take three arguments of its own in order to function. To solve this issue, I tried the following:
echo exec('/home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/bin/phantomjs /home/mainshee/public_html/wp-content/themes/twentyseventeen/phantom/phantomjs-directory/examples/bigdaddy.js' $_POST['admin'] $_POST['user'] $_POST['password']);
This bricked my site.
Does anybody have any ideas how this may be done? All of the possible solutions I have found detail PHP to PHP, NOT PHP to Javascript. Thanks all!
you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Web Form not recognizing PHP

I have built a webform with Laravel and have it working the way I want it to on my localhost. However, when I put it on the server my form stops recognizing my php commands. For example see below.
In my working model, my code looks like this.This is using javascript to return an array of data elements that I need for my project.
var pageDownloadInfo=<?php echo json_encode($project); ?>;
However when I put my form on the server an error occurs and it points to this in the console.
var pageDownloadInfo=<br />
and the console gives me this notice error:
Notice: Undefined variable: project in C:\xampp\htdocs\QPA Form\resources\views\pages\datatest.blade.php on line 278
null;
The forms are exactly the same. I am not sure what is causing this.
try using quotes around the echo statement as such
var pageDownloadInfo="<?php echo json_encode($project); ?>";

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.

Categories