I am using laravel 5.2 , I am using like below
var data = <?php json_encode($data['value']); ?>
when I am using JavaScript code below in the blade file, then its working fine, but when I am using the code as a separate file and trying to gulp that , then it is not working , my data is not loading
var data = "<?=json_encode($data['value']);?>"
or
var data = "<?php echo json_encode($data['value']);?>"
You are not echoing out the value, your var is null
Other mate already provided the correct solution specially #user1779617, now i am explaining with a basic example:
<?
// a simple array
$data['value'] = array(1=>'test');
$encodedData = json_encode($data['value']);
?>
<script type="text/javascript">
var data = <?=$encodedData?>;
console.log(data); // Object { 1="test"}
</script>
If you have posted original code than you have an error in your javascript, you miss the ending termination semicolon (;) plus you need to echo the result as other mentioned in answers.
UPDATE 1
if you are still facing the same issue than use JSON.parse in javascript
<script type="text/javascript">
var data = JSON.parse( ' <?=$encodedData?>');
console.log(data); // Object { 1="test"}
</script>
Related
I am passing an array from my controller.
Now, I put this code inside my Laravel 6.* Blade View,
<script>
var app = <?php echo json_encode($array); ?>;
</script>
This works just fine.
However, if I put the same piece of line (or any of the following lines) inside my custom app.js file, this doesn't work.
var app = <?php echo json_encode($array); ?>;
var app = {!! json_encode($array->toArray()) !!};
var app = '<?php echo json_encode($array); ?>';
Each time I am getting an invalid syntax error.
I am not sure if this is a valid ques for StackOverflow, but I have already tried all other similar solutions and none of them is working for me.
That's because you have no access to write php code in js file or you can use Ajax to get php variable.
In your statement if you put your code in your blade file before including app.js file you will be able to get app variable in your js file.
Ex:
<script>
var app = #json($array)
</script>
<script src="path to your app js file"></script>
And now in your app js file if you print app variable you will see the result
console.log(app); in your app.js file
One thing you can do is to move javascript to template and create route to it as:
Route::get('/app.js', function () {
$result = view('app', ['array' => [1,2,3,5,8]]);
return Response::make($result, 200)
->header('Content-Type', 'application/javascript');
});
Then in resouces\views
<script>
var app = <?php echo json_encode($array); ?>;
</script>
Common way of doing this is to create end point that returns json only and then use e.g. fetch api or axios library on client side.
Something like this:
Route::get('/app', function () {
return [1,2,3,5,8];
});
<script>
fetch(endPointUrl("/app")).then(response => {
console.log(response);
}).catch(error => {
console.error(error);
})
</script>
Where endPointUrl is just a helper function that creates full url.
I'm trying to create a button which dynamically add input and since I'm using Zend framework I use this method to get the input from the Form file : <?php echo $this->formm->getElement('refA'); ?>
but I get this error : Uncaught SyntaxError: Unexpected identifier
and the jquery function for that add button is :
$(document).ready(function (){
var j = "<?php echo $this->formm->getElement('refA'); ?>";
$("#add-more").click(function(){
$(".row").append(j);
});
});
and when I click on that error it shows me where I have the error it seems like that it uses:
$(document).ready(function (){
var j = "<label for="refA" class="optional">Article:</label>
<select name="refA" id="refA" class="form-control">
<option value="test1" label="test1">test1</option>
</select>";
$("#add-more").click(function(){
$(".row").append(j);
});
});
is it possible to get the code generated in single line so I can make the button to work ?
Looks like it's a quoting issue - the data that PHP is chucking in there has double quotes which keep terminating your string. Try wrapping it in single quotes - with escapes for refA:
$(document).ready(function (){
var j = '<?php echo $this->formm->getElement(\'refA\'); ?>';
$("#add-more").click(function(){
$(".row").append(j);
});
});
Ok, after doing some more digging, you need to get those quotes and spaces out before it. Unfortunately, I'm not a PHP guy - so I'm hoping that the syntax is right - the idea, is to get the data from refA and store it in $message - then get rid of any spaces and escape any quotes, then echo the value out to be set as 'j':
$(document).ready(function (){
var j = '<?php $message = $this->formm->getElement("refA"); $message = preg_replace("/\r?\n/", "\\n", addslashes($message));echo $message?>'
$("#add-more").click(function(){
$(".row").append(j);
});
});
PHP methods found here:
https://www.the-art-of-web.com/php/javascript-escape/
Another option that would completely take care of the issue would be to use es6 - template-strings (back-ticks)
$(document).ready(function (){
var j = `<?php echo $this->formm->getElement("refA"); ?>`;
$("#add-more").click(function(){
$(".row").append(j);
});
});
most modern browsers will nativity handle es6
Template Strings
As said by Kyle, you're facing a quoting issue. But, unlike what he said, quotes inside PHP tag must not be escaped, since they are rendered server side.
This should do the trick:
window.onload = function() {
$(document).ready(function (){
var j = '<?php echo preg_replace("/\r|\n/", "", $this->formm->getElement('refA')); ?>';
$("#add-more").click(function(){
$(".row").append(j);
});
});
}
Edit: looking at your screenshots and other comments, it seems that you are trying to access jQuery ($) before loading (I suppose you are loading all the JS dependencies at the end of the layout).
Since you can't use PHP code in JS files, you have two options:
You create a JS variable inside your template (ajouter.phtml), like var inputTemplate = <?php echo preg_replace(....);?>;, and use that variable in your JS file
You make sure that that JS snippet is executed only when the page has been fully loaded (hence the use of window.onload = function(){}
Personally, I'd suggest you the first option. Inserting JS code inside the phtml is conceptually wrong, because if you somehow you decide to not use jQuery anymore, you won't have to go inside all templates to find those snippets.
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....
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to read the meta-description of another website as a string in JavaScript. I tried using CORS but get an error saying "No 'Access-Control-Allow-Origin' header is present on the requested resource."
I was suggested that I could use PHP to do this. I don't know PHP and need some help. How do I call a PHP function to read source of some webpage on a different domain and then feed the output to a JavaScript function as a string?
Here is a simple, straight-forward way to help you get what you want. Try it out first... Paste the entire code below on an Empty PHP File and run it. No real need for Ajax in this Simple Scenario. So you have 2 Options:
OPTION NR. 1
<?php
//SIMPLY CHANGE THE URL TO THE URL YOU DESIRE
$siteURL = "https://yahoo.com/";
$siteContent = file_get_contents($siteURL);
$metaRx = "#<meta .*description.*>$#m";
preg_match($metaRx, $siteContent, $metaMatches);
$metaString = str_replace("'", "\'", $metaMatches[0]);
//DUMP THE ARRAY OF MATCHES TO THE SCREEN... JUST TO EXPLORE THE RESULTS
var_dump($metaMatches);
?>
<script type="text/javascript">
//EXPOSE THE META TO YOUR JAVASCRIPT USING A GLOBAL VARIABLE (FOR EXAMPLE).
var SITE_META_DESC = '<?php echo $metaString; ?>';
// DUMP VALUE TO THE SCREEN USING ALERT....
alert(SITE_META_DESC);
</script>
Here is another alternative... it is concise and simple; however it may not give you the result you want:
OPTION NR. 2
<?php
//SIMPLY CHANGE THE URL TO THE URL YOU DESIRE
$metaTags = get_meta_tags('https://yahoo.com/');
$metaDescription = $metaTags["description"];
var_dump($metaDescription);
//USING A DATA-SOURCE ARRAY:
$arrURLs = array("http://sbb.ch", "http://alibabaexpress.com", "https://yahoo.com", "http://badoo.com" );
$arrMetaDescs = array();
// LOOP THROUGH THE $arrURLs AND GET THE META
// AND STORE THE RESULT IN AN ARRAY TOO.
foreach($arrURLs as $url){
//IF YOU WANT YOU COULD USE THE URL AS KEY FOR EASIER IDENTIFICATION
try{
$metaTags = get_meta_tags($url);
if($metaTags){
$key = preg_replace("&(https:\/\/|http:\/\/|www\.|\/.*$)?&", "", $url);
$arrMetaDescs[$key] = $metaTags["description"];
}
}catch(Exception $e){
}
}
var_dump($arrMetaDescs);
?>
<script type="text/javascript">
//EXPOSE THE META TO YOUR JAVASCRIPT USING A GLOBAL VARIABLE (FOR EXAMPLE).
var SITE_META_DESC = '<?php echo $metaDescription; ?>';
alert(SITE_META_DESC);
// IN THE CASE OF ARRAY-BASED META-EXTRACTION,
// STORE THE META VALUES IN JSON FORMAT FOR JAVASCRIPT
var ARR_META_DESC_EXTRACT = '<?php echo json_encode($arrMetaDescs); ?>';
console.log(ARR_META_DESC_EXTRACT);
</script>
Here's one way to do it:
Set up a page source_getter.php on your server and include the following code (from this answer):
$html = file_get_contents('your_url_here');
echo $html;
If you're using jQuery, run a request like this:
$.ajax({
url : 'source_getter.php',
success : function (result) {
doSomethingWithResult(result);
// result will equal $html from your PHP code
},
error : function () {
alert("error");
}
})
I haven't tested this code specifically but it should work just fine.
This is probebly the easy way to do it:
<?php
// Get Meta Tags from the given URL
$tags = get_meta_tags('http://www.example.com');
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var urlMetaDesc = "<?php echo $tags['description']; ?>";
alert(urlMetaDesc);
</script>
</head>
<body>
</body>
</html>
Keep in mind though that if a website didn't set the meta-description tag, nothing will be returned and no alert will be shown.
I want to push a php variable to javascript. The code is below but does not seem to work. Can anyone show me how to do this?
ticks.push(<?php echo json_encode($new); ?>);
Is this what you're looking for?
ticks.push(JSON.parse('<?= json_encode($new); ?>'));
Or broken down:
var json = '<?= json_encode($new); ?>';
var obj = JSON.parse(json);
ticks.push(obj)
also addressed in this issue:
Accessing an array in PHP from Javascript/jQuery
can you try this
var tricks = [
<?php
foreach ($new as $n) {
echo '"'.$n'", ';
}
?>
];
you can use websocket to do such like functionality; in it you can send the result back to the client from the php code when it is ready one good example on that is how stackoverflow notify you when there is new question, or when they notify you if the post is edited.