Unable to call javascript from PHP - php

On the click of a button this Javascript is called:
var xmlhttp;
function register()
{
xmlhttp=GetXmlHttpObject();
alert("pass");
if(xmlhttp==null)
{
alert("Your browser does not support AJAX!");
return;
}
var url="register.php";
url=url+"?id="+uniqueid+"&name="+name+"&passwrd="+passwrd1+"&email="+email;
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
//alert("statechanged function");
if(xmlhttp.readyState==4)
{
//alert(xmlhttp.responseText);
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function testing()
{
document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}
And then this PHP script is called:
<?php
echo "<script type=\"text/javascript\">testing();</script>";
?>
The HTML has two DIV tags with IDs of mainbody and response:
<HTML>
<HEAD>
<SCRIPT SRC=javascriptname.js></SCRIPT>
</HEAD>
<BODY>
<DIV ID=mainbody>
<DIV ID=response>
</DIV>
</DIV>
</BODY>
</HTML>
I am unable to call the javascript from my php.
If anyone know what I am doing wrong or has an idea what I should do, it will be very helpful.

I don't think changing the innerHTML of an object and inserting a script will cause it to fire. I certainly wouldn't want to depend on that behavior.
Why not just do some kind of string comparison on the responseText, (in a case statement, for example) and then call the appropriate function?
EDIT: You could also remove the script tags, and call eval on the responseText, but eval is not the nicest function in the world.

I've successfully done this by passing the script tags within the string
Example:
<?php
function outputResults($var1)
{
$jsStringOut = "
<script type='text/javascript'>
document.write('".$var1."');
</script>
";
return $jsStringOut;
}
echo outputResults("Hello Stackers");
?>

Related

Ajax submit to self PHP file, but seems the PHP function do not execute

Ajax submit to self PHP file, but seems the PHP function do not execute.
<?php
function request(){
echo "<h1>requested</h1>";
}
?>
<html id="html">
<button id="btn_click" onclick="request1()">click</button>
</html>
<script type="text/javascript">
function request1(){
document.write("<h1>been clicked</h1>");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/index.php", true);
xmlhttp.send();
}
</script>
The JavaScript execute success, but seems the PHP code did not execute.
To add to what gibberish said, however, there's more to it. You must also keep in mind you don't seem to be executing the function at all.
A PHP function does nothing unless it is called.
function request() {
echo "<h1>Hello</h1>"
}
The function above will not be affected unless you call it:
request() // <h1>Hello</h1>
Also AJAX is best used when keeping requests simple. You send a request /path/to/file.php then that requests should return a plain text response or a JSON object, or a fully rendered static page if you are using a modal or some static item on your site.
/path/to/file.php
<?php
if( $_GET['clicked'] ) {
// do whatever
echo json_encode([
'user_id' => 1,
'total_clicks' => $_GET['clicked'],
'random_number' => rand(100, 999)
]);
}
The JS can easily handle the response:
function request(id) {
return fetch(`/path/to/file.php?clicked=${id}`)
.then(res => {
console.log(res);
body.innerHTML += res.user_id;
body.innerHTML += res.total_clicks;
})
.catch(err => console.error(err));
}
This will be the simplest way to have your server return information from the DB and make your page content as interactive as you need it to be,.
$_SERVER['HTTP_X_REQUESTED_WITH'] help us to detect an AJAX request
<?php
//Check Here Ajax Request
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
function request(){
echo "<h1>requested</h1>";
}
request();
die;
}
?>
<html id="html">
<body>
<button id="btn_click" onclick="request1()">click</button>
<div class="response" id="result" ></div>
<script type="text/javascript">
function request1(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
}
};
xmlhttp.open("GET", "./index.php", true);
xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // <-- ADD this
xmlhttp.send();
}
</script>
</body>
</html>

php variable to javascript via ajax

