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?
Related
I have a HTML file and a PHP file.
The HTML file has 3 clickable div buttons. When I click each of them, they should trigger a different Javascript function that returns different AJAX response.
My problem is that no matter which button I click, the program always produces the same AJAX response from only one function.
Specifically, no matter which button I click, the program always sends out a GET request from the showAll() function. I know this because I make the PHP file print out the GET request parameter and it always says the "show" parameter equals to "all", when I want the parameter to equal to "major" or "course".
HTML
<div id="List">
<div id="entries">
</div>
<a href="" onclick="showAll()">
<div id="button_all" class="buttons">
<p> Show All</p>
</div>
</a>
<input id="major" type="text">
<a href="" onclick="filterM()">
<div class="buttons">
<p>Filter by Major</p>
</div>
</a>
<input id="course" type="text">
<a href="" onclick="filterC()">
<div class="buttons">
<p>Filter by Course</p>
</div>
</a>
</div>
<script>
function showAll(){
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var mesgs = document.getElementById("entries");
mesgs.innerHTML = xmlhttp.responseText;
document.getElementById("button_all").style.display = "none";
}
}
xmlhttp.open("GET","queryEntries.php?show=all", true);
xmlhttp.send();
}
function filterM() {
var xmlhttp;
var majorName = document.getElementById("major").value;
alert("filterM() has been clicked and majorName is " + majorName);
if(window.XMLHttprequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var mesgs = document.getElementById("entries");
mesgs.innerHTML = xmlhttp.responseText;
document.getElementById("button_all").style.display = "block";
}
}
xmlhttp.open("GET", "queryEntries.php?show=major&value=" + majorName, true);
xmlhttp.send();
}
function filterC() {
alert("filterC() had been clicked");
var xmlhttp;
var courseName = document.getElementById("course");
if(window.XMLHttprequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var mesgs = document.getElementById("entries");
mesgs.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "queryEntries.php?show=course&value=" + courseName, true);
xmlhttp.send();
document.getElementById("button_all").style.display = "block";
}
</script>
</body>
</html>
PHP
<?php
$db_server = "...";
$db_user = "...";
$db_pwd = "...";
// Create connection
$conn = mysqli_connect($db_server, $db_user, $db_pwd) or die('Connection failed! ' . mysqli_error($conn));
// Select database
mysqli_select_db($conn, "h3517511") or die("Selection failed! " . mysqli_error($conn));
// Construct SQL query
echo "The show is: " . $_GET['show'] . "<br>";
echo "The value is: " . $_GET['value'];
$query = 'SELECT * FROM attendanceList';
if ($_GET['show'] == "major") {
echo "MAJOR";
$query = 'SELECT * FROM attendanceList WHERE major = "'.$_GET['value'].'" ';
}
if ($_GET['show'] == "course") {
echo "COURSE";
$query = 'SELECT * FROM attendanceList WHERE course = '.$_GET['value'].' ';
}
// Execute SQL query
$result = mysqli_query($conn, $query) or die('Query execution failed! ' . mysqli_error($conn));
while($row = mysqli_fetch_array($result)){
print "<div id=".$row['id'].">";
print "<span>".$row['attendOrNot']."</span>";
print "<h3>".$row['studentname']." (".$row['major'].")</h3>";
print "<h5>(".$row['course'].") on ".$row['coursedate']." </h5>";
print "</div>";
}
?>
Try the following code, it's based on yours but uses only one JS function with variables, which is easy to control and debug.
This is the main code:
<div id="List">
<div id="entries"></div>
<input id="all" type="hidden" value="all">
<a onclick="submitFilters('all', 'none')">
<div id="button_all" class="buttons">
<p>Show All</p>
</div>
</a>
<input id="major" type="text">
<a onclick="submitFilters('major', 'block')">
<div class="buttons">
<p>Filter by Major</p>
</div>
</a>
<input id="course" type="text">
<a onclick="submitFilters('course', 'block')">
<div class="buttons">
<p>Filter by Course</p>
</div>
</a>
</div>
<script>
function submitFilters(name, buttonDisplay){
var xmlhttp;
var value = document.getElementById(name).value;
alert(name + " has been clicked and value is " + value);
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var mesgs = document.getElementById("entries");
mesgs.innerHTML = xmlhttp.responseText;
document.getElementById("button_all").style.display = buttonDisplay;
}
}
xmlhttp.open("GET", "queryEntries.php?show=" + name + "&value=" + value, true);
xmlhttp.send();
}
</script>
EDIT:
I cleaned the "href" attributes, which are not needed when use "onclick". If you want the classic link style, add this block to your HTML:
<style>
a {
text-decoration: underline;
cursor: pointer;
color: blue;
}
</style>
Make sure the IF statment is valid in your php code. Try it like this:
if (trim($_GET['show']) === "major")
Define xmlhttp using var keyword. the way you are defining it is making it global so it will always have the values of the first request after refreshing the page.
Solution 1:
Chang this :
xmlhttp = new XMLHttpRequest();
to this :
var xmlhttp = new XMLHttpRequest();
Solution 2:
Use different name for it in each js function like xmlhttp1, xmlhttp2 and xmlhttp3
..........................
I recommend to use both solutions together at the same time because the query word from the input field may change so in this case solution 2 alone is not enough.
I’m working at a web GUI for an audio mixer. Therefor I have lot of repetitive faders. All looking the same, just differing by ID. The ID is a three digit number. The first digit is provide by the main php page, the other are repetitive in each fader section. I’m trying to get the result back from the server and posting it into a span field. The problem is that the span id depends on the full id.
The span id should be “result111”.Not hardcoded as it is but dynamically generated by the provide id followed by the identifier 11.
GUI php
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
backEnd.php
<?php
$id = 10;
$value = 7;
$result = 6;
if ( isset($_GET['id']) )
{
$id = $_GET['id'];
}
if ( isset($_GET['v']) )
{
$value = $_GET['v'];
$result = $value;
}
echo ("$id + $result");
?>
GUI.php
<?php
$id = 1;
include 'fader.php';
?>
fader.php
<script>
var id = <?php echo "$id"; ?>;
function setName (id2){
var fullId =""+ id + id2;
return fullId;
}
function setNameReturn (id2){
var fullIdReturn =""+ id + id2;
return fullIdReturn;
}
</script>
<form oninput="transfer(auswertung.value,setName(11))">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="setNameReturn (11)">n.a.</Span>
</form>
You passing value to your function in next way
transfer(auswertung.value,setName(11))
11, while expecting 111
is this your problem?
Update:
Just to be clear, everything you generated in PHP stays in PHP, you need to geenrate JS assignment to pass value to JS. You currently have hardcoded value of 11 at your transfer function, and span result111.
This might work or it might not. It is just an attempt, because you asked me for it in the comments. Have a try and see, what happens.
GUI.php
<?php
$id = 1;
function getSpanId($addedid){
$spanid = $id + $addedid;
return $spanid;
}
?>
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
<?php
include 'fader.php';
?>
fader.php
<form oninput="transfer(auswertung.value,<?php getSpanId(11); ?>)">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="<?php getSpanId(11); ?>">n.a.</Span>
</form>
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"];
?>
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
I have 3 buttons on my page and depending on which one the user is clickingi want to run through ajax call a delete query in my database. When the user clicks on a button the javascript function seems to work but it doesn't run the query in php script.
The html page:
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<script>
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
alert(name); // check if is getting in if statement and confirm the parameter's value
var xmlhttp;
if (str.length==0)
{
document.getElementById("clearMessage").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("clearMessage").innerHTML= responseText;
}
}
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.send();
}
else
alert('pff');
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="main">
<?php if (session_is_registered("username")){ ?>
<!--Εκκαθάριση παλαιών μηνυμάτων<br />
Εκκαθάριση παλαιών συνεδρίων<br />
Εκκαθάριση push notifications<br />-->
<input type="button" value="Εκκαθάριση παλαιών μηνυμάτων" onclick="myFunction('messages')" />
<input type="button" value="Εκκαθάριση παλαιών συνεδρίων" onclick="myFunction('conferences')" />
<input type="button" value="Εκκαθάριση push notifications" onclick="myFunction('notifications')" />
<div id="clearMessage"></div>
<?php } else echo "Login first."; ?>
</div>
<div id="footer"></div>
</div>
</body>
</html>
and the php script:
<?php
if (isset($_GET["q"]))
$q=$_GET["q"];
$host = "localhost";
$database = "dbname";
$user = "dbuser";
$pass = "dbpass";
$con = mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($database,$con) or die(mysql_error());
if ($q=="messages")
$query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="conferences")
$query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="notifications") {
$query = "DELETE FROM push_friend WHERE time_sent IS NOT NULL";
}
$res = mysql_query($query,$con) or die(mysql_error());
if ($res)
echo "success";
else
echo "failed";
mysql_close($con);
?>
You have a few issues.... and this got the text from clearDatabase.php... I just had it output some generic text
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<script>
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
// Issue #1: str is not defined anywhere
var str = "sfs";
alert("name " + name); // check if is getting in if statement and confirm the parameter's value
var xmlhttp;
if (str.length==0)
{
document.getElementById("clearMessage").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)
{
// Issue #2: responseText was not defined... it needs to belong to something
document.getElementById("clearMessage").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.send();
}
else
alert('pff');
}
</script>
note: anyone who runs "clearDatabase.php?q="+name can delete whatever from your database. Also, make those changes but it still may not work if the code on "clearDatabase.php?q="+name doesn't work.
Also: it would have been a lot easier for us to troubleshoot this for you if you had provided the console errors.
How I solved this: I just copied and pasted this in a document myself and opened up the Chrome version of Firebug (control+shift+j) and there was red text to tell me str wasn't defined. So I defined it as var str="". Then I realized it was hitting if (str.length==0) so I give it a value. Then, I got a new error that the responseText wasn't defined. I googled how to use the response form a javascript ajax call (I only know jquery) and looked at the examples. I saw it needed to be from the request and added xmlhttp.responseText;. Then it worked.
Try;
xmlhttp.open("POST","clearDatabase.php?q="+name,true);
instead of;
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
first open the xmlhttp request.
try this:
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("clearMessage").innerHTML= responseText;
}
}
xmlhttp.send(null);
why dont you use jquery -> ajax() ?
And your code will look like this:
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
alert(name); // check if is getting in if statement and confirm the parameter's value
$.ajax({
type: "GET",
url: "clearDatabase.php?q="+name,true,
success: function (res){
$("#clearMessage").html(res );
}
});
}
else{
alert('pff');
}
}