I'm not understanding AJAX, but I've heard it's used for this type of thing. Or if you have another solution, that's fine too. I've seen similar questions, with bits of code but no complete examples that I can understand. I have a webpage with no php variable set. I want to click a button, and without reloading the page, set a php variable and run the full code again and see that variable displayed. I'd love to see a working example without jquery. I assume I'd need 2 webpages. Call them page1.php and page2.php
Something like this...
<!Doctype>
<html>
<head>
<script type="text/javascript">
// some kind of ajax formula here...
</script>
</head>
<body>
<button onclick='callAjax()'>link</button>
<?php
if (isset($test)) echo $test;
?>
</body>
</html>
and page2.php would simply be used to set the variable like...
<?php
$test=123;
?>
It sounds like you want to post to a php script that returns a variable. This can be accomplished by using xhr but jQuery makes it easier using $.ajax.
There is a good intro to this here ... https://www.w3schools.com/xml/ajax_intro.asp
PHP is server side and Javascript is client side. Your Javascript will 'post' to the php file and the php file will return a response which the page can use without reloading. You can check if the php is responding by using the developer tools of your browser and looking at the network tab in chrome for instance. The shortcut to Dev tools is F12.
Related
I am using below code for redirect users.
<?php
$redirect_to = "https://google.com";
$redirect = "https://yahoo.com";
echo "<script>location.href = '".$redirect_to."';</script>";
header("Location: $redirect");
exit();
?>
I prefer to use javascript redirect, but in somecase when user have not javascript enabled in his browser, I am using PHP redirect as backup redirect but sometime I am getting header already sent error on php redirect code and sometime I am not getting that error.
if I use exit() after redirect by javascript, I will not able to
redirect user if he have javascript disabled in his browser.
my question is there any way to stop php code if javascript redirect was success? I am not getting idea what I have to do for handle my situation.
Let me know if any expert can help me to solve puzzle.
Thanks!
Well, you are a web developer using PHP and Javascript.
One thing to remember, PHP code always runs first on the server. It's a server-side language, so no matter how you arrange your lines of code, your php code will finish running. Then, the client source code (HTML, CSS, JavaScript) is sent to the browser and executed on it (Client-side).
And next, the job of redirecting is always on the client side, the server doesn't actually redirect people to another site. What actually happens is that your php source code generates a redirect command that sends the browser for a redirect.
Another thing, in php, any work related to the header() function needs to be executed before any content is generated. That is, it must run at the top, before any method echo, exit, print,... or content block.
When deploying a php application, if you already use header("Location: ....") then it makes no sense to use javascript directives, as the browser will prioritize handling the redirect in the header first! !
The source code should really be:
<?php
$redirect = "https://yahoo.com";
header("Location: $redirect");
?>
Another way if you still prefer using javascript redirects and are compatible with javascript disabled, that is to use the tag meta[http-equiv="refresh"]. Refer to the following example:
<?php
$redirect_to = "https://google.com";
?>
<meta http-equiv="refresh" content="5;URL='<?php echo $redirect_to; ?>'" />
<script>location.href = "<?php echo $redirect_to; ?>";</script>
The number 5 appears in the content of the meta specifying the countdown (seconds) the browser will redirect when the page has finished loading. When the page cannot execute javascript, after 5 seconds the page will redirect.
I would like to use js code, which works with php variables.
My situation now:
mainFile.php
<?
$myPHPvar = 1234;
?>
<html>
<body>
MY CONTENT
<script>
var myJSvar = <? echo $myPHPvar; ?>
</script>
<script src="myFile.js"></script>
</body>
</html>
myFile.js
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
console.log(myJSvar);
This works ! But I would like to change this structure. I would like to move the myJSvar definition out from main file into the jsFile.
But If I move this line var myJSvar = <? echo $myPHPvar; ?> into the myFile.js it will not work, because this is not an php file.
Not I thought that this could be a solution:
I rename the myFile.js to myFile.php and change the code like this:
// Here some js code where I access the myJSvar, which was set by $myPHPvar before
<script>
var myJSvar = <? echo $myPHPvar; ?>
console.log(myJSvar);
</script>
and in the mainFile.php I changed <script src="myFile.js"></script> to include('myFile.php');
This works !
BUT:
First question of all: Is this a good idea to do it like this?
Second: The "problem" now: All my files are now php files, also the files, which includes mainly js code. That's not very beautiful, because now I can't see on the first view, which is an js file and which is a php file.
Thank you for your support !
Using PHP, echo the values to hidden HTML fields on the page.
When you know the page is done loading, read them back out using JavaScript.
Note, Ideally, you'd just make the data a separate AJAX/xhr/fetch call to a URL (JSON or XML formatted data is nice for this), but as a stop-gap, hidden fields will do the trick for basic PHP pages.
Similarly, you can echo some inline JavaScript (tags and all) and reference the variables elsewhere. This approach will work but is often referred to as "spaghetti code" because the intertwined front-end (JavaScript) and back-end (PHP) code makes for tricky debugging and does not scale well to larger code projects... months or years after, developers will find themselves scratching their heads as to where code lives, how it's generated, where new code should be placed, etc.
You can do it like this. And there's nothing really wrong with it. You have to bring the data to the client browser somehow. You can do this with: 1. set php variables in the DOM 2. XHR call or 3. cookies
This can be achieved by generating the JS file dynamically... You can create a PHP file that would generate the JS dynamically like:
Note: THIS METHOD IS HIGHLY NOT RECOMMENDED. THIS IS FOR YOUR INFORMATION AND KNOWLEDGE ONLY.
myFile.php (The JS equivalent file)
console.log(123)
Your HTML file
<script type="text/javascript" src="a.php"></script>
But this is highly not recommended because JS files are static resources that can be cached. Using this method would request the JS file every time the page loads (where it will only be transferred at first load only if its static).
The best method is to keep the dynamic variables in your HTML and then include your static JS files which will use these variables.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I have a variable set in the PHP with some relevant information that I need to process with the Javascript, but I can't figure out how to port that information over to the Javascript.
I first create a test variable in one javascript file, x
Test='<--!TestString-->'
In the PHP I use str_replace to alter the value of the variable with the relevant data
str_replace('<--!TestString-->',seralize($data), x)
Now I try to see if the data has been added in a different file using alert(Test)
and it shows me <--!TestString-->
Is there a better way to do this and have the data show with the alert function so I can start processing it?
I don't understand your approach at all.
Of course the ideal way to accomplish is to use AJAX to grab data from the server and get into the client side so you can work with it in Javascript. (You can Google "Ajax php and javascript")
The easiest way to accomplish this is to just print the variable in PHP but in a context that it will be available to JS in the client.
<html>
<body>
<script>
var x = <?php echo json_encode($phpvar); ?>;
console.log(x);
</script>
</body>
</html>
I won't argue with anyone that disapproves of that approach but its easy and it works.
Use <script> tag?
<script> my_value = 'some'; </script>
Use AJAX?
// with jQuery:
$.get('/data.php',function(data){/*...*/})
PHP is executed on your server, Javascript in the client (ie. Browser of the user visiting your website). So PHP can not change variables of your JS code once the page has been sent to the browser. But what you can do is set the variable in PHP and insert it in your JS code like this:
<?php
$test="some important info here";
?>
<script>
alert("<?php echo $test ?>");
</script>
If you need to change the variable by the server, you would need to use AJAX to load the new value.
As mentioned before we might not be understanding your approach to your problem.
PHP is executed on the server side while Javascript in the client. PHP cannot change variables of your Javascript code once the page has been sent to the browser. What must be done is to invoke PHP by using preferably AJAX with jQuery.
Look into AJAX PHP with JSON. Perhaps you are looking into the json_encode(value) function?
I'm having an issue creating / setting a cookie on the click of a link, is there a proper way to do this? Either PHP or Javascript is fine.
<html>
<a href="2.html" id="cookie">
<div class="yes">
<p>Yes</p>
</div>
</a>
</html>
<script>
$("a#cookie").bind("click", function() {
});
</script>
<?php
setcookie( "cookie")
?>
Obviously both JS and PHP wouldn't exist in the same instance it was just to show what I have.
You can't mix JavaScript and PHP. By the time your JavaScript code loads, your PHP code would have already executed.
In your case, it may be easier for you to set cookies without using PHP.
$("a#cookie").bind("click", function() {
document.cookie="cookie=value";
});
Here is a good example of setting cookies with javascript w3schools demo And I doubt it will be possible to set cookies to other domains except the origin of the page.
With PHP it is done in the next way: 1st you send http request to the server using javascript native xhr or jquery etc. and then php script must set cookie headers and return back to client. In this case browser will automatically set cookies received in headers.
I'm busy doing server side and client side validation for magento. this validation works fine on server side (php)
on the client side i am using javasrcript.
When i started on this. i had my javascript embedded on a phtml file and everything was working as expected.
because i am using magento so I decided to inject the javascript file via page.xml
When I added the javascript code instead of getting the message pulled I get the php as is.
Here is my javascript:
function DefaultAddressErrorChangeNotAllowedMessage() {
alert("<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>");
return;
}
I run this when a user hit the onclick it will point to this function DefaultAddressErrorChangeNotAllowedMessage()
and the
<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>
will be populated as is.
but when I embed this directly to a phtml file it pull the correct message.
I there a way for javasrcipt that I can use to escape the php and get the correct message which is pulled from config.xml
PHP is rendered server side only. If you need to "inject" PHP specific values to your javascript, then you either need to render the actual value as part of the output of the php script, or you need to take a new roundtrip to the server, using Ajax.
Javascript is clientside, PHP is server side, so all php has been evaluated when javascript is loaded. This means, you can alert php echos, but you can't run PHP operations or any PHP logic in Javascript. You need ajax for this.
sorry for my clumsy answer, but maybe you lost the simple things.
I see that your javascript contains php tag, so i think you should insert your javascript code into .php extension because .js extension can't recognise the php tag.