Ok im tring to get PHP variable to javascript variable via ajax.
i have some piece of php code to make this variable it look like this: (i wont put entire code because its working so only relevant code for this topic. i have new_m variable which is ARRAY and i want to pass it)
shuffle($new_m);
echo json_encode($new_m);
then i have js file which should catch that echo and it look like this:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
var myvar = new Array();
var myvar=JSON.parse(xmlHttp.responseText);
return myvar;
}
}
xmlHttp.open("GET", "showimage.php", true);
xmlHttp.send(null);
}
When this code is not on separate page like here and when is myvar is used inside function it works (because i have used this code on another page successfully). So i think my problem is not returning correct variable or not returning it on correct way.
and final piece of code is part where this myvar should be used it looks like:
<script type="text/javascript" src="js/shuffle.js"></script>
<title>undf</title>
</head>
<body onload="MakeRequest()">
<script type="text/javascript">
alert(myvar);
var pos = 0;
var imgs = myvar;
</script>
and nothing happens. im still new at this ajax and javascript. thanks for you help in advance.
Your problem is that when alert( myvar); is executed, the request to the server hasn't happened yet, and the variable is undefined (not to mention that I believe the variable is out of scope, so you can't access it).
You should set up the JS so that when the window loads, you execute the request to retrieve the data and then read it:
<script type="text/javascript">
window.onload = function() {
var myvar = MakeRequest();
alert( myvar);
}
</script>
You can then get rid of the onload within the <body> tag.
Note that I'm not entirely sure that you're returning the value from the MakeRequest() function correctly, since the return is within the xmlhttp callback and not in the function. You should investigate this and verify.

Validating with Ajax

I wrote some ajax code that sends values to a php file for validation but I have a problem with it. This is my ajax code:
<html>
<body>
<style>
#displayDiv{
background-color: #ffeeaa;
width: 200;
}
</style>
<script type="text/javascript">
function ajaxFunction(str)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById("displayDiv").innerHTML=httpxml.responseText;
}
}
var url="username_exists.php?username=";
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<input type="text"
onkeyup="ajaxFunction(this.value);" name="username" /><div id="displayDiv"></div>
</body>
</html>
and the above code send values to username_exists.php :
<?php
$username = trim($_REQUEST['username']);
if (usernameExists($username)) {
echo '<span style="color:red";>Username Taken</span>';
}
else {
echo '<span style="color:green;">Username Available</span>';
}
function usernameExists($input) {
// in production use we would look up the username in
// our database, but for this example, we'll just check
// to see if its in an array of preset usernames.
$name_array = array ('k','steve', 'jon', 'george', 'admin');
if (in_array($input, $name_array)) {
return true;
}
else {
return false;
}
}
?>
My problem is that when any username is put in the textbox returns "Username Available"! What did I do wrong?
You are sending an empty string as username to check thru your ajax call.
var url="username_exists.php?username=";
I would suggest you to start using jQuery to help you in handling this case.You don't need to worry about the cross browser issue and you dont need to write all these lines of code.
jQuery is a wonderful javascript library. http://www.jquery.com
Include jquery library (i will use the CDN Version) in your head section of HTML document and change your code like this.
HTML
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id=txtUserName" />
</body>
javascript
$("#txtUserName").keyUp(function(){
if($("#txtUserName").val()!="")
{
$.ajax({
url: 'username_exist.php?username'+$("#txtUserName").val(),
success: function(data) {
alert(data);
}
});
}
}

Refreshing my php page with AJAX every 5 seconds

I'm creating a link-sharing website and on my index.php page (the page I want to refresh every 5 seconds) there are posts/links that must appear automatically (AJAX refreshing) without the user to refresh by him/herself or pressing F5 the whole time.
How would this work, precisely?
You should use the setInterval javascript function to deal with this issue.
setInterval(callServer, REFRESH_PERIOD_MILLIS);
See:
some info on ajax Periodic Refresh
javascript setInterval documentation
[edit] some good refresh examples, especially without js framework (depending wether you want to use jquery, mototools, another or no framework...)
you have to user the setInterval method to call your ajax function to inject new content into your div:
<HTML>
<HEAD>
<TITLE>Hello World Page</TITLE>
<script language="JavaScript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
// Mozilla/Safari
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq.overrideMimeType) {
xmlHttpReq.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) { // IE
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!xmlHttpReq) {
alert('ERROR AJAX:( Cannot create an XMLHTTP instance');
return false;
}
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlHttpReq.onreadystatechange = function() {
callBackFunction(xmlHttpReq);
};
xmlHttpReq.send("");
}
function callBackFunction(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var responceString = http_request.responseText;
//TODO implement your function e.g.
document.getElementById("myDiv").InnerHTML+ = (responceString);
} else {
alert('ERROR: AJAX request status = ' + http_request.status);
}
}
}
setInterval("xmlhttpPost('test.php')", 5000);
</script>
</HEAD>
<BODY>
Hello World
<div id="myDiv"></div>
</BODY>
</HTML>
Is there a need to use AJAX?
Unless I'm missing something; you could use the meta refresh tag:
<meta http-equiv="refresh" content="5">
I would recommend increasing the time between refreshes as this will put a heavier load on the server and may cause to freeze, or slow down the site.
Use setInterval(myAjaxCallbackfunction,[time in ms]).
Callback uses property of js that function are first class members(can be assigned to variables), and can be passed as argument to function for later use.

