Reputation: 2942
I am developing my laravel app. I have this function in javascript-
function abc(){
var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>';
}
Now, when the page is loaded, the variable 'x'
is loaded with either '1'
or '0'
. I want the php to be rendered everytime I call the function abc(). So, for instance, at time of page load 'x'
is '1'
but if the function is called after 20 secs of page load, I want the php to be rendered, so that the value of 'x'
can change based on the changes happening on server in those 20 secs.
Btw, I am aware of ajax. I am asking if there is some simpler solution.
Upvotes: 0
Views: 232
Reputation: 6294
Ajax is the way to go. Please take a look into other answers.
This is answer is not a general good approach, but it answers what you exactly ask. Im just posting this cause i don't know what you have in mind so it may be usefull for you.
start by putting your js function in onload of body and change the name a bit
<body onload="original_abc()">
then change your js function name accordingly
function original_abc(){
var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>';
}
now use this with the name of your original function
function abc()
{
location.reload();
}
as a result, everytime you call abc()
the page will reload, and the function original_abc
will execute.
may be useful in some very specific cases, but in general, use ajax.
Upvotes: 0
Reputation: 6908
As you're using Laravel, take a look at setting up a route to return the value you're looking for. There are plenty of examples here: http://laravel.com/docs/routing . As your example is referring to users, take a look at this doc on RESTful controllers, as the example there is specifically a UserController. http://laravel.com/docs/controllers#restful-controllers
Something like this would let you grab the data you need on the PHP-side (I'm assuming you're checking if the user's initialized):
class UserController extends BaseController {
/* other controller logic above here.. */
public function getInitStatus($id)
{
$user = /* Whatever code you get the user with based on ID */
return Response::json($user && ($user->first_name == "" || $user->number == "");
}
}
Then setup a route like:
Route::controller('users', 'UserController');
Now that you're set on the server-side, there are plenty of ways to just call it in JS (e.g. http://api.jquery.com/jquery.getjson/ ).
function abc() {
$.getJSON( "/users/" + userID, function( x ) { /* do whatever you were going to do with x */ });
}
Upvotes: 0
Reputation: 850
This isn't possible without AJAX because the JavaScript code is static once loaded on the client browser. The values do not change unless additional script executes to override those values asynchronously.
Upvotes: 1
Reputation:
function abc(){
$.ajax({url:"phpfile.php",success:function(result){
$("div").html(result);
}});
}
setTimeout(function(){ abc(); },20000);
Try this using ajax
Upvotes: 1