This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 2 years ago.
I want to put a php code inside of Yii::app()->clientScript->registerScript of yii1
How can I put it inside of this one?
<?php Yii::app()->clientScript->registerScript("form", <<<JAVASCRIPT
// I want the PHP code inside of this
JAVASCRIPT, CClientScript::POS_END); ?>
is there a way besides of ending the PHP in the middle of the code?
EDIT
if I put <?PHP ?> in the middle I'm getting an error of
Parse error: syntax error, unexpected end of file in
C:\xampp\htdocs\yii\project\protected\views\group_Form.php
on line 275
and that line is
JAVASCRIPT, CClientScript::POS_END); ?>
Since you can access the controller instance via $this in view context, I would suggest you doing something like that:
Create partial view php file where you can build your mixin (js + php) which obviously will contain any script type with some conditions on top of PHP.
Use CBaseController#renderPartial (which actually returns string instead of rendering, according to 3rd parameter return = true) in view context to get the mixin view contents as string and pass it as 2nd parameter to Yii::app()->clientScript->registerScript.
The implementation would look like this:
// _partial_view.php
// here is your mixin between js + php
/* #var $this CController */
<?php
echo '<script>' .
Yii::app()->user->isGuest
? 'alert("you\'re guest")'
: 'alert("you\'re logged user")'
. '</script>';
Then go back to your registering js invocation:
<?php Yii::app()->clientScript
->registerScript("form",
$this->renderPartial('_partial_view.php', [], true), // setting 3rd parameter to true is crucial in order to capture the string content instead of rendering it into the view
CClientScript::POS_END); ?>
Related
When I am parsing a PHP array which is filled with data from a database to JavaScript, I get an error called unexpected token '<' . The code which selectes data from my database is:
$wagennummern = NULL;
$result = $db->query("SELECT * FROM `Wagenbuch`");
while($row = $result->fetch()){
$wagennummern = $row['Wagennummer'];
}
The code to use this data in JavaScript is:
var wagennummer = <?php echo '["' . implode('", "', $wagennummern) . '"]' ?>;
The Javascript is the line where the error occurs. Can anybody tell me why there is an error and how to fix this?
The particular error message could be caused by a combination of characters that includes a < in the data.
If you want to convert a PHP data structure to a JS data structure, the json_encode, which is compatible with JS. Don't roll your own. Any special character is likely to break your attempt.
var wagennummer = json_encode( $wagennummern );
It might also be caused by the PHP not being executed at all. This would happen if you weren't loading it from a web server, or if you put it in a file with a .js file extension instead of a .php file.
In addition to #Quentin's answer:
I would point out that if your query does not return any row, the variable $wagennummern will be null (first line of your code)
Trying to feed a null value into implode will generate an error, which will be display as HTML, thus creating the unexpected token '<' error.
I would suggest to initialize the $wagennummern variable to an empty array, that way it will not cause any problems if you have no rows.
Another solution would be to check for the variable being !== null
This question already has answers here:
"Unexpected T_STRING"? [closed]
(3 answers)
Closed 4 years ago.
I'm using Codeigniter 2.2.
I'm trying to build a table using HTML table class library. It also contain the delete button with it .for the button purpose I m using form_button() helper .view file of my code is as below :
<?php
foreach($invoices as $row) {
$data = array(
'type' => 'button',
'content' => 'delete',
'class'=>'btn btn-default btn-sm dropdown-toggle',
);
$js='onclick="confirm_modal('base_url().'admin/invoice/delete/'. $row['invoice_id']')"';
$links = form_button($data,$js);
$this->table->add_row(
$this->crud_model->get_type_name_by_id('student',$row['student_id']),$row['title'],$row['description'],$row['amount'],$row['amount_paid'],$row['due'],$row['status'] ,$links
);
}
echo $this->table->generate();
?>
But in the row :
$js='onclick="confirm_modal('base_url().'admin/invoice/delete/'. $row['invoice_id']')"';
I am getting error as
unexpected T_ STRING.
Please help me out....thanx in advance ..
Syntax error
$js='onclick="confirm_modal('base_url().'admin/invoice/delete/'. $row['invoice_id']')"';
missing the . (s)
$js='onclick="confirm_modal(\''.base_url().'admin/invoice/delete/'. $row['invoice_id'].'\')"';
A good IDE will help you avoid these simple mistakes.
The T_STRING is the name of a STRING token used when PHP interprets your text into code, AKA the lexer/parser part of the deal. So an UNEXPECTED T_STRING is an unexpected string meaning a string that is just chilling where it's not meant to be.
And based on another comment your also missing the ' for the JS part.
Another way to do it would be a HEREDOC
$url = base_url().'admin/invoice/delete/'. $row['invoice_id'];
$js= <<<SCRIPT
onclick="confirm_modal('{$url}')"
SCRIPT; //nothing can go here no spaces not even this comment.
With a HEREDOC you can use both quotes freely, but you can't put function calls in them. You have to be careful with the ending TAG (you can use whatever you want for the tag) but the ending tag has to be on it's own line with nothing else not even a single space.
I forget if going to the next line puts a line return in there, it looks better anyway. HEREDOCs can take a bit of getting used to but they can really free up the quotes and make things a bit simpler overall when dealing with putting in multiple types of quotes.
You are doing wrong concat
it should be like
$js='onclick="confirm_modal('.base_url().'admin/invoice/delete/'. $row['invoice_id'].')"';
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
So I need to request an image from a database, this then gets put in a variable, and gets called up in an echo.
However, i'm in a shortage of quotemarks in this case, seeing as the PHP echo uses double quotes, And then after calling up the onmouseover I use the single quotemarks, but after that I cannot use the double quotemarks again for the URL that gets caled up,
Going around this by putting the whole command in a variable didn't work.
Putting the whole command into the database didn't work.
Putting the command or url in a shorthand if statement didn't work.
And putting the Javascript code into a function, Also does not work.
Here is the code I'm talking about.
$afbeeldingurl = $row["afbeeldingurl"];
$overurl = $row["overafbeelding url"];
echo "<div><a href='../".$url.".html'><img onmouseover=mouseover() src='images/".$afbeeldingurl."' alt='' /></a>";
<script>
function mouseover()
{
this.src='images/<?php$overurl?>';
}
</script>
I thank you in advance :)
(Note, Only Javascript allowed, I cannot call up Jquery)
this.src='images/<?php$overurl?>';
Try switch this to
this.src='images/<?php echo $overurl; ?>';
I try to parse this page : http://fr.hearthhead.com/cards to get the hearthstoneCards JS variable.
So i do something like this :
$url = 'http://fr.hearthhead.com/cards';
$content = file_get_contents($url);
preg_match('#var hearthstoneCards = (.*)}]\;#Us', $content, $out);
$out = $out[1].'}]';
$tab_id_card = json_decode($out,true);
I try every tricks i could find (trim, stripslashes, preg for BOM and other things, put flags on json_decode and many other things), but i didn't get this working.
If i file_put_contents the $out var and compare to the real source it's the same thing (same length). If i put the string on a JS console, i get the data. But PHP don't want to parse this var :(
Some one got an idea ? :)
The problem is that you assume that code is JSON, when it's really full-fledged JavaScript. Within that code, many unquoted repetitions of the property name popularity occur, which is fine JavaScript but invalid JSON.
I tried to build a regex to fix any unquoted property names. Problem is, it's infeasible. In my case, any colons inside values broke my regex.
Short of writing a parser to fix such nonconformities or invoking a JS interpreter (which would require an external dependency such as V8Js), I think you'll be fine with fixing this specific scenario for now:
$url = 'http://fr.hearthhead.com/cards';
$content = file_get_contents($url);
preg_match('#var hearthstoneCards = (.*)}]\;#Us', $content, $out);
$out = str_replace('popularity', '"popularity"', $out);
$out = $out[1].'}]';
$tab_id_card = json_decode($out,true);
If you worry about future introduction of new unquoted properties, you can check $tab_id_card for NULL and either log the error somewhere you routinely check or even go as far as somehow firing a notification for yourself. Although I'd do it, I'd say it's not a likely scenario, due to all the other properties being correctly quoted.
This question already has answers here:
Efficient way to Pass variables from PHP to JavaScript [duplicate]
(8 answers)
Closed 9 years ago.
What is the best way to pass a server-side PHP variable to Javascript?
To simplify the problem assume that we have a variable in PHP ($phpVar) and we want to assign its value to a Javascript variable (jsVar)
Javascript files are loaded in html - they are not created dynamic!
Some food for thought:
1. Print with PHP before loading Javascript files:
<script language="javascript" type="text/javascript">
var jsVar= <?php echo $phpVar?>;
</script>
2. Store in DOM (in hidden elements)
a. in PHP:
<span data-name="phpVar" data-value="<?php echo $phpVar?>"></span>
b. Read in Javascript files (assuming jQuery available):
var jsVar= $('span[data-name="phpVar"]').attr('data-value');
3. Ask it with AJAX after page has loaded
Obviosly not the best solution. Doesn't fit to all scenarios and requires an additional request...
In conclusion:
They both seem ugly to me... Is there a better approach?
Is there any frameworks that can handle this dependecies? Please keep server reconfiguration minimal.
The best approach would be providing an "internal API" requested via AJAX from client side.
Doing this way you can keep your sides separated.
After this, the fastest way is printing in a shared file the values you want to share (as you wrote in your question).
As a last note: if you carry on with the second way I would suggest you
json_encode()
as a really helpful method to pass arrays and objects from php to javascript.
So if you have your php array:
$array = array( "a" => 1, "b" => 2 );
<script language="javascript" type="text/javascript">
var js_array= <?php echo json_encode( $array ) ; ?>;
</script>
It depends on the situation, but in common, predominantly to use first case. But don't forget about quotes if you pass a string:
<script language="javascript" type="text/javascript">
var jsVar = '<?php echo $phpVar?>';
</script>