How to submit a form in a page which is being accessed by AJAX?

I am trying to figure out how to submit a form in a page being accessed by AJAX?
Here are some code snippets to help demonstrate what I am trying to say.
HTML BODY - THIS IS WHAT THE USER WILL SEE:
<html>
<head>
<script language="javascript" src="linktoajaxfile.js">
</head>
<body onLoad="gotoPage(0)">
<div id="fillThis">
</div>
</body>
</html>
Ajax file:
var xmlhttp
function gotoPage(phase)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pageofstuffce.php";
url=url+"?stg="+phase;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("fillThis").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
PAGE OF DATA:
<?php
$stage = $_GET['stg'];
if($stage == 0)
{
echo '<a onClick="gotoPage(1)">click me</a>';
}
elseif($stage == 1)
{
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
}
elseif(somehow can reach here)
{
show data from form.
}
?>
How to get past the form and display the data in the same page?
I have tried submitting the form to itself (same file) and that destroyed the AJAX link, and opened the page. I have also tried just having the button move the page onto another step, but the $_POST variable is empty.
hey u can go through this link
http://www.ajaxlines.com/ajax/stuff/article/how_to_submit_a_form_with_ajax_in_jquery.php
let me know if any issues regarding this
I think there's a bug in your code. You are not setting the stage variable anywhere.
Look at:
url=url+"?stg="+phase;
Probably you'll have to change stg => stage.
Don't see any other issue with it.
Hi for displaying the result or form in the same page u can use
form method ="POST" action =
or if u want to use ajax then write one function in jquery something like this
function call() {
$.ajax({
type:'POST',
url:'path to same file name?action=submit',
// data u want to pass
data:',
success:function() {
}
});
}//function ends
and ur php code
check if $_GET['action'] is there then execute ur function
Thanks
Here are the scripts that you are looking for.
pageofstuffce.php
<?php
$stage = $_GET['stg'];
if($stage == 0)
{
echo '<a onClick="gotoPage(1)">click me</a>';
}
elseif($stage == 1)
{
echo '<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>';
}
else
{
echo 'show data from form.';
}
?>
Your HTML
<html>
<head>
<script type="text/javascript" language="javascript" src="linktoajaxfile.js"></script>
</head>
<body onload="gotoPage(0)">
<div id="fillThis">
</div>
</body>
</html>
Javascript for making Ajax Calls linktoajaxfile.js
var xmlhttp
function gotoPage(phase)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pageofstuffce.php";
url=url+"?stg="+phase;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("fillThis").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
Hope this will Help!
Thanks!
Hussain.

Categories