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

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.

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;
}

ajax query on secondary page

Background
I've read through several posts and tutorials here on AJAX, and I've gotten it to work great - on one page, but I'm still new to utilizing AJAX so I hit a rough spot that I can't understand how to fix.
I have my main page, ajaxtest.php which contains a drop-down with this code:
<a>
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select name="PMName" onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?></select></a>
which pulls this function:
<script>
function showUser(str) {
if (str !==".PM") {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
Sending the selection from the database off to my second page, getuser.php.
The user then sees the rest of the initial page populated with the results of getuser.php, which contains the bulk of my code and the HTML tables populated with the SQL info.
This is working fine.
Issue
My issue stems from the fact that once (and pardon my lack of technical jargon,) getuser.php is populated into the <div> that is inside of ajaxtest.php, I can't utilize any other JavaScript or AJAX functions or the entire page just refreshes as if I were to reload ajaxtest.php again from scratch and it puts me back to the initial blank screen with the dropdown menu.
On getuser.php, within the <form> that surrounds the entire table, there is a submit button:
<form action="" method="POST" onsubmit="test()">
and
<input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">
and this is supposed to link to my JavaScript test() function that simply reads:
function test() {
alert("yo");
}
but when I click the button, the entire page refreshes instead of executing this function. Why is this?
If I manually go to localhost/getuser.php?q=John%20Doe instead of "having this page load inside of my ajaxtest.php <div>" and click the button, it works just fine and I get the JavaScript alert to pop up. What am I doing wrong here?
Try editing the function test() to return false
function test() {alert("yo"); return false}
and change the line
<form action="" method="POST" onsubmit="test()">
into
<form action="" method="POST" onsubmit="return test()">
Now it shouldn't refresh the page. Function used in onsubmit needs to return true or false.

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.

Acess php variable in javascript and vise versa

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.

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