ajax, php and mysql connection issues - javascript

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"];
?>

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;

Populating liquid carousel

I know there are similar questions but I can't find answer for my problem. I am populating slider with data from database, but AJAX only puts first value in slider.
Here is my AJAX code:
$(document).ready(function() {
$('#myNavbar > ul > li ').click(function(){
var data=$(this).text();
add(data);
});
function add(data) {
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("slider").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/add.php?data="+data,true);
xmlhttp.send();
}
});
Here is my code for the slider in my HTML page:
<div class="w3-third">
<div id="liquid1" class="liquid">
<span class="previous"></span>
<div class="wrapper">
<ul id="slider">
</ul>
</div>
<span class="next"></span>
</div>
</div>
And here is my PHP code:
<?php
$conn=mysqli_connect("localhost","root","","iptv");
if (mysqli_errno($conn)) {
die("Neuspjela konekcija: " . mysqli_connect_error());
}
else{
$cat=$_GET['data'];
$query='SELECT * FROM stream WHERE Kategorija="'.$cat.'"';
$all=mysqli_query($conn,$query);
if(!$all)echo'greska je "'.mysqli_error($conn).'"';
$contentPC = "";
while(($row = mysqli_fetch_assoc($all)) != NULL) {
$contentPC .= "<li><div class=/"tv/"><a href='javascript:changeVideoJW(\"".addcslashes($row['Link'],'"')."\");'>".addcslashes($row['Naziv'],'"')."</a></div></li>";
}
mysqli_close($conn);
echo $contentPC;
}
?>
Ajax puts only first value from query in slider. The slider I'm using is the jQuery Liquid Carousel plugin. How do I make this work properly?

passing variables through parameters AJAX PHP JAVASCRIPT

I'm trying to write a simple AJAX code to get it to search through a simple array, and output the results to the screen, and it works before I tried to pass the variables through the parameter, but now it isn't passing the variables through the parameters for some reason. Please take a look:
functions.js:
var xmlHttp = createXmlHttpRequestObject();
//****************************************************************AJAX
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Not xmlHttp!")else
return xmlHttp;
}
//****************************************************************AJAX
function process(IDName, passTo, output) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
get = encodeURIComponent(document.getElementById(IDName).value);
xmlHttp.open("GET", passTo + get, true);
xmlHttp.onreadystatechange = handleServerResponse(output);
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
//****************************************************************AJAX
function handleServerResponse(output) {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById(output).innerHTML = message;
setTimeout('process()', 1000);
} else {
alert('xmlHttp.status does not equal 200!');
}
}
}
foodstore.php:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food.'!';
elseif ($food=='')
echo 'Enter a food';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
test5.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body onload="process('userInput','foodstore.php?food=','underInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
Try adding console.log(variable) on different stages to check the current state of variables, probably you are having problems with the get variable with the encodeURIComponent or maybe it isn't entering to that if on process function.

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

JavaScript do not run in php output ajax

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

Categories