displaying records in search results with ajax - php

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});

Related

How to store ajax value in php variable?

I want to store ajax value 'when selected' stored in php variable.
<select name="client_name" onchange="ajaxReq('product_name', this.value);">
<option>- - -</option>
<option value="SANY">SANY</option>
<option value="MBFC">MBFC</option>
</select>
<span id="slo_product_name"> </span>
<span id="slo_release_no"> </span>
<script type="text/javascript">
var ar_cols = ["client_name","product_name","release_no",null]; var preid = "slo_";
</script>
I've tried this, but didn't succeeded.
$releasenu=$_POST['release_no'];
How should i store the ajax value of release_no in php variable? Is there any other way?
function ajaxReq(col, wval) {
removeLists(col);
if(wval!='- - -' && wval!='') {
var request = get_XmlHttp();
var php_file = 'select_list.php';
var data_send = 'col='+col+'&wval='+wval;
request.open("POST", php_file, true);
document.getElementById(preid+col).innerHTML = 'Loadding...';
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);
request.onreadystatechange = function() {
if (request.readyState==4) {
document.getElementById(preid+col).innerHTML = request.responseText; }
} } }
According to your code, you should use this in your select_list.php script:
$col = $_POST['col'];
$wval = $_POST['wval'];
// now you can use those variables to save to DB, or get some data out of DB
I assume you want to have cascade <select> elements, you should change your ajaxReq() function:
function ajaxReq(col, wval) {
// first remove all selects that are after this one
var remove = false;
var next = null; // we also need to trap next select so we can fill it
for (i in ar_cols) {
if (ar_cols[i] == col) {
remove = true; // from now on, remove lists
} else if (remove) { // if ok to remove
if (!next) {
next = ar_cols[i]; // now we found next column to fill
}
if (ar_cols[i]) { // remove only non null
removeLists(ar_cols[i]);
}
}
}
if(wval!='- - -' && wval!='' && next) { // also if there is column after to fill
var request = get_XmlHttp();
var php_file = 'select_list.php';
var data_send = 'col='+col+'&wval='+wval+'&next='+next; // also add next param
request.open("POST", php_file, true);
document.getElementById(preid+col).innerHTML = 'Loadding...';
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);
request.onreadystatechange = function() {
if (request.readyState==4) {
// we fill next select
document.getElementById(preid+next).innerHTML = request.responseText;
}
}
}
}
Your select_list.php should look something like this:
$col = $_POST['col']; // this is just a filter for values in next <select>
$wval = $_POST['wval'];
$next = $_POST['next']; // we need to get this param or we cannot setup next <select>
// using $col and $wval variables get values from DB
echo '<select name="' . $next . '" onchange="ajaxReq(\'' . $next . '\', this.value);">';
foreach ($data as $row) {
echo '<option ...>...</option>'; // fix this to work for you
}
echo '</select>';
// Code changed due to bug found
The ajax request should contain one more parameter (next column) since the returned <select> should have name and onchange event prepared for next, not the currently changed.
Check the code above again.

Separate url in autocomplete menu

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!

How to pass javascript variable to php in html? (wikipedia parsing)

