I have an autocomplete jQuery menu, that output the name of all the users I have, from a MySQL database. I'm trying to link each selection to the proper profile. For that, the URL is something like: /profile.php?id=341, 341 that stands for the ID of the user selected.
The only problem, is that when I try to put the ID of a given user, ALL the ID of ALL the user are shown in the URL... and I want only the ID of the selected user!
I have tried with PHP, but I don't know what to add to the following line to make it work.
$req = mysql_query("select id, Username, EmailAddress from ***");
Should it be something like WHERE Username='username'....? Finally, I know that I should maybe try something else, without PHP, but I just want to test it that way! Thanks!
<input type="text" name="course" id="course" />
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("/test/test2.php", {
selectFirst: false,
formatItem: function(data, i, n, value) {
//make the suggestion look nice
return "<font color='#3399CC'>" + value.split("::")[0] + "</font>";
},
formatResult: function(data,value) {
//only show the suggestions and not the URLs in the list
return value.split("::")[0];
}
}).result(function(event, data, formatted) {
//redirect to the URL in the string
var pieces = formatted.split("::");
window.location.href = '/profile.php?id='+
<?php
mysql_connect ("***", "***","***") or die (mysql_error());
mysql_select_db ("***");
$req = mysql_query("select id, Username, EmailAddress from ***");
while($dnn = mysql_fetch_array($req))
{
echo $dnn['id'];
}
?>
;
console.log(data);
console.log(formatted);
});
});
</script>
Your MySQL query is true to every user in the database, so it returns all the users. If you want to go to "foo"'s profile, you need to tell the database to fetch "foo"'s id only. A unique row that the user has maybe there email and must be their username.
I assume you have an array in javascript which contains selected users:
var users = new Array("Daniel","Amy","Sandy");
then you need to use ajax to communicate to php:
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}//This can become an external file to link
</script>
so then you can post data to php:
<script>
var returnedStr = "";
function searchuser(){ //use searchuser function on a button to call
var usersStr = users.toString(); //the string that contain the users separated by ","
var ajax = ajaxObj("POST", "thisurl.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "fail"){ //i didn't include this in php, but you can add it yourself if you can't fetch from mysql
echo "Failed";
} else {
returnedStr = ajax.responseText;// when php echos
}
}
}
ajax.send("u="+usersStr);
}
</script>
then your php will need to handle the string:
<?php
if(isset($_POST["u"])){
$returnArr = array();
$returnStr = "";
$processedArr = explode(',', $_POST['u']); //Here the posted data will turn into an array
$lengthArr = count($processedArr);
for ($i=0; $i<=$lengthArr; $i++)
{
$req = mysql_query("SELECT id FROM xxx WHERE Username='$processedArr[$i]' LIMIT 1");
while($dnn = mysql_fetch_array($req))
{
array_push($returnArr, $dnn['id']);
}
}
$returnStr = implode(",",$returnArr);
echo ($returnStr);
}
?>
Now in Javascript returnedStr will hopefully be 1,2,3 or something like that.
Please comment if this doesn't work!
Related
I have a list on my site that has a favorites button associated with each item on the list. I am using an image as the button to click. The PHP for it is:
echo "<img src=\"./images/emptystar.png\" alt=\"favorite\" class=\"favoritebutton\" billid=\"" . $count['id'] ."\" userid=\"". $_SESSION['userid'] ."\" />\n";
I have javascript/jQuery to make an onclick of that image submit an AJAX request to a PHP file.
$(document).ready(function() {
$(".favoritebutton").click(function () {
var billid = $(this).attr("billid");
var userid = $(this).attr("userid");
var ajaxrequest;
var params = "billid=" + billid + "&userid=" + userid;
ajaxrequest.open("POST","./ajaxphp/favorites.php",true);
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.setRequestHeader("Content-length", params.length);
ajaxrequest.setRequestHeader("Connection", "close");
ajaxrequest.send(params);
ajaxrequest.onreadystatechange=function()
{
if (ajaxrequest.readyState===4 && ajaxrequest.status===200)
{
if(ajaxrequest.responseText === "true")
{
if($(this).attr("src") === "./images/emptystar.png")
{
$(this).attr("src","./images/fullstar.png");
}
else
{
$(this).attr("src","./images/emptystar.png");
}
}
}
};
});
});
The php file at ./ajaxphp/favorites.php is the following:
<?php
include("./includes/dbcxnfunction.inc");
$billid = $_POST['billid'];
$userid = $_POST['userid'];
$query = "IF NOT EXISTS (SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid)
ELSE
DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid' ";
$result = mysqli_query(dbcxn('bill'),$query)
or exit("Couldn't execute query for favorites");
if($result)
{
$request = "true";
}
else
{
$request = "false";
}
echo $request;
?>
In particular I am concerned with the SQL query and the javascript because I am not certain of their correctness, but I used a validator for the javascript with JQuery and everything is valid.
When I click the image on the page, nothing happens even though I have tested both conditions for the image change. Either the javascript is written incorrectly, or there is never a response sent back from the favorites.php file.
The network tab in console.
Use JQuery's .ajax and pass the clicked element by storing it in var before you make the ajax call
$(".favoritebutton").click(function () {
//Store $(this) in var so that it can be passed inside the success function
var this$ = $(this);
var billid = this$.attr("billid");
var userid = this$.attr("userid");
$.ajax( { url : "./ajaxphp/favorites.php", type: 'post', data : { billid : billid , userid : userid },
success : function( responseText ){
if( responseText == "true"){
if( this$.attr("src") == "./images/emptystar.png"){
this$.attr("src","./images/fullstar.png");
}else{
this$.attr("src","./images/emptystar.png");
}
}
},
error : function( e ){
alert( ' Error : ' + e );
}
});
});
I have this code that GET the php file using an AJAX method. The goal is to inform the user if the movie table is empty or not. If the table is empty, it will display a confirm box that will ask if the user wants to add movies or not?
Here's my index.php file:
Movies
Here's my moviestbl.php:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
?>
<script language="JavaScript">
var option = confirm("No Movies found. Add Movies now?");
if(option ==true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
}
else{
//do nothing. return to current window.
}
</script>
<?php
}
?>
And finally, here's my AJAX file.
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
</script>
When I click the link, it is not doing or displaying anything. need help. thanks.
You will need to get the data from server using an ajax request , the response could be in JSON format.
Suggestions .
use jQuery and $.ajax - for pulling data from server
on getting the response - do the confirm and switch window
You can structure the logic to handle specific logics at client & server
PHP : logic on server could beCreate and interface for responding with JSON result for status of entries on movie table. your current query should work fine.
Javascript: Make use of the interface defined on php to to query data and make use of the 'confirm' javascript to do the switching.
Right now if you change
Movies
to
Movies
You should see it working with page reloads and redirects.
This will probably work better:
<?php
include ('../phpfunc/connect'); //includes the connection to mysql
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
if($countRows == 0){
echo "empty";
}
?>
<script>
/*connect to database then count the table, if it's zero, dispLay a confirmation box*/
var XMLHttpRequestObject = false;
if(window.XMLHttpRequest){
XMLHttpRequestObject = new XMLHttpRequest();
}
else if(window.ActiveXObject){
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTable(dataSource){
//get data from the server
//onreadystatechange = stores a function
var obj = document.getElementById("readystate");
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if(XMLHttpRequestObject.status == 200){
obj.innerHTML = XMLHttpRequestObject.responseText;
if(XMLHttpRequestObject.responseText === "empty"){
var option = confirm("No Movies found. Add Movies now?");
if(option == true){
//redirect to another page
window.location = "../addmedia.php?add=movies";
} else{
//do nothing. return to current window.
}
}
}
}
XMLHttpRequestObject.send(null);
}
</script>
I was able to make the code run now. Thanks to Firebug and coffee. The anchor tag is the problem. I don't know why, but when I used the img instead, it worked.
<img alt="movies" style="cursor:hand;cursor:pointer;" onclick="checkMovieTbl('/movies/ajaxphp/moviestbl.php')"/>
The PHP Script file:
<?php
//fetch the data from the table movies
include '../phpfunc/connect.php';
$checkMovieTable = mysql_query("SELECT * FROM movies ORDER BY title ASC") or die("Table not found");
$countRows = mysql_num_rows($checkMovieTable);
$json = json_encode($countRows);
if($json == 0){
echo $json;
}
?>
And lastly, the AJAX file.
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function checkMovieTbl(url){
//if not false
if(XMLHttpRequestObject){
XMLHttpRequestObject.open("GET", url, false); //not sync
XMLHttpRequestObject.onreadystatechange = function(){
if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
var response = XMLHttpRequestObject.responseText;
//alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
if(response==0){
//execute something here
}
}
else{
alert(XMLHttpRequestObject.responseText + "readyState:" + XMLHttpRequestObject.readyState + "\nStatus:" +XMLHttpRequestObject.status);
}
}
XMLHttpRequestObject.send();
}
}
Thanks to everyone who answered my questions and helped me. Chiao!
Hi I am creating a wordpress plugin and i am a little bit stack here. there's text box number 1 which is the order number and number 2 which is the order name. This is what i want. If the customer enters a number in textbox number 1 which is order number, the value he or she entered will check into the database and get the corresponding order name of that order number. Its realtime. No need to submit before it appears. Everytime they input something it will immediate check to the database and display it in text box number 2(order name). I research this and try using ajax in wordpress but i dont know how to use. Thanks.
Here's some boilerplate code to get you started....
<script type="text/javascript" charset="utf-8">
var req;
function handler_orderNumberField_onchange(fld) {
var text = fld.value;
if (text.length == 8) {
queryForOrderName(text);
}
}
function queryForOrderName(orderNumber) {
document.getElementById('orderNameField').value = "Please wait..."
req = new XMLHttpRequest();
var url = "http://www.mydomain.com/getordername.php?ordernumber=" + orderNumber;
req.onreadystatechange = function() {
var field = document.getElementById('orderNameField');
var rs = this.readyState;
var status = this.status;
if (rs == 4 && status == 200) {
field.value = req.responseText;
}
};
req.ontimeout = function() {
document.getElementById('orderNameField').value = 'Timeout.';
}
req.timeout = 10000;
req.open("GET", url, true);
req.send();
}
</script>
<p>Order Number: <input type="text" name="orderNumber" value="" id="orderNumberField" onchange="handler_orderNumberField_onchange(this)"></p>
<p>Order Name: <input type="text" name="orderName" value="" id="orderNameField"></p>
Note that you need to implement a getordername.php script yourself; example:
<?php
$ordernr = (int) $_GET["ordernumber"];
$result = sprintf("Testorder - Order Number %d", $ordernr);
header("Content-type: text/plain; charset=UTF-8");
echo $result;
exit;
?>
Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)
I have the following ajax.js, which I must use:
var xmlRequest = null;
function ajax(url, parametersArray, callbackFunction, fcnVars) {
if (xmlRequest != null) {
if (xmlRequest.readyState == 2 || xmlRequest.readyState == 3) {
xmlRequest.abort();
xmlRequest = null;
}
}
if (parametersArray == null)
parameters = "";
else
parameters = formatParameters(parametersArray);
if (window.XMLHttpRequest)
xmlRequest = new XMLHttpRequest();
else
xmlRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
xmlRequest.open("POST", url, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
if (xmlRequest.responseText) {
callbackFunction(xmlRequest.responseText, fcnVars);
}
}
}
xmlRequest.setRequestHeader("Content-length", parameters.length);
xmlRequest.setRequestHeader("Connection", "close");
xmlRequest.send(parameters);
}
function formatParameters(parameters) {
var i = 0;
var param = "";
for (index in parameters) {
if (i==0) {
param += index+"="+urlencode(parameters[index]);
} else {
param += "&"+index+"="+urlencode(parameters[index]);
}
i++;
}
return param;
}
function urlencode(clearString) {
clearString = encodeURI(clearString);
clearString = clearString.replace('&', '%26');
return clearString;
}
and I have the following mysql table:
CREATE TABLE `dictionary` (
`word` varchar(64) NOT NULL,
PRIMARY KEY (`word`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
on the end, here is my search page:
<div id = "search">
<form id="searchform" method="post">
Search for Word:
</select>
<input type="text" id="search_term" name="search_term" />
<input type="submit" id="cmdSearch" value="Search" />
</form>
<div id="search_results"></div>
</div>
Now, I have to create a php function which will return an array with the words found in the table, using the above ajax.js
Results should be shown within the search_results div using ajax.
Of course, I will need a javascript code as well.
Anyone can help me to start to build this? I have done similar things with jquery,but now I must use this script, and I have no other way to do it.
Goal is to display the results in the php page without refresh.
Any help will be deeply appreciated
Update:
Here is my php code:
<?php
// add encoding here
header("Content-Type: text/html; charset=iso-8859-7");
// include the database connection here
include 'config.php';
include 'openDb.php';
function findWords(){
// sanitaze the user input
$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysql_escape_string($term);
// query the database. one fileld only, so nothing to optimize here
$sql = "SELECT word FROM dictionary WHERE word like '%$term%'";
$result = mysql_query($sql);
// set the string variable
$string = '';
// if resulta are found then populate the string variable
if (mysql_num_rows($result) > 0){
while($row = mysql_fetch_object($result)){
// display the results here in bold and add a new line or break after each result
$string[] = "<b>".$row->user_name."</b><br/>\n";
}
} else {
// if no results are found, inform the visitors...
$string[] = "No matches!";
}
// output the string
return $string[];
Here is the javascript:
<script type='text/javascript'>
ajax("findWord.php", {id:search_term}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:search_term});
</script>
You will have to rely on the ajax function which lets you access whatever it loaded in the callback function:
callbackFunction(xmlRequest.responseText, fcnVars);
And ajax explains how it should be called itself:
ajax(url, parametersArray, callbackFunction, fcnVars)
Even though parametersArray should actually be an object ({index:value, i1:v2,...}) rather than an array ([val1, val2,...]). fcnVars can be an object containing anything that you want passed on to the callback function.
This should work:
ajax("add_page.php", {id:535}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:535});