Unexpected T_STRING error in codeigniter [duplicate] - javascript

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'].')"';

Related

Put php code inside of registerScript of yii framework [duplicate]

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); ?>

How can I properly supply a php Json encoded object to a javascript method.

I'm trying to pass a PHP json_encoded object to a function which accepts 2 parameters. But when it's rendered on the browser it kept saying that there's
On Firefox's Inspector:
SyntaxError: missing ) after argument list
On Chrome's Inspector:
Uncaught SyntaxError: Unexpected end of input
Code:
<td>
Edit
</td>
Source Code On Browser:
<td>
Edit
</td>
I tried adding \'' but didn't help. Maybe I'm doing it wrong. I've been on this since last night so I think I need to ask now.
I clear the browser's cache everytime I test but I get the same result. There are similar questions but I tried them but won't fix my problem.
I'd appreciate any help.
All you gotta do is change the quote. from " to ' for the onclick function.
browser read your HTML as
Edit
when you want to read it as
<a href="#" onclick='showEditModal({"id":2,"title":"Announcement 1","content":"Announcement 1 Content","dateAdded":"2018-04-24 14:44:27"})'>Edit</a>
Check the difference in syntax highlight.
Hence why you got the
SyntaxError: missing ) after argument list
But like #CertainPerformance mentioned. It is better to not write it as inline functions. set the value as a JS object and use it while executing the function. Avoid inline-functions as much as possible.
Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code, especially if you're trying to write into them on the fly with PHP like that. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
To send data from the server to the client, you should either use data- attributes, application/json, or a network request. For example, taking the application/json route, you would do something like the following:
<td>
Edit
<script type="application/json">
<?= json_encode($value, JSON_HEX_APOS) ?>
</script>
</td>
Javascript:
// (select the `a` referenced above)
a.addEventListener('click', () => {
const parsedObj = JSON.parse(a.nextElementSibling.textContent);
showEditModal(parsedObj);
});

php writing a onkeyup= function

I am writing a php script which generates html with a javascript onkeyup event, as such:
// generate the function text
$fn_text = "checkContentQuizAnswer(\"#".$var_name."\",\"".$equation_solutions_array[0][0]."\",\"{'incorrect_values':[";
for($r=1;$r<count($equation_solutions_array);$r++) {
// THIS ISNT WORKING CORRECTLY, NEED A BETTER WAY TO PASS INCORRECT INFO
$fn_text .= "{'equation':'".$equation_solutions_array[$r][0]."','message':'".$equation_solutions_array[$r][1]."'}";
if(($r+1)<count($equation_solutions_array)) {
$fn_text .= ",";
}
}
$fn_text .= "]}\")";
However this isnt working... the code it generates looks something like this:
onkeyup="checkContentQuizAnswer("#theonlyvariable","27.62*5","{'incorrect_values':[{'equation':'27.62+5','message':'you added 5'},{'equation':'27.62-5','message':'you subtracted 5'}]}")"
however, it hasn't been working... the errors have included complaints about missing }'s, MathJax (an eval() style library) is undefined.
Im sure that it is how I am parsing the onkeyup part of the tag but i cant get the combination/syntax correct.
Can anybody see a glaring problem? :S
Thanks
Alex
Although you are escaping the quotes in the PHP file, the quotes in the javascript parser are not being escaped. Change the quotes inside the onKeyUp to single quotes to fix this. You will also need to escape the quotes in the JSON as well - the json_encode() function can help with that. You need to output something like:
onkeyup="checkContentQuizAnswer('#theonlyvariable','27.62*5','{\'incorrect_values\':[{\'equation\':\'27.62+5\',\'message\':\'you added 5\'},{\'equation\':\'27.62-5\',\'message\':\'you subtracted 5\'}]}')"

PHP - file_get_contents get JSON with regex, but can't JSON decode (got JSON_ERROR_SYNTAX)

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.

Onclick-function on elements in Handlebars-template

I'm building a simple webapp with just Handlebars.js and some jQuery.
Now I have a list of data, and i present them through a Handlebars-template. Then I want some actions associated with these, e.g. update one element, or delete one. I have buttons that one associates with these actions, the problem is that I cannot manage to get onclick-methods associated with buttons in the template to work.
I read this question and answer, which lead me to adding the extra bracket and helpermethod, but it still doesn't work. See code below.
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context);
});
var myGreatFunction = function(someValue) {
// Work with that value
}
The template:
{{#each Something}}
<button onclick="myGreatFunction({{{json this}}})"></button>
{{/each}}
Now, doing it like this give me Uncaught SyntaxError: missing ) after argument list at the top of the HTML-file.
I noted the answer here, so I tried with onclick="myGreatFunction( '{{{json this}}}' )" which gives me the error Uncaught SyntaxError: Unexpected token ILLEGAL at the end of HTML-file.
With onclick="myGreatFunction( '{{json this}}' )" the button simply disappears on click.
Does anyone see something I've missed, or is there another way of doing this? I thought of adding the object to some div/button in the template, then add a jQuery-listener for the click that fetches the value from the template, but that seems so ugly and unclear.
Any tips? All help is greatly appreciated - thanks in advance.
UPDATE: Seems the problem is, as Hacketo mentioned below, that the outputted JSON is kind of messed up. I inspected an element in my code:
onclick="someFunc('{"id":5,"publisher":null,"message":" asdadsad","address":"asdad","published":&quot
Last Saturday at 12:00 AM","createdAt":"2015-07
23T09:55:35.486Z","updatedAt":"2015-07-23T09:55:35.486Z"}')"
(Broken over multiple lines for your convenience).
Now I just have to find out of to get that JSON to look right.
This is because JSON.stringify return a JSON string and contains ".
At the moment, your template may look like this:
<button onclick="myGreatFunction({{{json this}}})"></button>
Compiled :
<button onclick="myGreatFunction({"foo":"bar"})"></button>
^ ^ ^ ^ ^ ^
And this result as
Uncaught SyntaxError: missing ) after argument list
You need to escape those " and you can do this in your helper
Handlebars.registerHelper('json', function(context) {
return JSON.stringify(context).replace(/"/g, '"');
});
And this will result as
<button onclick="myGreatFunction({"foo":"bar"})"></button>
Just take out the extra bracket. If you let Handlebars do HTML escaping (which it will automatically on a regular {{json this}} invocation), it will also escape the quotes for you.

Categories

Resources