Hi I'm trying to pass a javascript variable called $url to a function in php all located in the same html file. The logic here is that there is a text box and the user inputs a species and we call the wikipedia api to check if the input has a wikipedia page if it does I parse the page and bring the species info up, everything works independently 100% but I cant seem to connect them. However I cant get javascript to pass the url to the php function below. and innerHTML the php function with the url which is suppose to render the parsed species info. The error I get is that from the get go I just get the php function spit out with nothing.
Enter a species here : [text box here]
find('table.infobox'); foreach($html->find('img') as $element) { $image[]= $element; } Print $image[1]; $data = array(); foreach($table[0]->find('tr') as $row) { $td = $row->find('> td'); if (count($td) == 2) { $name = $td[0]->innertext; $td = $td[1]->find('a'); $text = $td[0]->innertext; $data[$name] = $text; } } print ""; foreach($data as $value => $before ) { print ""; } print "
$value $before
"; } ?>
Here is my attempt so far, I call the javascript and check if a link is found and call the parse function to innerthml out in the result div
<?php
//call the javascript
//if link found
//send ajax url variable to php function
//ajax call the function innerhtml in the result div
//We check if we have the param within the page call
$theDeletenode = false;
if(isset($_POST['deletenode']))
$theDeletenode = $_POST['deletenode'];
if($theDeletenode)
{
//The param 'deletenode' is given, so we juste have to call the php function "parse", to return the value
parse($theDeletenode);
}else
{
// No parametre, so we echo the javascript, and the form (without the quote and \n, it's much better)
?>
Here is the start of my html, the text box is connected to javascript which called the wikipedia api to check if the input has a wikipedia page.
<html><head>
<script type="text/javascript">
// create and return an XMLHttpRequest object
function createRequest() {
var ajaxRequest; // the xmlrequest object
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
return ajaxRequest;
}; // end of createRequest
var spellcheck = function(data){
var found=false;var url='';
var text=data[0];
if(text!=document.getElementById('spellcheckinput').value) return;
for(i=0;i<data[1].length;i++)
{
if(text.toLowerCase()==data[1][i].toLowerCase())
{found=true;
url='http://en.wikipedia.org/wiki/'+text;
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:green\">Correct</b> - <a target=\"_top\" href=\"'+url+'\">link</a>';
}
}
if(!found)
document.getElementById('spellcheckresult').innerHTML='<b style=\"color:red\">Incorrect</b>';
};
var requestone = createRequest();
var getjs= function(value)
{
if(!value) return;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&search='+value+'&format=json&callback=spellcheck'; // this is the variable I want to pass
document.getElementById('spellcheckresult').innerHTML='Checking ...';
var elem=document.createElement('script');
elem.setAttribute('src',url);
elem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(elem);
// Ajax call to this page, this time with the 'deletenode' parameter
var vars = "url=" + encodeURIComponent(url);
requestone.open("POST", "parser.php", true); // parser.php : the name of this current page
requestone.onreadystatechange = handleRequest; // function to handle the response
requestone.send(vars);
};
function handleRequest()
{
//here we handle the php page response by echoing de result of the php page (normally the result of the parse function)
try{
if(requestone.readyState == 4 && requestone.status == 200)
document.getElementById('resultdiv').innerHTML= requestone.responseText;
} catch (e) {
//Wrong server answer...
}
};
</script>
</head>
<body>
<form action="#" method="get" onsubmit="return false">
<p>Enter a species here : <input id="spellcheckinput" onkeyup="getjs (this.value);" type="text">
<span id="spellcheckresult"></span></p>
</form>
<div id=resultdiv></div>
</body>
</html>
Here is my parse function which recieves a variable called url which is the validated wikipedia page and then it parses it for species info, this tested and it works but I cant get it to innerhtml this function along with the validated wikipedia url.
<?php
}
function parse($url){
print $url;
$html = file_get_html('http://en.wikipedia.org/wiki/Beaver');
$table = $html->find('table.infobox');
foreach($html->find('img') as $element)
{
$image[]= $element;
}
Print $image[1];
$data = array();
foreach($table[0]->find('tr') as $row)
{
$td = $row->find('> td');
if (count($td) == 2)
{
$name = $td[0]->innertext;
$td = $td[1]->find('a');
$text = $td[0]->innertext;
$data[$name] = $text;
}
}
print "<table class='infobox' style='text-align: left; width: 200px; font-size: 100%'>";
foreach($data as $value => $before )
{
print "<tr><td>$value</td><td>$before</td></tr>";
}
print "</table>";
}
?>
This question has many related answers 1234
If it helps, here is some JavaScript:
var form = document.createElement("form");
var input = document.createElement("input");
form.method="{post/get}";
form.action="{page}";
input.name="{name}";
input.value="{value}";
form.appendChild(input);
form.submit();

Passing js variables to php using jquery

I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);

sending php array to javascript function onclick

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); ?>)

Categories