Acess php variable in javascript and vise versa - javascript

Suppose I have php page index.php
<?php
$x=$_POST[sent] // I get some value in #x
?>
<html>
<head>
<script>
function getVar()
{
var x= <How to fetch $x from php code>
alert(x);
}
</script>
</head>
<body>
<button type="submit"> click </buttton>
</body>
</html>
How can I fetch $x in getVar(_) function?
Or another case some variable is in JS then getting it into php code?
Is it possible or not?
Actually I have index.php and through ajax request loading new page url.php. I want to send few variables to url.php and want to access them in JS code in it.
Here is my ajax request:
var id=mydata.id; // Guess I am getting some data here
$.ajax({
url:'url.php'
,async: true
,cache: false
,dataType: 'html'
,success: function(data){
$('body').html(data);
FB.XFBML.parse();
}
I want to send id in ajax request to url.php. I will fetch it as $x and want to use it in JS code.

php to javascript can be done by using
<?php $x = "iam a php variable"; ?>
<script>
function getVar()
{
var x= "<?= $x; ?>";
alert(x); //alerts **iam a php variable**(value of $x from php)
}
</script>
The vise versa can be done via Ajax. Here is the simple example
<script>
function showUser()
{
var str= "iam a javascript variable";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText); //alerts response from php
}
}
xmlhttp.open("GET","new.php?q="+str,true); //you can send request through post or get methods
xmlhttp.send();
}
</script>
Here, i am getting a javascript variable in php through ajax using GET.
In new.php, i am just printing out the request received via GET
<?php
print $_GET["q"]; //prints **iam a javascript variable**(value of str from javascript)
?>

Communication between PHP and Javascript is a classic example of client-server communication. In this case, PHP is your server application and Javascript is your client application. There are many protocols established for this communication, but you should take a look at AJAX and RESTful services.
In order to understand what is going on, i suggest that you read this tutorial on HTTP and REST, from a PHP programmer point of view. When designing a client-server application, PHP would "generate" all the content, by applying business logic and communicating with the database, and Javascript would ask PHP for this content on certain events (click, show table, etc). PHP, instead of outputting HTML, would output XML or JSON, so you can parse and show that data in Javascript.

Transfer boths ways:
function getVar($var)
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$phpVar = xmlhttp.responseText;
return $phpVar;
}
}
xmlhttp.open("POST","/yourPage.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("var=" + $var);
}
And then on yourpage.php:
<?
if (isset($_POST["var"])) {
die($_POST["var"]);
}
?>

If you're simply trying to get pass the value of $x variable to JavaScript, then it can be done as follows:
function getVar()
{
var x= "<?php echo htmlspecialchars($x); ?>";
alert(x);
}
Here's a working example:
<?php
$x = $_POST['sent'] // I get some value in #x
?>
<html>
<head>
<script>
function getVar()
{
var x= "<?php echo htmlspecialchars($x); ?>";
alert(x);
}
</script>
</head>
<body>
<button type="submit" onclick="getVar()"> click </buttton>
</body>
</html>
If the $x variable is received by the script correctly, then it will be alertd when you click the button.

Related

AJAX and PHP sending "HTTP get request" to the same page

My application gathers some client related information via JavaScript and submits it via AJAX to a php page.
See the code below:
index.php
<html>
<head>
<script>
function postClientData(){
var client_data = new Array(screen.availHeight, screen.availWidth);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == client_data[0]){
document.getElementById("message").innerHTML = "Client data successfully submitted!";
}
}
};
var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
xmlhttp.open("GET", parameters, true);
xmlhttp.send();
}
</script>
</head>
<body onload="postClientData()">
<span id="message"></span></p>
</body>
</html>
ajax.php
<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>
I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. When I try adding the code, I probably get into a endless loop since I don't get my "success" message.
How can I solve this issue?
Correct, IMO I would definitely keep this specific logic separated in the ajax.php file.
If you do really want to merge, add it to the top of index.php (before printing data):
if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
// Execute specific logic and exit to prevent sending the HTML.
exit;
}

php javascript code to call php function from javascript

Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..
If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.

Insert Javascript Code into HTML from PHP response [duplicate]

