Transferring data from PHP to Javascript for processing [duplicate] - javascript

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?

Related

Is there a way to execute a php include after the Page loaded? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
Im trying to rerun an php include after I changed it with js
The php file ist connectiong to an db and only gets the data which is requestet with the get variable in the url
<output id = "ulid">
<?php include ("http://localhost/Test/testx.php?testget=HRA"); ?>
</output>
And then i change the file with innerHTML from output (after an onchange event from)
var skala = document.getElementById("skalaRock").value;
var y = '<\?php include ("http:\/\/localhost\/Test\testx.php?skala='+skala+'"); ?>';
document.getElementById("ulid").innerHTML = y;
The output is '<?php include ("http://localhost/Test/testx.php?skala='+skala+'"); ?>'
that is the right file, but how can I get the file to execute? And dont just show the php command?
You can use .load method of jQuery to load the php file after the change event
Below is the given link of jQuery documentation of load()
https://api.jquery.com/load/
PHP runs on the service side.
and the page runs on the client side.
you cant change the code on the servie side from the client side.
When you do soemthing with JavaScript in response to an onchage event, this happens on client side, in the browser.
If you want any php code to be executed (on server side) from there, you will have to send an Ajax request to the server.

AJAX and PHP Can I Set a variable onclick? no Jquery

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.

Define a string java with a js variable [duplicate]

Ello there,
I'm trying to assign the value of a javascript variable to a java variable. But I don't have clue how to do this? Say for example I have this:
<html>
<head>
<script type="text/javascript">
function return variable(){
var a = "hello";
return a;
}
</script>
</head>
<body>
<%
//The java code
String b = //how do I get that javascript variable here?
%>
</body>
</html>
Java script plays on browser where java code is server side thing so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server
HTML
<input type="hidden" id="hiddenField"/>
make sure this fields lays under <form>
Javascript
document.getElementById("hiddenField").value=yourCalculatedVariable;
on server you would get this as a part of request
You need to read something about a JSP's lifecycle. Try this: http://en.wikipedia.org/wiki/File:JSPLife.png
JavaScript runs on the client, but in order to change the jsp, you need access to the server. This can be done through Ajax(http://en.wikipedia.org/wiki/Ajax_%28programming%29).
Here are some Ajax-related links: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
The answer is You can't. Java (in your case JSP) is a server-side scripting language, which means that it is compiled and executed before all javascript code. You can assign javascript variables to JSP variables but not the other way around. If possible, you can have the variable appear in a QueryString or pass it via a form (through a hidden field), post it and extract the variable through JSP that way. But this would require resubmitting the page.
Hope this helps.
JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.
I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.
you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side.
you may set the value to a hidden html element and send to servlet in request just in case you want to use for further
As JavaScript is client side and JSP is Server side.
So Javascript does not execute until it gets to the browser,
But Java executes on the server.
So, Java does not know the value of the JavaScript variable.
However you assign value of Java variable to JavaScript variable.

Escape <?php ... ?> on javascript file

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.

Passing JavaScript variable to smarty

I'm having some trouble passing a variable from JavaScript to smarty.
Example:
{literal}
<script type="text/javascript">
var js_variable = 110;
</script>
{/literal}
jQuery('div.fakbox_msg').html("{/literal}{lang_sprintf id=100013 1=js_variable}{literal}");
You cannot do that in an easy way. PHP, and by extension Smarty, is parsed and run on the server side before the browser get the data. JavaScript is run on the client side when the browser parses the HTML, CSS and Javascript that the server sent.
You will have to make a new HTTP request in some way, sending the new data. You can do that by reloading the entire web page and sending stuff in the querystring (after ? in the URL), or slightly more advanced by doing an Ajax call from your JS code and make JS do the changes of the page that you desire. The latter is more complex and requires some knowledge of Javascript, but the page does not need to be reloaded in its entirety.
for more info :
Assign JavaScript variable to Smarty variable
I never used Smarty, so I may be wrong, but from what I see on your code. this should work:
jQuery('div.fakbox_msg').html("{/literal}{lang_sprintf id=100013 1=" + js_variable + "}{literal}");
Smarty cannot use client side variables, such as the ones created by JavaScript.

Categories

Resources