Currently users can search a database using php and ajax with the results shown without a page refresh.
This requires uses to enter a search criteria - is it possible to create a direct link to the search results by including the criteria in the url?
For example:
search.php?keywords=iphone
would bring back any results for iphone without the user needing to enter a search criteria.
My ajax code is below:
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var kw = document.getElementById('kw').value;
var division = document.getElementById('division').value;
var queryString = "?kw=" + kw + "&division=" + division;
ajaxRequest.open("GET", "search/jsearch.php" + queryString, true);
ajaxRequest.send(null);
}
You basically check if the url contains the keywords query string variable and if so, you call your ajax function, try this:
window.onload = function(){
if (getQueryVariable('keywords'))
{
var kw = getQueryVariable('keywords');
ajaxFunction(kw);
}
};
You need to modify your ajaxFunction to accept an argument from url. Here is a function to get query string variable using javascript:
getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
}
Related
I am working in a chat system that relies on a mysql database.
At the beginning of the first loading of the page sending the following query:
SELECT * FROM `Shoutbox` ORDER BY `Shoutbox`.`ID` ASC LIMIT 0 , 30
and then using a while loop mold all messages (with user names and date) in a div.
while($array=mysql_fetch_array($dati)) {
echo "<div class='tag_li $array[ID]'><span class='when'>$array[DateTime]</span><span class='linea mess'><span id='author'><a onclick='ajaxLoadContent(this)' link='profile.php?name=$array[User]'>$array[User]</a></span>: $array[Message]</span></div>";
}
Now I would like to be sent every second query, and then updates the contents of the div with new messages if any.
How can I send a SQL query in a range?
I will assume you are using javascript and want to make an ajax call.
Start with the timer on the client side
window.setInterval("ajaxFunction()",milliseconds);
And the ajax function
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxDisplay.innerHTML + ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "ajax-example.php" , true);
ajaxRequest.send(null);
}
the php part
while($array=mysql_fetch_array($dati)) {
echo "<div class='tag_li $array[ID]'><span class='when'>$array[DateTime]</span><span class='linea mess'><span id='author'><a onclick='ajaxLoadContent(this)' link='profile.php?name=$array[User]'>$array[User]</a></span>: $array[Message]</span></div>";
}
And the html part
<div id="ajaxDiv"></div>
That should give you an idea how it is done.
I am using AJAX function. I am passing 3 variables to the next page using AJAX. When I add the 4th variable the function doesn't get called.
Code:
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var count = document.getElementById('count').value;
var type = document.getElementById('type').value;
var sem = document.getElementById('sem').value;
var rid = document.getElementById('room').value;
ajaxRequest.open("GET", "add_requi_ajax.php?count=" + count+"&type="+ type+"&sem="+sem+"&rid="+rid, true);
ajaxRequest.send(null);
};
</script>
Your code is syntactically and logically correct, which means that the problem is likely one of your input IDs is wrong (typo? Should room be rid?), or you call the function before the inputs are rendered on the page (use window.onload).
Verify each of your input IDs. If they all look correct, then comment them out and hard code the values to rule out your inputs as a problem. Watch the error console for any error messages. If an uncaught error is encountered, it can appear that the function isn't being called.
You probably need to urlencode your values.
I'm using the following to update a DIV called 'output'. This works fine with one exception, I would like echo entries to update the parent page.
<script type="text/javascript">
<!--
var divid = 'output';
var loadingmessage = '<img src="working.gif">';
function AJAX(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
return xmlHttp;
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
}
catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
function formget(f, url) {
var poststr = getFormValues(f);
postData(url, poststr);
}
function postData(url, parameters){
var xmlHttp = AJAX();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState > 0 && xmlHttp.readyState < 4){
document.getElementById(divid).innerHTML=loadingmessage;
}
if (xmlHttp.readyState == 4) {
document.getElementById(divid).innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(parameters);
}
function getFormValues(fobj)
{
var str = "";
var valueArr = null;
var val = "";
var cmd = "";
for(var i = 0;i < fobj.elements.length;i++)
{
switch(fobj.elements[i].type)
{
case "select-one":
str += fobj.elements[i].name +
"=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
break;
}
}
str = str.substr(0,(str.length - 1));
return str;
}
//--></script>
This is called using :
<input type='button' name='Send' value='submit' onclick="javascript: formget(this.form, 'foo.php');">
The issue I have is foo.php runs a series of exec() commands, between each command is an echo statement that I would like to be displayed in the output div.
So it will do something like:
echo "archive files";
exec ("tar -cvf bar.tar bar.txt foo.txt");
echo "backing up /user";
exec ("tar -cvf /user.tar /user/*");
I would like the user to see the working.gif, but under it each echo statement from foo.php
Can that be done and how ?
Thanks
I can't say I've ever tried sending back chunks of data at separate times with a single AJAX request, so I'm not sure it's possible. What happens currently? Do you only get first echoed message, or do only get the entire response at the end?
Two things that I know will work:
Break your PHP script into multiple scripts and execute them in order with separate AJAX requests. This will only work if the separated scripts don't depend on each other or you find some other way to persist the state across the separated scripts.
Create an iframe and load the PHP script into it instead of using an AJAX request. Flushing the output of the PHP script should then work. (If you have ever used Wordpress, I believe they use this technique to show the progress of plugin updates.)
I also want a listbox with multiple selection to use along with the above code, but its not working
$cnty is the variable (listbox - multiselection).
Below is my complete ajax function used .
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//document.myForm.time.value = ajaxRequest.responseText;
document.getElementById("result").innerHTML=ajaxRequest.responseText
}
}
var dav = document.getElementById('dav').value;
var pathogen = document.getElementById('pathogen').value;
var topic1 = document.getElementById('topic1').value;
var ind1 = document.getElementById('ind1').value;
var subindg1 = document.getElementById('subindg1').value;
var cnty = document.getElementById('countryRF').value;
var queryString = "?dav=" + dav + "&pathogen=" + pathogen + "&topic1=" + topic1 + "&ind1=" + encodeURIComponent(ind1) + "&subindg1=" + encodeURIComponent(subindg1) + "&cnty=" + encodeURIComponent(cnty);
ajaxRequest.open("GET", "sortby.php" + queryString, true);
ajaxRequest.send(null);
}
</script>
sortby.php page
<?php
$con = mysql_connect("localhost","root","adminpp");
mysql_select_db("pdata", $con);
$datav=$_GET["dav"];
$pathogen=$_GET["pathogen"];
$topic1=$_GET["topic1"];
$ind1=$_GET['ind1'];
$subindg1=$_GET["subindg1"];
$cnty=$_GET['cnty'];
echo $subindg1;
echo $cnty;
?>
There's a variety of ways to pass a multiselect list to the server through Ajax. This is just one of many... and probably not even the best. :)
I'm going to use the variable name multisel throughout so you can find it easily and see how to use it.
Add this function to your javascript
function loopSelected(selObj)
{
var selectedArray = new Array();
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
return selectedArray;
}
Now, add the following lines to ajaxFunction just after your variables.
var selObj = document.getElementById('multistore');
var multisel = loopSelected(selObj).join('~'); // join array into a string
Finally, in PHP, add these lines
$multisel = $_GET['multisel'];
$multisel_array = explode('~',$multisel); // split the items into an array
var_dump($multisel_array);
At this point all of the selected items are in $multisel_array.
function ajaxFunction(phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.subCat').html(ajaxRequest.responseText);
$('.subCat').ready(function(){
$('.subCat').fadeIn();
});
}
}
var url = "products.php?func=" + phpFunction;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
This function works great, and has no problems. But if I add:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
});
}
}
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
When I try to execute ajaxFunction('returnAllProducts') I get:
syntax error
});\n
from
$('.' + idNum).html(ajaxRequest.responseText);
}); <<<----
and
ajaxFunction is not defined
javascript:ajaxFunction('returnAllProducts')()
So my questions are:
a) how do I convert this over to jquery? I've read over some jquery ajax tutorials, but I wasn't able to make the connection how to do what I am doing here.
b) How do I get both functions to work? I know the PHP behind them works fine, but I can't even test if refreshProduct() works properly right now.
You seem to be missing a }
this is your code, properly indented...
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
});
When it should be
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.'idNum).empty();
$('.'idNum).html(ajaxRequest.responseText);
}
});
Also, the two } after this should be deleted, rendering your code like this:
function refreshProduct(idNum, phpFunction){
var ajaxRequest; // The variable that makes Ajax possible!
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;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('.' + idNum).empty();
$('.' + idNum).html(ajaxRequest.responseText);
}
});
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
As for rewriting this using jQuery, it's really easy:
function ajaxFunction(phpFunction){
var url = "products.php?func=" + phpFunction;
$.get(url, function(data) {
$('.subCat').html(data).ready(function(){
$('.subCat').fadeIn();
});
});
}
function refreshProduct(idNum, phpFunction){
var url = "products.php?func=" + phpFunction + "&idNum=" + idNum;
$.get(url, function(data) {
$('.' + idNum).empty().html(data);
});
}