This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Hi I am trying to insert a JavaScript code in my HTML document using the following AJAX-PHP code inside the function called exJS(), following is the content of the function exJS()
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
This what ajax.php is
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
Now whenever I execute this function exJS() the alert doesn't work but when I view the source code using F12 and see the contents of the div#myDiv" I see that the entire script is embedded inside the div but still the JavaScript for some reason is not getting registered.
I even tried accessing the JavaScript variable testVAR, I see the variable in the source code when I hit F12 but when I try to access that variable I get an error, that no such variable is defined.
Please note that it is simple example so there is no error and that the PHP code is echoing just fine, all the contents are returned from the PHP code, when I view the code and see what are the content of the div element the entire PHP echo content is present there but still not executing.
Also if I open the ajax.php file directly it works fine, I mean I get the alert message, but the same thing doesn't happen when I execute the function jsEx() the JavaScript code gets inserted into myDiv but nothing happens, no alert.
BTW jQuery has a specific AJAX function to get a script: http://api.jquery.com/jquery.getscript/
If you want to avoid jQuery a workaround would be to make it so you echo an iframe and from that Iframe you link to the PHP generating the actual Javascript.
E.G. a sample ajax.php
if( isset($_GET['getscript']) ){
header('Content-type: application/javascript'); #or header('Content-type: text/javascript');
echo 'alert("The script is working.")';
exit;
}
echo '<iframe src="ajax.php?getscript=1" frameborder="0"/>';
?>
try this:
tested in my WAMP (win 7, php 5.4) & works fine in IE11,Chrome,Safari,FireFox and Opera (I don't have any other ;-) )
index.html:
<head>
<title>Testing DYNAMIC JS</title>
<script type="text/javascript">
function exJS(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var script = document.createElement('script');
script.onload = function() {
// alert("Script loaded and ready");
};
script.setAttribute("type","text/javascript");
script.text = xmlhttp.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
}
</script>
</head>
<body onload="exJS();">
</body>
</html>
in ajax.php try:
<?php
echo 'alert("Hello World"); var testVAR = "Hello World";';
?>
if you want to run script from within a div:
use:
javaScript:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var MyDiv=document.getElementById("myDiv");
var arr = MyDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML);
}
and php:
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
hope it'll help you.

whole php code getting printed instead of just what's in echo

i have made a very small code in which i just want to show what's in echo through div with ajax but it shows me the whole php script instead of what's in echo , can someone help me
<html>
<script type="text/javascript" >
function test() {
xmlHttp=new XMLHttpRequest();
if (xmlHttp !== null) {
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4 && xmlHttp.status==200) {
var response = xmlHttp.responseText;
alert("Match");
alert(response);
document.getElementById('show').innerHTML = response;
}
}
}
xmlHttp.open("GET","try.php",true);
xmlHttp.send(null);
}
</script>
<body>
Enter answer: <input type="text" onKeyUp="test();"><br />
See returned value: <div id="show"></div>
</body>
</html>
this is my php file , i just wanted to check if it prints what's in echo so it's small
<?php
echo "i just want to see if this get's printed";
?>
Check the Network tab in your browser's development console. In Chrome, press F12, go to the "Network" tab, execute your test() function, and check the appropriate response in the Network results. You can see the result in the "Response" tab. Similar consoles should exist for other browsers.

Need a javascript function in return of Ajax Call

I am trying to get the javascript function in ajax call. My code works fine and returning back my javascript code but there is a problem in my received javascript function. Here is my code for Ajax..
function media_type(id)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText);
}
}
xmlhttp.open("GET","video/media_type.php?cat_id="+id,true);
xmlhttp.send();
}
And her is the code where i am returning a simple hello world alert box.
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<script type="text/javascript">
alert("hello World");
</script>';
}
I am receiving the code back exactly but code is not executing. Please tell me how i can fix this issue. Thanks in advance.
Can I ask why you need to return JavaScript from the server? How about you return a simple response (string, boolean, number) from the server, and execute something that already lives on the client based on the return value? Much safer and easier. It may not be the solution you are looking for, but your js-fu will be much stronger for it.
Just return the JS that you want to execute (alert("hello World");) and make an eval. Remove <script type="text/javascript"> and </script>
eval(xmlhttp.responseText);
will be:
eval('alert("hello World")');
i will try with this
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<html><script type="text/javascript">
alert("hello World");
</script>
</html>';
}
i think this line is creating problem
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText)
that is
eval(document.getElementById("asad").innerHTML='<script>alert("Hi");</script>';)
getting converted to
eval(document.getElementById("asad").innerHTML='< script > alert("Hi");</script>';)
I had this issue the other day...
you have to set your header in the php page to Content-Type: text/javascript; charset=utf-8
Here is the Entire Code to make this work
For your php file
<?php
header("Content-Type: text/javascript; charset=utf-8");
echo'<script type="text/javascript">
alert("hello World");
</script>
';?>
and here is the Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
$.ajax({
type:'POST',
url:'toget.php',
success:function(d)
{
$(document).append(d);
}
});
</script>
//try using this
<?php
if($num_rows==0)
{
//echo("Sorry no record found.");
?>
<script type="text/javascript">
alert("hello World");
</script>
<?php
}
?>

Categories

Resources