I have a searchbar included with the livesearch.com functionality from ajaxlivesearch.com
The problem is when i click on a result nothing happens. I want to send a query and show a result page when i click on the result. Before i included the ajaxlivesearch funtion i just typed in a keyword and pushed enter and then my result page showed up, this happens with an query. But after i included the ajaxlivesearch funtion pressing enter was not an option anymore, nothing happens.
I think the problem is within these jQuery lines;
jQuery(".mySearch").ajaxlivesearch({
loaded_at: <?php echo $time; ?>,
token: <?php echo "'" . $token . "'"; ?>,
maxInput: <?php echo $maxInputLength; ?>,
onResultClick: function(e, data) {
// get the index 1 (second column) value
var selectedOne = jQuery(data.selected).find('td').eq('1').text();
// set the input value
jQuery('.mySearch').val(selectedOne);
// hide the result
jQuery(".mySearch").trigger('ajaxlivesearch:hide_result');
},
onResultEnter: function(e, data) {
// do whatever you want
// jQuery(".mySearch").trigger('ajaxlivesearch:search', {query: 'test'});
},
onAjaxComplete: function(e, data) {
// do whatever you want
}
});
I hope someone can help me out
Cheers!
Before you do anything, go to the ajaxlivesearch.js file, and find this line of code ->
// disable the form submit on pressing enter
form.submit(function () {
return false;
});
Basically it's disabling anything form happening when you press enter, which is kind of the opposite of what you're trying to do. So obviously you need to change it, ex.
$("#search_ls_query").submit(function(){
return true;
});
Now, (This is not an entirely vital addition but nonetheless, submit the form in the "onResultEnter" area that you add to your index page. Ex.
jQuery(document).ready(function(){
jQuery(".mySearch").ajaxlivesearch({
loaded_at: <?php echo $time; ?>,
token: <?php echo "'" . $token . "'"; ?>,
maxInput: <?php echo $maxInputLength; ?>,
onResultClick: function(e, data) {
// get the index 0 (1st column) value
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// set the input value
jQuery('.mySearch').val(selectedOne);
// hide the result
jQuery(".mySearch").trigger('ajaxlivesearch:hide_result');
},
onResultEnter: function(e, data) {
$("#search_ls_query").submit();
},
/* #search_ls_query is the id of the default form that is submitted when you press enter (Find in ajaxlivesearch.js)*/
onAjaxComplete: function(e, data) {
}
});
})
Now go to the ajaxlivesearch.js file and find this:
var wrapper = '<div class="' + ls.container_class + '">' +
'<form accept-charset="UTF-8" class="' + ls.form_class + '" id="' + ls.form_class + '_' + elem_id + '" name="ls_form">' +
'</form>' +
'</div>';
And add an action to this form as this is what is being activated when you press enter in the search bar. So make it this:
var wrapper = '<div class="' + ls.container_class + '">' +
'<form accept-charset="UTF-8" action="search.php" class="' + ls.form_class + '" id="' + ls.form_class + '_' + elem_id + '" name="ls_form">' +
'</form>' +
'</div>';
This way it actually has a destination to send the values to. So the name of the value being sent is "ls_query", so whatever you type in the bar will now be inserted into the value of "ls_query". Therefore, once you press enter and arrive at your new page, you can then use this variable to filter your search options, or whatever you need. For example, on your search page you could write:
$ls_query = secure($_GET['ls_query'],$mysqli);
$sql = "SELECT *
FROM users
WHERE username ='$ls_query'";
This took me a while to figure out as well. But if you're still looking for the answer, this worked for me. Let me know how it went!
Related
I'm learning JavaScript but I want the following thing in my little (self-started) project as soon as possible.
Suppose the page of my website is www.mywebsite.com/myPage.html
Here is a scenario that 10 users are viewing myPage.html from my website. As I make any change to myPage.html from server (being admin), I want all viewers of myPage.html to see refreshed page with new changes taken effect just after I make any change in myPage.html. It should be very fast.
For this I think I'll have to create a button which will refresh the page myPage.html. As I'll make changes to myPage.html, I'll press that button and that button will reload every viewer's browser's page (myPage.html). And they will see the result of modified myPage.html in their browsers.
Kindly explain your answer properly, since I'm a beginner. Which Languages are needed for this?
i think the best option here would be some kind of push implementation / web sockets ... here are a few links to get you started in the right direction ...
Websockets : Using modern HTML5 technology for true server push
Push Notifications to the Browser With Server Sent Events
In the case of socket.io in client side(browser) subscribe every client with a particular channel and make the page reload with javascript when request from server via that channel is recieved. And in server you can broadcast message to that particular channel whenever you want to reload the page.
you can create an AJAX function that is executing in intervals(like every 10 seconds) and this function will connect to server to ask for any update from mysql, so if there's any updates! you notify the user.
so you should create a table in DB to be updated with page update info when you update a page.
AJAX(asynchronous javascript and xml ) is a technology connect to your server without having to use Forms to post, and you can refresh part of your page automatically.
now here is an example:
I wanted to create an online chat, so here is the code:
this code use ajax to post to ChatNotifyController.php to see if theres anyone online,if there's any it will notify the user.
//notify user if someone has or had send a message
setInterval(function(){
xmlhttp.open("POST" , "../controller/ChatNotifyController.php" , true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
if(xmlhttp.status == 200)
{
if((xmlhttp.response).length > 4)
{
var friendName = (xmlhttp.response).replace(/^\s*$[\n\r]{1,}/gm, '');
var responseArea = document.getElementById( friendName + 'ChatArea');
var x = friendName ;
if(x.indexOf('.') > 0)
{
x = x.replace('.', '\\.');
}
var link = $('#' + x);
var input = $('#' + x + 'ChatInput');
var e = jQuery.Event("keydown");
e.which = 13;
if(link.length > 0)
{
link.click();
input.trigger(e);
}
else
{
var html = "<li><a class=\"onlineUserLink\" id=\"" + friendName + "\" onclick=\"chat(" + "'" + friendName + "'" + ")\" >" + friendName + "</a></li>";
html += "<div class=\"chatDialog\" title=\"'" + friendName + "\"' id=\"'" + friendName + 'ChatDialog' + "'\">";
html += "<div class=\"chatArea\"" + " id=\"'" + friendName + "ChatArea" + "'\">" + "</div>";
html += "<input class=\"chatInput\"" + " id=\"'" + friendName + 'ChatInput' + "'\" size=\"21\" onkeydown=\"chatController(event , '" + friendName + "' , '" + window.user + "')>" + "</div>";
window.onlineArea.innerHTML += html;
var THIS = $('#' + x + 'ChatDialog');
$(function() {
THIS.dialog({
stack: false
});
});
link.click();
input.trigger(e);
}
}
}
else
{
//alert("Error during AJAX call. Please try again #003");
}
}
};
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("user=" + window.user);
} ,5000);
I've been wrestling with a problem that I just cannot seem to solve. I've got a web form that is built from a MySQL query that's run from PHP and returned to JQuery that displays a gallery of movies that the user can give a numeric rating. I'm wanting to send the form back to PHP for processing and writing to the database.
function loadGallery()
{
$('content').append('<form id="movieRatings" action="../php/saveRatings.php" method="post">).html();
$.get('../php/getMovies.php')
.done(function(data) {
var query = $.parseJSON(data);
for (var i = 0, len = query.length; i < len; i++) {
var galleryMovies = '<div class="movContainer">' +
'<div class="movie">' +
'<a title="' + query[i].mov_title + '" href="../' + query[i].mov_title + '.html">' +
'<h3>' + query[i].mov_title + '</h3>' +
'<img src="../imgs/' + query[i].poster_path + '" /></a>' +
'<input type="number" name="' + query[i].mov_title + '" >' +
'</div>' +
'</div>';
$('#content').append(galleryMovies).html();
}
$('#content').append('<input type="submit" value="Submit"></form>');
})
.fail(function() {
$('#content').html("Epic Fail!") ;
});
}
The form displays without any issues, but clicking the submit button doesn't even send the request for the "saveRatings" PHP file. I'm sure I'm missing something simple, I just can't seem to figure out what that is. My first thought was that it was because the gallery isn't part of the actual html, but from what I've read that shouldn't have anything to do with it.
And pointers/sugestions/insight would be appreciated.
instead of
$('#ID').click(function(){
// do something here
});
switch to
$(document).on("click", "#ID", function(){
// do smth here
});
Your first assumption was true, if the element is not part of the initial html, then any events bound to it won't work unless you go with my second approach. You can find more about this behavior in the jquery documentation.
L.E: same goes for the submit action, in case i was not clear with the click example:
$(document).on("submit", 'form#formID',function(){
// do smth here...
});
I am a newbee in php,jquery and ajax. I have a code in jquery to add and remove the textboxes dynamically on button click. I want to post the values of dynamically created textbox values to next page and display those values in next page. Any help is much appreciated.Thanks in advance.
I have pasted the code below..
You can also check the link http://jsfiddle.net/NSePb/1/
$(document).ready(function () {
var counter = 1;
$("#addButton").click(function () {
if(counter>7){
alert("Only 7 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Product #'+ counter + ' : </label>' +
'<input type="text" size="22" name="product' + counter +
'" id="product' + counter + '" value=""> \n\
<label>Quantity #'+ counter + ' : </label>' +
'<input type="text" size="1" name="qty' + counter +
'" id="qty' + counter + '" value=""> \n\
<label>Rate #'+ counter + ' : </label>' +
'<input type="text" size="2" name="rates' + counter +
'" id="rates' + counter + '" value="" > \n\
<label>Total #'+ counter + ' : </label>' +
'<input type="text" size="3" name="total' + counter +
'" id="total' + counter + '" value="" > ');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==0){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
When you are creating the text boxes dynamically, i assume your text box names to be dynamic which i can't see here. So, store the dynamic field names in an array as
$request = array(#field names#) // comma separated
$requestJson = json_encode($request);
Pass
$requestJson as an hidden field in the form and submit the form.
In the next page i.e. in the action page receive the hidden field and decode it
$requestArr = json_decode($_REQUEST['requestFields']);
Loop the array and receive the values as
for($i=0; $i < count($requestArr); $i++)
{
$value = $requestArr[$i]; // get the field name
$content = $_REQUEST[$value]; // get the input value
$fetchedResult = array($content); // Store the text field value
}
Now your $fetchedResult will have the values to your future usage.
UPDATED - AS PER THE LATEST QUESTION ON COMMENT
var queryArr = [];
newTextBoxDiv.appendTo("#TextBoxesGroup"); // after this line add
queryArr.push(product' + counter + '); // alert OR print in console to check the array values as and when the button is clicked.
$("#TextBoxDiv" + counter).remove(); //after this add
var removeItem = product' + counter + ' // #removed id#;
y = jQuery.grep(queryArr, function(value) {
return value != removeItem;
});
$('<input>').attr({
type: 'hidden',
id: 'foo',
name: 'bar',
value : queryArr
}).appendTo('form');
You need use the $_POST superglobal, and use the id of the HTML element.
Consider this:
<form action="foobar.php" method="post">
<input type="text" id="an_element" name="an_element" />
</form>
If you wanted to display this using PHP, you would go to the page where the action attribute is pointing (in our case, foobar.php), and use the $_POST superglobal.
So the PHP code would look like this:
<?php
echo $_POST['an_element'];
?>
So, using your rates textbox as an example, you might want to do this:
<?php
echo $_POST['rates'];
?>
Please note that if you set the action attribute to get, you will need to use $_GET instead of $_POST.
Also, just taking a look at your code, you are missing the form element in your HTML. Instead of using $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);, you might want to use this:
$(document.createElement('form'))
.attr({
id: 'TextBoxDiv' + counter,
action: 'foobar.php',
method: 'post'
});
I was wondering how it would be possible to attach an HTML form's text box value to a link. For instance, I have 3 links and each link goes to a different PHP file, however, I need to pass a variable. Because of the design of my page, I cannot use buttons. So, I created a form with a text field. How do I send that Text Fields value with the links?
EG:
<form>
<input type="text" name="test1" id="test1"></input></form>
Link 1
Link 2
Link 3
I hope this makes sense as to what I am trying to do.
EDIT:
I tried to do this dynamically, but:
OK, I made a function like this:
<script>
function awardcode()
{ var awamount = document.getElementById("awardamount");
document.write('<?php $awardvar = ' + awamount.value + '; ?>');
};
</script>
Then, I made the link via PHP that looks like this:
echo '<a id=awlink3 name=awlink3 href="index.php?siteid=gmaward&type=xp&post=' . $posts_row['posts_id'] . '&handle=' . $posts_row['handle'] . '&varamount=' . $awardvar . '">Award XP</a>';
However, that didn't work. This is my input box code:
<form><input type=text name='awardamount' id='awardamount' onchange='awardcode()' style:'width:10px;'></form>
When I put the number and then tab, it loads an empty page.
How can I adjust that?
You'll need to dynamically change the link using JavaScript. Here's one approach:
$('a').on('click',function(e) {
e.preventDefault();
var url = $(this).attr('href').split('$')[0];
window.location = url + $('#test1').val();
});
But it might be better to add an onchange event to the textbox itself, so that the HREF changes instantly and the user can see the intended destination on mouseover:
$('#test1').on('change', function () {
var val = $(this).val();
$('a[href*=\\?id\\=]').each(function (i, el) {
$(el).attr('href', function (j, str) {
return str.split('?')[0] + "?id=" + val;
});
});
});
Hello I am using autocomplete to allow users to search venues stored in a MySQL database. The autocomplete plugin is currently listing the venues when the user begins typing and prints the selected venue using the result handler.
I would like to also print the address, phone number and website of the venue as well but I am not sure how to do this.
I have the autocomplete plugin running a php script to print out the venue names from the database. I am not sure how to retrieve the other fields in the database without displaying the autocomplete input field...
This is what I have so far:
JQuery
$(document).ready(function(){
$("#example").autocomplete("search.php", {width: 260, selectFirst: false}).result(function(event, data, formatted) {
$("#result").html( !data ? "No match!" : "Selected: " + formatted);
});
});
PHP
$search = $_GET['q'];
$search = "%".$search."%";
$result = mysql_query("SELECT club_name FROM clubs WHERE club_name LIKE '$search'") or die('Something is wrong');
while($value = mysql_fetch_array($result)){
$club = $value[club_name];
echo "$club\n";
}
The php above only select the club name because when I try to select more fields they display in the search results on the JQuery side.
I am new to JQuery so I am a little lost... Any suggestions?
There are a few ways to do it, but this is the easiest:
You want to return the data from the server like this. The first column should contain the value you want to retrieve in the end:
title|address|phone|web
title|address|phone|web
title|address|phone|web
And then you want to use the formatItem and formatValue callback in your autocomplete function:
$(document).ready(function(){
$("#example").autocomplete("search.php", {
width: 260,
selectFirst: false,
formatItem: function(row){
var ret = '<span class="title">' + row[0] + '</span><br />';
ret += '<span class="address">' + row[1] + '</span> ';
ret += '<span class="phone">' + row[2] + '</span> ';
ret += '<span class="web">' + row[3] + '</span> ';
return ret;
},
formatValue: function(row){
return row[0]; // We only want the first value to be searched
}
}).result(function(event, data, formatted) {
$("#result").html( !data ? "No match!" : "Selected: " + formatted);
});
});
Also, your are not escaping the input from the user and as such have a nasty vunerability for SQL injection