I am getting a "Uncaught SyntaxError: missing ) after argument list" error when running the line below (which returns a json formatted file from my PHP to my javascript).
var moredata = JSON.parse("<?php echo json_encode(find_detailed_forecast()); ?>");
I'm not sure how to fix this. If I edit the line to remove the parentheses or add a '' pair, then I get a "Not Found The requested URL /[object Object] was not found on this server." When I look at the console, the php echo code is running correctly, so I get a JSON.parse(""long string here""). Not sure what is exactly wrong with my javascript and any help would be much appreciated. If it matters, my php, javascript, and html code are all in the same file.
Edit: The code looks like below on execution (its a really long file so I wasn't sure if I should copy paste the entire thing):
var moredata = JSON.parse(""{\"latitude\":999.123456,\"longitude\":-999.123456,\"timezone\":\"America\/New_York\",\"currently\":{ .... }"\n"");
JSON.parse outputs data with double quotes, so you have to use single quotes.
var moredata = JSON.parse('<?php echo json_encode(find_detailed_forecast()); ?>');
Related
I need to json encode a php object called 'contact' in my controller, pass it to my view and then parse it using javascript. One of the object properties contains HTML markup, which seems to cause a lot of issues. I have been running in to a lot of trouble successfully parsing the object.
I keep getting the following javascript error when calling JSON.parse().
VM4464:1 Uncaught SyntaxError: Unexpected token & in JSON at position 1
at JSON.parse (<anonymous>)
What I tried:
PHP
$contact = htmlspecialchars(json_encode($contact), ENT_QUOTES, 'UTF-8');
Front end
var contact = JSON.parse("{{ $contact }}");
just yesterday I had the same problems, apparently it has something to do with blade escaping special character. I found the answers on this site,
try
var contact = JSON.parse('{!! json_encode($contact) !!}');
notice the use of {!! instead of {{, and try to experiment the usage of single/double quotes, or even without quotes, maybe?
PHP
<?php $arr = array(); $i = 0; $arr[0] = 'desk'; $arr[1] = 'chair'; $arr[2] = 'carpet'; ?>
JS
var test = "<?php echo json_encode($arr); ?>";
console.log(test[0]);
When I inspect and check on console tab, I got Uncaught SyntaxError: Unexpected identifier error. And when I check in sources tab, the error lead to a code statement as shown in the image below. What did I do wrong? Currently I'm using laravel 5.4.
Please, never do that unless you want people to inject arbitrary codes into your site.
JavaScript source codes should never be generated. Create an API endpoint or some other information passing mechanism instead.
You only need to get rid of the double quote around your PHP.
Saying like this:
var test = <?php echo json_encode($arr); ?>
This will result in:
var test = ["desk","chair","carpet"];
Your array is surrounded by quotes. In js array declarations are not surrounded by quotes. You may need to modify the output of the json encoding or pass a flag to tell it to not surround the output in quotes.
If you use non-associative array, you can force it to be an object using the predefined constant JSON_FORCE_OBJECT
var test = "<?php echo json_encode($arr, JSON_FORCE_OBJECT); ?>";
I am in trouble to escape this js function in php file:
it returns error:
JavaScript: SyntaxError: missing ) after argument list
The code is this:
echo "Delete";
Basically this is js function with 5 parameters and some of them are also functions and there is the problem. all variables like $messages[] are language defined variables.. The error shows the last parameter - function redirect_communicator()
Can you tell me what is wrong and how to escape it?
Thank you for any suggestions
EDIT:
I also tried this:
delete
and still the same error.. When I add json_encode another error raisen..
Mixing languages like this is always hard to read, and rarely a good idea.
However if you need to do it, you can use sprintf to help clarify it a little:
echo sprintf(
"Delete",
$messages['deleting_message'],
$messages['close'],
$lang['delete'],
$fullurl
);
I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;
i have the following button :
<button onclick='enroll(<?php echo $course['cs_id']; ?>)'>enroll</button>
when the user click on it the following javascript function will start :
function enroll(id){
$.post("<?php echo base_url().'courses/enroll/'; ?>"+id , function(data){
obj = JSON.parse(data);
alert(obj.state);
});
}
which perform a post request to php page which echo json array like this :
$data = array("state"=>"done");
die(json_encode($data));
but unfortunately the following error appears in the console :
JSON.parse: unexpected character
i checked the page response and its look like this (which seems fine ) :
{"state":"done"}
also when i change the enroll() function to be like this :
function enroll(id){
$.post("<?php echo base_url().'courses/enroll/'; ?>"+id , function(data){
alert(data);
});
}
its show the alert message correctly like this :
{"state":"done"}
so why it refuse do parse the response where everything seems okay ? any idea ?
My guess is that your code is actually working better than you think! I think that jQuery receives your JSON from the server and realises that it is JSON, even though you haven't specified it as such. (Perhaps your PHP is sending a Content-Type header?)
So data is actually already a Javascript object, which jQuery has decoded from your JSON. When you call JSON.parse on an object, it is converted to a string [object Object], and then parsed. [object Object] is evidently invalid JSON, hence the unexpected character error.
Since the string was obviously valid JSON, my next guess was that there was some data before the string that was causing the parser to be unhappy. The best way to test this is with String#charCodeAt, which reveals the precise character at a given point in the string.
So, with the following code, we can test to see what the first character in the string is:
console.log(data.charCodeAt(0));
You say that this returns 65279, which, at the beginning of a Unicode document, is a byte order mark. You are apparently outputting this somewhere in your server-side code. You need to find out where that is and remove it.
Do not parse the data again:
function enroll(id){
$.post("<?php echo base_url().'courses/enroll/'; ?>"+id , function(data){
alert(data.state);
});
}