Convert WebStorage (JS/JQuery) content into Blade-ready variable - javascript

so I'm currently saving local data via WebStorage. Was wondering if there's a way to convert it to a Laravel Blade-ready variable upon page load. Here's what I've done so far.
$(document).ready(function () {
var data = JSON.parse(localStorage.getItem("data"));
// initialize php code
<?php $var = ?> data <?php ; ?>
});
However this doesnt work since it breaks PHP ruling

Related

How to place php variable in javascript object in different? [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Executing PHP code inside a .js file
(5 answers)
Closed 2 years ago.
I am trying to fetch data from php, store it as json and load it into my javascript code.
I stored my variable in php like this:
$data = array[];
$data = json_encode($raw_data);
Now I want to retrieve that data and use it in my javascript file.
I tried to use the following code in my js file:
var data ="<?php echo $data ?>";
[screenshot]: https://i.stack.imgur.com/pDfsf.png
If the data is only needed once on page load, you can use a script bloc inside the PHP code and then use a JS function to fetch it. But if data is being updated according to the user's interaction with the page, keep in mind that you can't send data from server side in PHP to the client side in JS without using AJAX.
I suggest you read about and use one of these 3 methods:
XHR
fetch
or axios
You are declaring the string to the variable data by using quotes.
Please remove the quotes and that would behave as per your expectations.
So your code should be replaced by the below lines.
var data =<?php echo $data ?>;
var data = <?php echo $data ?>;
or
var data = JSON.parse("<?php echo $data ?>");
The most obvious problem is your quote marks, which make the variable a string in JavaScript, rather than a complex object with a data structure. So any references to properties etc in the variable would not work. The quote marks should be removed so that the data is rendered as an object literal into the emitted JavaScript.
But there's another signficant issue: if this is being done in a .js file as you state, then the PHP interpreter is not running there, so the echo won't work (quotes or no quotes), because it isn't executed by PHP and turned into data. You'd just see the PHP code directly embedded in the JS code.
You'd have to echo the data into a script block in the .php file, then call the appropriate function in your .js file and pass the data as a parameter. This will work nicely if the data is only needed once.
e.g.
PHP file
<?php
$data = array[];
$data = json_encode($raw_data);
?>
<script src="someJsFile.js"></script>
<script>
var data = <?php echo $data ?>; //inject the data into the JS as an object literal
someFunc(data); //pass the data to a function in someJsFile.js
</script>
JS file:
function someFunc(data) {
//your code to process the data
}
If you need to keep it updated during the lifetime of the page, then you'll need AJAX to be able to request new data from the server, as suggested in one of the other answers.

how to hold javascript variable in php variable

I want to use javascript variable as php variable. I am echo php variable then its print. but when i am use for fetching data from database its show an error
Notice: Undefined index: document.write(i)
here my code
javascript
var i=0;
function inc()
{
i+=1;
}
<?php $foo="<script>document.write(i)</script>"; ?>
php
code work for
echo $foo
code not work for
$i=$foo;
$query="select * from TABLE where id = $i";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_row($result))
{
echo $row[0];
}
Then It show This Error Notice: Undefined index: document.write(i)
PHP is server-side code that is run to generate a page. Javascript is client-side code that is run after the page is sent to the visitor's browser. Javascript can't affect the server-side code because the server code is done running by the time the Javascript runs. If you want to have a user's selection change the behavior of the PHP code the next time the form is loaded, pass a variable through a $_POST variable when the form is submitted.
If you want your PHP and Javascript code to be using the same value, have the PHP code write a Javascript variable initialization into the page's <head> section before any Javascript would run that would need to use it.
<script>
var i=0;
function inc()
{
i+=1;
return i;
}
</script>
<?php
$foo = '<script type="text/javascript">document.write(inc());</script>'; //Script function call which return the var i value to php variable
echo $foo;
?>

How to transfer a value on DB to JAVASCRIPT through PHP

