JavaScript do not run in php output ajax - javascript

this is my index.php (submit a form by ajax and retrun an alert)
<form>
<input id="email" type="text">
<input id="cellphone" type="text">
<input type="button" value="submit" onclick='runajax()'/>
</form>
<div id="display">
this is js code:
<script type="text/javascript">
function runajax() {
var xmlhttp;
var val1=document.getElementById('email').value;
var val2=document.getElementById('cellphone').value;
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("display").innerHTML = xmlhttp.responseText;
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "doForm.php?email="+val1+"&cellphone="+val2, true);
xmlhttp.send(null);
}
</script>
and this is "doForm.php"
<?php
echo "your email is".$_GET['email'];
echo "<script>alert(your email is".$_GET['email'].")</script>";
?>
the problem is this
first echo in doform.php print currectly
but second echo (include an alert javascript code) do not run!
how can I run javascript alert in php output?

try changing this line:
echo "<script>alert(your email is".$_GET['email'].")</script>";
to:
echo "<script>alert('your email is".$_GET['email']."')</script>";

Related

submit without page redirect

I want without page redirect when user click submit button.
Here I was posting only userid. I want to post password too.
This is my HTML text area and button:
<input type="text" name="user" id="user" value="" placeholder="Mail-Id"><br>
<input type="text" name="userp" id="userp" value="" placeholder="Password"><br>
<input type="button" name="checkuser" id="checkuser" value="Validated" onclick="test();">
<script>
function test()
{
var username = document.getElementById('user').value;
var url = "login.php?user="+username;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
if(xmlhttp.responseText!='')
{
document.getElementById('use`enter code here`r_status').innerHTML =result ;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
<?php
include_once('B810.php');
$Email = $_REQUEST['user'];
//$password = $_REQUEST['userp'];
$Q810_1 = "SELECT SIGNUP.EMAIL,SIGNUP.PWD FROM SIGNUP WHERE SIGNUP.EMAIL='".$Email."'";
// AND SIGNUP.PWD='".$password."' ";
$R810_1 = mysql_query($Q810_1);
$O810 = mysql_fetch_assoc($R810_1);
if (($O810)) {
echo 'success';
// header("Attendance.html");
// exit();
} else
echo 'failure';
}
//mysqli_close($con);
?>
Change this code
var username = document.getElementById('user').value;
var url = "login.php?user="+username;
To
var username = document.getElementById('user').value;
var password = document.getElementById('userp').value;
var url = "login.php?user="+username+'&password='+password;

ajax, php and mysql connection issues

Am fetching data from database using ajax but it is failing. The data should be displayed at the div I have declared in the main page called 'display'. The query runs but nothing is printed on the div. Here are my codes:
//ajax:
<script>
function Jobs(str) {
if (str == "") {
document.getElementById("display").innerHTML = "";
return;
} else {
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("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","search.php?q="+str);
xmlhttp.send();
}
}
</script>
//php
?php $q = intval($_GET['q']);?>
<?php
include('includes/conn.php');
$row="SELECT DISTINCT title,id FROM jobs WHERE dept='$q' AND state=0 ORDER BY id";
$query=mysqli_query($conn,$row) or die(mysqli_error($conn));
while($row=mysqli_fetch_array($query))
{
echo $row['title'];
}
mysqli_close($conn);
?>
Sample ajax example codes
addfield.php file:
<html>
<head>
<script>
function Jobs(str) {
if (str == "") {
document.getElementById("display").innerHTML = "";
return;
} else {
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("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","search.php?q="+str);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="Jobs(this.value)">
</form>
<p>Suggestions: <span id="display"></span></p>
</body>
</html>
search.php code:
<?php
echo $q = $_REQUEST["q"];
?>

How to use the response PHP variables in a XHR call?

I have two pages say, page1.php and page2.php. In page1.php I have a button, when clicked it makes XHR call to page2.php and shows the response in a defined divison i.e. "print" in page1.
Code for page1.php
<html>
<button type="button" onclick="randomFunction()">Request data</button>
<div id="print"></div>
<script type="text/javascript">
function randomFunction()
{
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("print").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","page2.php",true);
xmlhttp.send();
}
</script>
</html>
Code for page2.php
<?php
$a = "apple";
$b = "banana";
echo $a;
echo $b;
?>
Output I am getting now, http://imgur.com/tyqEOgW
I want to manipulate with the response I'm getting from page2. As in I want to show "apple" in red and "banana" in blue on page1.php
How do I do that?
Send back JSON from page2.php and then add your custom HTML with that data to page1.php.
page1.php
<html>
<button type="button" onclick="randomFunction()">Request data</button>
<div id="print"></div>
<script type="text/javascript">
function randomFunction()
{
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 data = JSON.parse(xmlhttp.responseText);
var html = '<span class="apple">'+data.a+'</span><span class="banana">'+data.b+'</span>';
document.getElementById("print").innerHTML = html;
}
}
xmlhttp.open("POST","page2.php",true);
xmlhttp.send();
}
</script>
</html>
page2.php
<?php
$a = "apple";
$b = "banana";
echo json_encode( array( 'a' => $a, 'b' => $b ) );
?>
Now you could style these spans like you want. Of course you can edit the HTML structure to your desire.
Only PHP
page1.php
<html>
Request data
<div id="print">
<?php
// Show data only, if our link was clicked
if( $_GET['showData'] == 1 ){
// Get page2.php
require_once('page2.php');
echo '<span class="apple">'.$a.'</span><span class="banana">'.$b.'</span>';
}
?>
</div>
</html>
page2.php
<?php
$a = "apple";
$b = "banana";
?>

How to display ajax in html

Following the example from http://www.w3schools.com/ajax/ajax_aspphp.asp and am using a php file to send back suggestion related to words within the array. I want to display them in html but when I put the paragraph tag round the php file the whole array is printed to screen not the selected words, please help my code for javascript and the form are below
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
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","gethint.php",true);
xmlhttp.send();
}
</script>
My PHP file is then
<?PHP
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
// get the q parameter from URL
$q=$_REQUEST["q"];
$hint="";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{ $q=strtolower($q); $len=strlen($q);
foreach($a as $name)
{ if (stristr($q, substr($name,0,$len)))
{ if ($hint==="")
{ $hint=$name; }
else
{ $hint .= ", $name"; }
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>
It seems that your are not passing your q get param to the php script via ajax at all
xmlhttp.open("GET","gethint.php",true);
should be
xmlhttp.open("GET","gethint.php?q="+str,true);
Check if your copy is IDENTICALL with mine. Working copy:
http://pastebin.com/zWDtqvka
This one works for me with no problems, i tested the php and html in isolation and running both.
===============================
HTML FILE
===============================
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length == 0)
{
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", "hints.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
=================================================================================================================
PHP hints.php
=================================================================================================================
<?php
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
$q = isset($_REQUEST['q']) ? $_REQUEST['q'] : '';
$hint = '';
if ($q !== '') {
$q = strtolower($q);
$len = strlen($q);
foreach ($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === '') {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
echo ($hint === "") ? "no suggestion" : $hint;
?>
Also, if you are running it in netbeans make sure, you installed php, and check this config after clicking your project name by right mouse button in projects view

AJAX Response Text Empty

I'm creating a system that interacts with Minecraft server using AJAX. My JavaScript code is as follows:
function doMessage(name, message)
{
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.open("GET","http://duncan.usr.sh/omnicraft/api/broadcast-msg.php?message=" + message + "&user=" + name,false);
xmlhttp.send();
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
My PHP code is as follows:
<?php
header('content-type: text/plain');
echo "OmniCraft/Api/RequestHTTP";
if($_GET['message'] == "" or ctype_space($_GET['message']) or $_GET['user'] == "" or ctype_space($_GET['user']))
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nRequest invalid: No message specified";
exit;
}
include_once '../MinecraftQuery.class.php';
$Query = new MinecraftQuery( );
try
{
$Query->Connect( 'localhost', 25565 );
$info = $Query->GetInfo( );
}
catch( MinecraftQueryException $e )
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nServer not online";
exit;
}
include_once("rcon.class.php"); //Include this file
$r = new rcon("127.0.0.1",25575,"notRealPasswordHere"); //create rcon object for server on the rcon port with a specific password
if($r->Auth()) //Connect and attempt to authenticate
{
$message = $_GET['message'];
$user = $_GET['user'];
$r->rconCommand("/tellraw #a {'text':'<$user using OmniMessage> $message','color':'white'}"); //send a command
echo "\nOmniCraft/Api/Request/Success";
echo "\nMessage sent successfully!";
}
else
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nUnable to authenticate to RCON";
exit;
}
?>
My form is as follows:
<form >
<div class="input">
<input type="text" placeholder="Message" style="padding: 20px 28px;font-size: 25px;" required="true" name="message">
</div>
<div class="input">
<input type="text" placeholder="Name" style="padding: 20px 28px;font-size: 25px;" required="true" name="name">
</div>
<button class="btn btn-large btn-success" type="button" onclick="doMessage(this.form.name.value, this.form.message.value)">Send</button>
<div>
<p class="lead" id="preview">< using OmniMessage></p>
<div>
<div id="response">
</div>
The AJAX query executes well, except for the fact that the responseText variable seems to not contain the response text (i.e. the DIV with the id 'response' remains empty after the query is complete).
The correct contents of the response DIV should be:
OmniCraft/Api/RequestHTTP
OmniCraft/Api/Request/Success
Message sent successfully!
However, this is not the case. What am I doing wrong?
EDIT: More Info:
I get the following error:
[20:14:21.855] NS_ERROR_FAILURE: Failure # http://omnicraft.duncan.usr.sh/omnimessage/:154
Line 154 is: xmlhttp.send();
(or maybe document.getElementById("response").innerHTML=xmlhttp.responseText;
Try this
You haven't handled onreadystatechange
function doMessage(name, message) {
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.open("GET","http://duncan.usr.sh/omnicraft/api/broadcast-msg.php?message=" + message + "&user=" + name,false);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
}
}
Try removing the header call in your PHP code. I’m having a very similar issue that only goes away when I no longer issue a Content-Type header through PHP.

Categories