I have a an ajax function that is not displaying properly on my html page. I have included a screenshot of the error here:
What is happening: The ajax function is POSTed to my PHP file where an SQL Query is ran. The stagename of the musician is searched in my database and the real name of the artist is ultimately returned from the ajax function and sent my HTML page in a div with id="#namers". When I click on an artists name, that name is stored in a variable, sent into the ajax function and sql query and the returned name value is displayed.
The Problem:
The page comes up, shows the artists name (duplicated) but then 2-3 seconds later, the element disappears entirely. In the GIF I am clicking only once and the artists name. Each click event triggers the ajax function and subsequently, an SQL query.
What I would like:
I would like the name of the artist to appear only once and I would like the name to be statically displayed on the page. I want to stop the div from disappearing. When I click on an artists name, I want the element with their real name to be displayed until another artist is clicked on. Each name only needs to be loaded to the site once per visit.
jQuery:
$(document).ready(function () {
$('#namers').hide();
$('#prf').hide();
$('.artists').click(function () {
$('.mainpage').hide();
$('#prf').show();
}); //when .artists is clicked
$('li').click(function () {
var name = $(this).text();
$('#prf').attr("class",name);
$('#pic').attr("class",name);
$('#info').attr("class",name);
$.post("ajax-name.php", {name: name}, function( html ) {
$('#namers').html(html);
}) //POST function
$('#namers').show();
}); //when 'li' clicked
}); //document.ready
PHP:
<?php
//PDO
$rname = $_POST['name'];
try {
$db = new PDO('mysql:dbname=dbname;host=myhost;charset=utf8', 'user', 'pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
$result=$stmt->fetchAll();
foreach($result[0] as $child) {
echo $child . "<br />"; }
}
catch(PDOExeception $e){echo $e->getMessage();}
?>
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<title></title>
<script src="jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="jquery.js" type="text/javascript" ></script>
</head>
<body>
<div class="header"><h1></h1></div>
<div class="mainpage">
<h1>Get Curious. Click an artists to get started. Have fun! :)</h1>
</div>
<div id="prf" class="profile">
<div id ="info" class="basicinfo">
<div id="pic" class="artistphoto">Artist photo here</div>
<div class="artistname">Name(s):<div id="namers"></div></div>
<div id="hometown" class="hometown">Hometown:</div>
</div>
</div>
<div class="leftpanel">
<ul class="artists" >
<li>Aly and Fila</li>
<li>Andrew Rayel</li>
<li>Arnej</li>
<li>Avicii</li>
<li>Basenectar</li>
<li>Borgeous</li>
<li>Bryan Kearney</li>
<li>Caked Up</li>
<li>Cash Cash</li>
<li>Coone</li>
<li>David Guetta</li>
<li>Dimitri Vegas and Like Mike</li>
<li>Diplo</li>
<li>Dirtcaps</li>
<li>DVBBS</li>
<li>DYRO</li>
<li>ETC! ETC!</li>
<li>Ferry Corsten</li>
<li>Henry Fong</li>
<li>John Digweed</li>
<li>Jordan Suckley</li>
<li>Kaskade</li>
<li>Le Castle Vania</li>
<li>Martin Garrix</li>
<li>M4sonic</li>
<li>Makj</li>
<li>Mat Zo</li>
<li>Morgan Page</li>
<li>Myon and Shane 54</li>
<li>New World Sound</li>
<li>Nicky Romero</li>
<li>Orjan Nilsen</li>
<li>Paris Blohm</li>
<li>Pete Tong</li>
<li>Richie Hawtin</li>
<li>Romeo Blanco</li>
<li>Skrillex</li>
<li>Simon Patterson</li>
<li>Steve Aoki</li>
<li>Swanky Tunes</li>
<li>Tiesto</li>
<li>TJR</li>
<li>Woflpack</li>
<li>Yves V</li>
<li>Zedd</li>
</ul>
</div>
<div class="footer">
<h1>footer</h1>
</div>
</body>
</html>
Related
I am trying to cascade update a SELECT tag using jQuery AJAX.
The criterium is passed as POST/JSON to a PHP script which, in turn, pulls the data from a MySql database using PDO. The response is then displayed using JSON.
My problem is that with 2 specific records, the response will be empty.
The form (selectBB.php):
<?php
include_once '../core/classes/bbClasses.php';
$db=new workingDB();
?>
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link href="../Core/css/css.css" rel="stylesheet" type="text/css"/>
<script src="../Core/jquery/jquery-1.11.1.js" type="text/javascript"></script>
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>-->
<title>Liste des départements</title>
</head>
<body>
<div id="wrapper">
<header>
<div id="logoZone"></div>
<nav>
<li>Clients</li>
<li>Positions</li>
<li>Clients</li>
<li>Maintenance</li>
<li>Rapports</li>
</nav>
</header>
<aside>
<ul>
<li>Reservation</li>
<li>Location</li>
<li>Renouvellement</li>
</ul>
</aside>
<div id="content">
<form method="$POST" name="frmSlctBB">
<label for="slctDPT">Departement</label>
<select id= "Dpt" name="slctDPT">
<?php
$listDPT=$db->loadDPT();
if(count($listDPT)){
foreach ($listDPT as $DPT) {
echo ("<option value=".$DPT['IDDepartment'].">".$DPT['DepartmentName']."</option>");
}
}
?>
</select>
<label for ="slctVille">Ville</label>
<select id="slctVille" name="slctVille">
</select>
<label for ="slctFormat">Format</label>
<select id="slctFormat" name="slctFormat"></select>
<label for ="slctStatut">Statut</label>
<select id="slctStatut" name="Statut"></select>
</form>
<!--Error log-->
<div class="errorlog"></div>
<!-- End of error log-->
</div> <!-- end of content-->
<footer>
<ul>
<li> <address><strong>Dauphin s.a.</strong>bldg #8, complexe Acra <br>route de Delmas,<br>Delmas, HT6120<br>Haiti</address></li>
</ul>
</footer>
</div> <!-- end of wrapper-->
<script src="../Core/js/searchCritFunctions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Dpt").change(function(){
fetchCities();
});
});
</script>
AJAX request
function fetchCities(){
// Uses Ajax to return a list of cities based on selected department
var selDpt= $("#Dpt").val();
$(".errorlog").empty();
$.ajax({
url :'listCities.php',
data:{d:selDpt},
type: 'POST',
dataType: 'JSON'
})
.done( function(result){
// Clear Select from previous entries
$('#slctVille').empty();
//load new entries
for(var i=0;i<result.length;i++){
$('#slctVille').append('<option value='+ result[i].IDCity +'>'+result[i].CityName+'</option>');
};
console.log(result);
})
.fail(function (){
$(document).ajaxError(function(jqXHR,textStatus,thrownError){
$(".errorlog").append("<h3>An error has occured</h3><p>"+textStatus+"</p>");
console.log(thrownError);
})
;
});
};
PDO Statement
<?php
require_once '../core/config/config.php';
class workingDB extends db {
public function loadDPT(){
$sql="SELECT * FROM tblDepartments ORDER BY DepartmentName";
$q = $this->conn->prepare($sql);
$q->execute();
return $row=$q -> fetchAll();
}
public function loadCities($dpt){
$sql="SELECT IDCity, IDDepartement, CityName FROM tblCities WHERE IDDepartement=".$dpt;
$q = $this->conn->prepare($sql);
$q->execute();
$row=$q -> fetchAll();
return $row;
}
}
As a tentative to debug the code, I have outputted the response to the console. If, for example, the data sent thru AJAX is "5", the html response would be :
[{"IDCity":"22","0":"22","IDDepartement":"5","1":"5","CityName":"Hinche","2":"Hinche"},{"IDCity":"23","0":"23","IDDepartement":"5","1":"5","CityName":"Mirebalais","2":"Mirebalais"}]
On the opposite, if Ajax data is "1" or "9", the response would be empty.
Thanks in advance for your help.
P.S.: I have verified the database and these specific rows aren't empty.
P.S.: #Sean, thanks for noting I had forget to add listCities.php
<?php
//Output list of cities based on departments selected
include_once '../core/classes/bbClasses.php';
$d=$_POST['d']; //array of departments selected
$base= new workingDB();
$villes=$base ->loadCities($d);
echo json_encode($villes);
$base="";
?>
I am retrieving data from mySQL using PHP and able to show it, like the Job Titles in List Items. And would like to show the Job Skills and Description in a PopUp when it is clicked. Each Job Title will have unique Skills and Description. Please, help me...
Sample Code :
<?php
//including the database connection file
include_once("includes/db.php");
// Get all the data from the table
$result = mysql_query("SELECT * FROM job_posting ORDER BY id DESC") or die(mysql_error());
echo "<ul>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array($result)) {
// Print out the contents of each row into a table
echo "<li> <a href='post_resume.php?id=".base64_encode($row['id'])."'>" . $row['title'] . "</a></li>";
}
echo "<ul>";
?>
With reference to : http://jqueryui.com/dialog/
Put a div inside your li .
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<script>
$(function() {
$( ".dialog" ).dialog({ autoOpen: false });
});
</script>
<body>
<ul>
<li>
<div class="dialog" title="SOME TEXT">
<p>
JOB SKILLS AND DESCRIPTION
</p>
</div> </li> </ul> </body>
I'm new to the whole coding thing and have been learning a lot with yer help lately so I hope it may continue with the next problem I am having!
I have a Jquery list which is rendering perfectly and what it does is display some dummy info I've inputted that comes from a local MYSQL database. What I've done so far is that when the user clicks on one of the listed links it will bring them to the next page and say "You have selected link #" and the # tag in this instance represents the dealid number of the users selected list link.
What I'm trying to find out what to do is this:
With the information I've gained from the users selection (i.e. the selected dealid number) how can I then pass this back onto the database so I can find and retrieve the particular entry with that dealid number.
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/test/json3.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"'><h1>"+dat.name+"</h1><p>"+dat.dname+"</p></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
listObject.itemID = $(this).attr('id');
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
$('#index2 [data-role="content"]').html('You have selected Link' + listObject.itemID);
// var url="http://localhost/test/json9.php";
// $.getJSON(url, function(json){
});
var listObject = {
itemID : null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<a data-role="button" href="#page1" data-icon="star" data-iconpos="left">Get Deal </a>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
The PHP/Json file that is being referenced to create the original list (Json3.php) is as follows:
<?php
$link = mysql_pconnect("localhost", "root", "") or die ("Could not Connect to DB");
mysql_select_db("findadeal") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT r.restaurantid, r.name, r.image, d.dealid, d.dname, d.restaurantid
FROM restaurant r, deal d
WHERE r.restaurantid = d.restaurantid;");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"deals":'.json_encode($arr).'}';
?>
I'm running at a loss here as I've been looking for information on this for a while and cant seem to find what I'm looking for. I appreciate anyones help, I really mean it! Thanks in advance!! :)
you can simplify your javascript like this:
$(document).on('click', '#'+dat.dealid, function(event){
listObject.itemID = $(this).attr('id');
$.mobile.changePage( "#index2", { transition: "slide"} );
event.stopPropagation();
});
If you want to load the data of your item without reloading the page then you need to do an ajax request. If you don't mind reloading the page, redirect to http://domain.com/uri/whatever?id=<the_selected_id> then in your PHP script you can get the item using the get parameter $_GET['id'] and perform a query to get the data for this id.
UPDATE
You need a PHP script to retrieve the data from the database. This script is called like this: http://www.domain.com/foo/bar/my_script.php?id=<the_id_from_the_selection>
And your script should looks like this:
<?php
// Default value to return
$data = array('error' => 'No deal found');
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// Using PDO for the database connection, it's much better and avoid SQL injection
// Make sure the PDO extension is enable in your php.ini
$pdo = new \PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');
$sql = "SELECT * FROM deal WHERE id = :id";
$statement = $pdo->prepare($sql);
$statement->execute(array('id' => $_GET['id']));
$data = $statement->fetch(\PDO:FETCH_ASSOC);
}
echo json_encode($data);
// You don't need the closing PHP tag. Actually it's easier to debug if you don't use it.
Your ajax request (called when user select something, this is javascript) should look like this:
var dealId; // the selected deal id
$.ajax({
url : 'foo/bar/my_script.php',
data: {id: dealId},
type: "GET",
async: true,
onSuccess: function(response){
console.log(response); // look into the console to check the object structure
// Display your data here using dom selector and jquery
}
});
I am a newbie on AJAX, I have a link that loads table.php. Then it writes the code to the index.php. In that code, I have another link to
show the info.php. Is it possible to do this?
<!--This is index.php-->
<div id="link">my Info</div><!--it works here-->
<div id="link">My Table</div>
<div id="table"></div>
<div id="info"></div>
<!--My javascript-->
<script type="text/javascript">
$(document).ready(function() {
$('#link a').click(function(){
var page = $(this).attr('href');
if(page =='table')
$('#table').load('table.php');
else if(page =='info')
$('#info').load('info.php');
return false;
})
});
</script>
<!--This is table.php-->
<div id="link">my Info</div><!--it doesn't works here-->
<!--This is info.php-->
<h1>My info</h1>
Your three <div> (as pointed out by #scragar) have the same id link, most probably causing the issue. Make it a class like that :
<div class="link">
And in your JS :
$('.link a')
EDIT : As noted by dbf, you must as well declare your handler with live() or on() instead of click() :
$('.link a').live('click', function(){ ... });
in order for it to be binded after table.php is loaded in the page. ( http://api.jquery.com/live/ )
i need to show a dialog box if login failed. now i'm able to show the error line inside the form, but i need to show the error message using modals.
here's my code:
$sfAuth = new SfAuthenticate();
$sfHelper = new SfHelper();
$user = $_POST['txtUsername'];
$pass = $_POST['txtPassword'];
$checkUser = $sfAuth->checkUserJobSeeker($user);
if($checkUser)
{
$login = $sfAuth->loginJobSeeker($user, $pass);
if($login)
{
echo $sfHelper->redirect('forms/jobSeeker/HomeJobSeeker.php');
}else{
echo $sfHelper->redirect('forms/jobSeeker/formLoginJobSeeker.php?err=Invalid Username or Password');
}
}else{
echo $sfHelper->redirect('forms/jobSeeker/formLoginJobSeeker.php?err=Sorry, We Cannot found your Username');
}
i want to show the dialog box after redirecting to the login form.
can anyone help me please?
Have a look at this fiddle, it should work: http://jsfiddle.net/7PwWp/5/
As to launching the modal window on user error, you can add a condition:
<?php if(isset($_GET['err']): ?>
launchWindow('#message');
<?php endif; ?>
In the message box, you can put:
<p><?php echo (isset($_GET['err'])? $_GET['err']:''; ?></p>
To show a modal dialog box you'll need javascript. Check this previous SO question: How to create popup window(modal dialog box) in HTML). I would, similarly, recommend checking out jQueryUI which is an extension of the javascript library jQuery.
In 3 steps, here's how this works:
Include jQuery and jQueryUI library scripts in the page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"/></script>
Create the markup for the modal dialog to be displayed
Doesn't need to be fancy but note the id tag as jQuery uses that to know which element to display in dialog.
<div id="dialog" title="Basic dialog">
<p>This is the message inside the modal dialog.</p>
</div>
Show the dialog using jQueryUI
<script>
$(document).ready(function() {
$( "#dialog" ).dialog();
});
</script>
See a full working example here: http://jsfiddle.net/wjp94/3/
put this code on formLoginJobSeeker.php file
<?php
if($_GET['err'] == "Sorry, We Cannot found your Username")\
{
echo '<script> alert("Sorry Wrong Username Or Password");</script>'
}
?>
If you want to show dialog then you have to use jquery dialog
Add following code to your page;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/base/jquery-ui.css" type="text/css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.min.js"/></script>
<div id="dialog" title="Basic dialog" style="display:none">
<p>
<?php if(isset($_GET['err'])) echo $_GET['err'];?>
</p>
</div>
<?php if(isset($_GET['err']){ ?>
<script type="text/javascript">
$(document).ready(function() {
$( "#dialog" ).dialog();
});
</script>
<?php } ?>
if you want to see how your modal looks like check on this link
http://codebins.com/bin/4ldqp8p
Solved?
If not, here is my solution.
Redirect to sth like that (notice #run_modal):
`forms/jobSeeker/formLoginJobSeeker.php?err=YOUR_MESSAGE#run_modal`
and JS:
function detectModalParam()
{
var hash = $(location).attr('hash');
if (hash == '#run_modal')
{
YOUT_MODAL_FUNCTION();
};
}
$(document).ready(function()
{
detectModalParam();
}