<?php
// Connect to database server
mysql_connect("192.168.1.101/phpmyadmin/", "root", "praticas") or die (mysql_error ());
// Select database
mysql_select_db("logs_history") or die(mysql_error());
//---> at this point, I want yo pull a VALUE from a column called potencia_ativa and insert in
// the code JS below
mysql_query($strSQL);
// Close the database connection
mysql_close();
?>
//JS code-------------------------------------------------------------------------------------------
<div id="graphHolder" style="height:75%;width:100%"></div>
<script type="text/javascript">
setInterval(
function() {
var d1 = [];
for (var i = 0; i < parseInt(document.getElementById('number').value,10); i += 0.5) {
d1.push([ //----------> pull the value from the php/DB as a FLOAT
]);
}
$.plot("#graphHolder", [{
label: "Label",
data: d1,
lines: { show: true, fill: true }
}
]);
}, 1000);
</script>
Remember, PHP executes on the server and GENERATES the page that runs the Javascript on the client. Putting a value from PHP into the JS code is as simple as:
<script>
var foo = <?php echo json_encode('bar'); ?>;
</script>
If you need to send the PHP data over AFTER the page was generated and already send to the client, then you need to have the client execute an AJAX request to fetch that data from the server. Once PHP has shoved the page out the door, it's basically done and can't "reach out" to the client to do updates on its own.
Also: Note the use of json_encode(). You should NEVER dump output from PHP directly into a Javascript context without it. Anything else puts you at risk of generating JS syntax errors, which will kill the entire JS code block.
Why are you using Interval? Are you trying to update the displaying page data/value automatically after some time passed? That won't work, because if anything changes in database, It won't change in the displaying page, unless you use AJAX to call your php script and return some values, and then, change in the displaying page.
To get a value from PHP script to JAVASCRIPT, you just need to use the php clausule;
var test = <?php echo $variable; ?>
// echo for strings, ints, floats.
// print_r for arrays.
Of course, if your PHP script already injected the data into the page/the data is in the same page you're using JAVASCRIPT, assuming that you have already fetched the data, handled it and etc.

Assign js variable in PHP variable

function show_selling_price(sp,co)
{
$r=sp;
var e="select * from tbl where id='$r'; ?>";
document.getElementById('selling_price_'+co).value=e;
}
//php assign value does not work why?
//Please correct above code with proper description
You can not set a PHP variable from JavaScript. For example this is not possible:
var js_var = 10;
$php_var = js_var;
However you can set a JS variable from PHP:
var js_var = <?php echo $php_var ?>;
PHP is executed on the server side and then the result shows up on the browser.
JavaScript is executed on the client side once the server returns the response.
If you really need to pass a JS var then use AJAX to submit vars to the server.
It is not possible to assign a javascript variable to a php variable like your example above.
Javascript is a client side language whilst PHP is a server side language.
What you can do is to echo out php variables to a javascript code before it is rendered at the visitors web browser like:
<script>
var text = "<?php echo $variable; ?>";
</script>
If you are setting a variable in Javascript first, and then want to pass it on to PHP, you either have to use ajax, or use a html-form to post the information to the server

php and JavaScript zip code

What i'm trying to do is when a user enters a zip code in the input type i get the value of the input type store in origin_zipcode than add origin_zipcode inside the $url variable. From there it should run the xml and i should be able to display the city and state but it doesn't do that it im trying to make it work like
https://ship.onemorepallet.com/shipment/start?hsCtaTracking=296d76b9-a6fc-4140-83f9-de066c986716|9001d544-e760-4dae-ac72-36cc2922be55?utm_referrer=http%3A%2F%2Fwww.onemorepallet.com%2F
when you enter in the zip code
$("#origin_zipcode").keyup(function(){
var origin_zipcode = $("#origin_zipcode").val();
<?php
$url = "http://zipcodedistanceapi.redline13.com/rest/gNPseXsQyP3daTlKfRB3D0v0mPVC3jJj6zMlwec54fie8EZowAsaBXaXN5zQpjav/info.xml/origin_zipcode/degree";
$xml = simplexml_load_file($url);
$city = $xml->city;
$state = $xml->state;
?>
$(".labelzip").text(<?php echo $city,$state"; ?>);
});
You can't send a jQuery variable to a PHP script unless you refresh the page using one of a few possible methods. This is because while jQuery is client-side, php is server-side. After PHP has finished loading the page, it can't be used again without a page reload.
You can look at these questions for a possible solutions:
How to pass jQuery variables to PHP variable?
jquery 'variable' to php 'variable'
how to pass a jquery variable to php and then display it

Categories

Resources