How to pass parameters with php in my case - javascript

I am getting an "Uncaught SyntaxError: Unexpected token ILLEGAL" error when try to load a page with a php variable.
$(document).ready(function() {
$.get("index.html", {token:<?php echo $token; ?>}, function(data) {
//codes..
});
});
I can't seem to echo $token in my javascript and I am sure $token is valid.
Can someone help me solve this issue? Thanks a lot!

You're echoing text from PHP into a Javascript context, which means you have to generate valid Javascript code. Simplest solution: json_encode()
{token : <?php echo json_encode($token) ?>}
json_encode() will take care of any quoting/escaping which needs to be done.
e.g. if $token = 'foo', then you'd be producing
{token: foo}
and be producing an undefined variable error.

you need to put quotes around the php output otherwise it will be treated as a javascript variable rather than a string
{token:'<?php echo $token; ?>'}

Related

PHP Variable from String with Javascript popup

In /var/www/html/msg.txt is just one word "Test".
Can someone please tell me why this doesn't work?
echo "<script>alert('$tes');</script>";
Complet php code:
<?php
$ma="Test";
$tes = file_get_contents("/var/www/html/msg.txt");
echo "$tes"; //works
echo "<script>alert('$ma'); //works
</script>";
//but if this
echo "<script>alert('$tes'); // doesn't work!!!! Why?
</script>";
?>
how can I do it?
Most likely you have a line break in that file, so the resulting code is:
<script>alert('Test
');
</script>;
Which is wont work, you can confirm this by looking at the source, and/or it will be erroring out in the browser console.
The problem is with your file_get_contents. Probably you are setting an incorerect path, or the file that you are trying to access doesn't have the right permissions

How to pass php variable in window.location javascript

I want to pass the php variable inside the window.location javascript this is my php code and i am unable to do that.
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
try to set quotation marks
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'"</script>';
You are closing your quote in JS
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
Should be
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'</script>';
This will cause an error in JS on the client side, you could see this by pressing f12 and looking in the console log in the browser debugger. Your source code will look like this
<script>location.href = "reportConsumption.php?creategenReport="35"&sDate="...
//where this is a quoted block
"reportConsumption.php?creategenReport="
//and this is just chilling in space
35
//and then a new quoted block, etc.
"&sDate="
And you had this other (php syntax error) issue I took the liberty of fixing.
.$enddate;</script>';
Just in PHP you can redirect with
header("Location: $url");
But you have to be sure of 2 things:
You do not output "Anything" not even a line return before calling header
You call exit(); immediately after it. If you don't PHP will continue to execute the current script after it executes the redirect. Which is probably not desirable.
You are closing the double quotes too early. It should be close at the end of the URL. So you have a syntax error in your JavaScript:
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'";</script>';
Or separate using a variable to be more clear:
$url = 'reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate;
echo '<script>location.href = "'.$url.'";</script>';
You should not use double quote around the values for GET param
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.
'&sDate='.$startdate.'&eDate='. $enddate .'"';</script>';

pass PHP Variable to JS

The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....

variable assignment open_form() codeigniter

just a simple question, can we assigned codeigniter open_form() to javascript var?
i have a code like this:
var openForm = '<?php echo form_open("controller/some_function",
array('class' => 'class_name', 'enctype' => 'multipart/form-data'));?>';
but when i run it, i got error in my console saying:
Uncaught SyntaxError: Invalid or unexpected token
but, when i try this:
var closeForm = '<?php echo form_close(); ?>';
it didn't show any error.
though i guess it's not about syntax error, i still have no idea what is wrong and what happens. can anyone explain?
Yes. You can use like this
var openForm = `<?php echo form_open("controller/some_function", array("class" => "class_name", "enctype" => "multipart/form-data")); ?>`;
openForm += '<?php echo form_close(); ?>';
$("#your_element)id").html(openForm);
In javascript You can't split a string across multiple lines. <?php echo form_open(); ?> add \n at the end which create Syntax error.
As well <?php echo form_open(); ?> adds double quotes, which also ends into escaping issues.
To avoid issues In such cases you can use the template literals which is `
For more details you can visit this site.
I hope it justifies your query.

Debugging JSON Object Javascript

I am learning Javascript and have been following a tutorial on coding an autofill search box. I have got so far but am now stuck on parsing some JSON code. The JSON code is the result of a PHP SELECT from my database.
The JSON result looks like the below.
["Leeds","Leicester"]
According to JSONLint it is valid JSON code.
However when I run the snippet of code below I get a script 1014 Invalid Character at the jQuery.parseJSON line...................I know its something to do with the fact that my JSON code is not an object but cannot work out what to do. I even tried stringify on the data before parsing but that did not work either
................other code
$.get("No1PHPfile.php",{keyword:keyword})
.done(function(data) {
console.log(data);
var results=jQuery.parseJSON(data);
console.log(results);
...................other code
EDIT
Two sets of PHP Files
No. 1
<?php
require('..........sqldatabase.php');
require('.........selectdatabasecode.php');
if(!isset($_GET['keyword'])) {
die();
}
$keyword=$_GET['keyword'];
$data=searchForKeyword($keyword);
echo json_encode($data);
?>
No. 2
<?php
function getDbconnection() {
$db=new PDO(DB_DRIVER.":dbname=".DB_DATABASE.";host=".DB_SERVER.";charset=utf8",DB_USER,DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $db;
}
function searchForKeyword($keyword) {
$db=getDbconnection();
$stmt=$db->prepare("SELECT stationlong FROM `station` WHERE stationlong LIKE ? ORDER BY stationlong ");
$keyword=$keyword.'%';
$stmt->bindParam(1,$keyword,PDO::PARAM_STR,100);
$isQueryOk=$stmt->execute();
$results=array();
if ($isQueryOk) {
$results=$stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
trigger_error('Error Executing Staement.',E_USER_ERROR);
}
$db=null;
return $results;
}
?>
something like
$result = json_encode ($data_i_want_to_send);
header('Content-type: application/json');
echo $result;
may help
UPD
Yes. i'm sclerotic((
Try
$data=searchForKeyword($keyword);
$data=array ('data' => $data); // so you send OBJECT anyway
$data=json_encode($data);
header('Content-type: application/json');
echo $data;
and on client side
var results= data.data; // instead of jQuery.parseJSON(data);
It should help to avoid different "magic" differences how it interpret your data and it works for sure in my site.

Categories