Get php variable to javascript from laravel controller - javascript

Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
I tried to make and echo in Javascript and doesn´t work. some ideas?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.

Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com.
The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer

You can simply get PHP variable in JavaScript like this:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert to see the result in popup dialog too:
<script>
var casa = alert('<?php echo $casa ?>');
</script>

Related

How to get "$.Post" variable in another site

i search internet for my question and i doesn't found how to get my $_POST on another page. Please help.
game.php:
<?php
session_start();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
}
presave.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno']
?>
Undefined array key picture
Your question seems incomplete in my opinion. There are many things missing from your question. From your image I assume you are using it on local server. There are one thing that looks weird is this:
`$.post( "save.php", { drzewo: drzewo } );`
Where is this save.php file stored? Is it stored in your root file? Or along with the operating file. Put a "/" before save.php and see what happens.
There is another thing that seems awkward is your image is showing there is a presave.php file. But I found nothing about that file in your question details.
I can see that you put a redirecting code in your script. JS is not supposed to work like that. What happening here is it is doing an asynchronous operation. That is why PHP can't get the data and showing you a error. If you want to send data send it in a form. Or you can put a redirection in your PHP code after getting the post data. Since it is an AJAX call you can see some reports in your console.log() with the response data.
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
Let's analyze these 2 lines of code.
When you send a post request through javascript, it goes through an ajax request and the browser waits till the save.php completes working it's code and returns to the ajax. Here the save.php has received the $_POST data and has processed it.
This processed data by save.php will not output in the browser. It will go to the post (ajax) callback function. If you want to display the data, you need to use a callback function. See this https://www.w3schools.com/jquery/ajax_post.asp for a simple usage of $.post() function.
In the next line of your code you are redirecting your browser to save.php without sending any $_POST data. Since now your save.php does not have any information about $_POST["drzewo"] it throws an error Undefined array key "drzewo" .
Therefore instead of window.location.href page redirect, you need a callback function with your $.post() function. I hope now you understand why you are getting this error.
[Edit]- I have added some code for your better understanding. You can refer to this excellent "JQuery Ajax POST Method" tutorial from freecodecamp.org. https://www.freecodecamp.org/news/jquery-ajax-post-method/
game.php
<?php
session_start();
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" onclick="save();">Click this</button>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post("save.php", {
drzewo: drzewo
},
function(result) {
alert("This result contains the output from save.php : " + result);
//Write here the code you want to execute after the POST request is successfully completed.
}
);
}
</script>
</body>
</html>
save.php
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno'];
If you want to pass data from one URL to another, use query string. $.post() makes a POST request, but it seems like save.php is not an endpoint but actually a page.
In other words, you can do this:
window.location.href = `save.php?drzewo=${drzewo}`;
And then on save.php simply read the value from $_GET:
<?php
session_start();
$_SESSION['drewno'] = $_GET["drzewo"];
echo $_SESSION['drewno']
?>

Sending JS object with AJAX not updating PHP script [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

PHP echo is not working with JQuery post data [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

Is it possible to store a JavaScript function that returns a string in a php variable?

something like :
<?php
$phpVar = "<script> function jsFunc(){ return 'Hello world';} </script>";
?>
is that even possible? if no, is there a way to do same thing?
If Ajax is the only solution, how do I retrieve a value of an input and store it as a php variable?
I tried something like this and it doesn't work.
<input type=text value="hello" id="myInput">
<?php
$phpVar = "<script>
function jsFunc(){
var inputVal = $('#myInput').val();
return inputVal;
}
</script>";
?>
PHP runs at server side and JS in the browser (apart node and related technologies).
Only way you can do something similar would be do to render from PHP in your HTML a tag <script> </script> and add you JS function and executing it there.
Al thought I would definitely not suggest it.
you can store this string in variable. for php interpreter it will be just a text string, nothing else. but when browser receives this data, string will be recognized as js function.
UPDATE
in this case easiest way for send data from browser to server is use a form. there is many examples in the web how to do it.

PHP function return value to JavaScript

I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.

Categories