I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/.
My problem is, when the user searches for something and then selects a new search type (clicks on a tab) they have to go to the text box and press enter to submit their query again. How can I make it so when a search is active and a tab is clicked that it loads the results straight away instead?
I hope you can understand what I'm trying to describe. JSfiddle: http://jsfiddle.net/phWSR/
My current jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
});
$('#type_search').click();
$('input').keyup(function () {
query = $(this).val();
url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
});
My current HTML code is:
<div id='nav'>
<a id='type_search'>All</a>
<a id='type_images'>Images</a>
<a id='type_videos'>Videos</a>
<a id='type_news'>News</a>
<a id='type_social'>Social</a>
</div>
<input type='text' autocomplete='off'>
<div id='results'></div>
You could isolate the code for the ajax call (currently in $('input').keyup()) in a separate function, and bind it to both $('input').keyup() and $('#nav a').click().
Related
I cannot seem to get my suggestion box to show for the nearest input after adding more inputs dynamically.
The below code is where I am currently, I can see the suggestion box for a new input and add to that new input but if I go back to edit the input data the suggestion box fails to show.
<div id="tester"></div>
<button id="add_test">ADD</button>
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$(".flavour-name-input").css("background","#FFF no-repeat 165px");
$(".suggestion-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
$('.flavhey input').closest('flavourInput input').next('.suggestion-box').show();
$('.flavhey input').next('.suggestion-box').html(data);
$(".suggestion-box").css("background","#FFF");
}
});
return false;
});
$(document).on("click",".search-flavour",function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li class="search-flavour"><b>'.$con['flavour_name'].'</b> - <i>'.$con['flavour_company_name'].'</i></li>';
}
$html .= '</ul>';
echo $html;
}
}
Ok short version:
Use var box = $(e.target).next(".suggestion-box"); to aquire a reference to the correct suggestion box in the success handler of the ajax request.
Long version:
I replaced the php parts with static placeholders to get a runnable example.
$(document).ready(function() {
$("#add_test").on("click", function() {
var input = '<div class="flavhey"><div class="flavourInput"><input class="ftext form-control flavour-name-input" type="text" name="flav-name-input" value="" placeholder="Flavour Name" /><div class="suggestion-box"></div></div></div>';
$('#tester').append(input);
});
$(document).on('keyup', '.flavhey input', function(e) {
var token = "[token]";
var search = $(this).val();
var box = $(e.target).next(".suggestion-box");
box.show();
box.html("TestData");
box.css("background", "#FFF");
return false;
});
$(document).on("click", ".search-flavour", function(e) {
e.preventDefault();
$(this).closest('.flavourInput').find('.flavour-name-input').val($(this).text());
$('.suggestion-box').hide();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tester"></div>
<button id="add_test">ADD</button>
<ul>
<li class="search-flavour">
<b>flavour_name_1</b> - <i>flavour_company_name_1</i>
</li>
<li class="search-flavour">
<b>flavour_name_2</b> - <i>flavour_company_name_2</i>
</li>
<li class="search-flavour">
<b>flavour_name_3</b> - <i>flavour_company_name_3</i>
</li>
</ul>
Now being able to execute your code I was able to reproduce the described error. Please try to provide a runnable example next time.
I realized that your box was only appearing once because the call to .show() wasn't working at all. It was visible from the beginning just without any content so you couldn't see it, then after setting html() it had content and it looked like the call to show() worked as intended.
Afer you clicked on a .search-flavour all boxes were correctly hidden and thus never appeared again.
So to fix this, replace the success handler of the ajax request with this:
success: function(data){
// e.target is the currently active input element
var box = $(e.target).next(".suggestion-box");
box.show()
.html(data)
.css("background", "#FFF");
}
So I got a select menu and when an user select an option, it calls a post function via ajax that generates some table rows via PHP and then it returns the html coding for it. In it, there is an Add button.
What I am trying to do is that when the user clicks the add button, a form shows up.
But for some reason, it is not working...
Here is the code:
$(document).ready(function () {
$(".add_form").hide();
$("#console").change(function () {
var id = $(this).val();
var dataString = 'console_id=' + id;
$.ajax({
type: "POST",
url: "generate-games-list",
data: dataString,
cache: false,
success: function (html) {
$("#games_table_body").html(html);
}
});
});
$(".add_button").click(function () {
alert("HELLO");
var id = this.id;
$.post('manage_games', 'game_id=' + id, function (response) {
alert(response);
});
$("#game_id").val(id);
$(".add_form").show();
});
});
Here is the PHP code that returns the table rows:
$console = Console::find(Input::get('console_id'));
$type = GameType::find(Input::get('type_id'));
if(!Input::has('console_id'))
return "Error";
else{
foreach($console->games()->get() as $console_game){
$available_consoles_string = "";
$game_types_string = "";
//Get all the consoles the game can be played on
foreach($console_game->consoles()->orderBy('name', 'asc')->get() as $available_consoles){
$available_consoles_string = $available_consoles_string . " " .$available_consoles->name .", ";
}
//Get all the types that the game falls in
foreach($console_game->types()->orderBy('type', 'asc')->get() as $game_types){
$game_types_string = $game_types_string . " " .$game_types->type .", ";
}
return "<tr><td>" .$console_game->name. "</td><td>". $available_consoles_string. "</td><td>" .$game_types_string. "</td><td><input type='button' id='" .$console_game->id. "' class='add_button' value='Add'/> / View</td></tr>";
}
}
Any idea why it is not working? When I mean not working, I mean the alert is not showing up but I am not getting any error on the Chrome Console...
Thanks,
Ara
Simply use .on():
$(document).on("click", ".add_button", function(){
// your event code
});
When your js runs a click event is attached to all current elements with the .add_button class. However, you're adding extra buttons via ajax and these won't have trigger the same click event.
To fix this use the code above. It attaches the event to the document so even if you add buttons once the page has loaded the click event will be triggered by them.
I'm looking to put a div on my website where the content changes based on what link is clicked without refreshing. The content to put there comes from a MySQL database and it's put in JSON.
My problem is that I can't get the JSON data to display when clicking the links.
Here's the script I'm using:
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
for(var i=0; i<data.length;i++) {
$("#changetext"+data[i].id).click(function() {
$("#rightside").html("<h1>" + data[i].title + "</h1><p />" + data[i].content);
});
}
}
});
This is the div element that has to change:
<div class='rightside' id='rightside'>Test</div>
The links are constructed this way:
echo "<a id='changetext" . $row['id'] . "'> ";
echo "<div class='tile'>";
echo "<h2>Tile</h2></div></a>";
I've tested the different elements and they work fine (changing the divs content with hardcoded data, displaying the JSON data), but I'm having a hard time figuring out why the combined thing isn't working.
Objects does'nt have a length, use $.each to iterate it instead, unless it's actually an array containing objects :
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
$.each(data, function(i, d) {
$("#changetext" + d.id).on('click', function() {
var h1 = $('<h1 />', {text : d.title}),
p = $('<p />', {text : d.content});
$("#rightside").html(h1.add(p));
});
});
}
});
The problem is that i var will be data.length at the end of the loop and that's what the click handler will see.
New here and glad to be, I've gotten a lot of answers from this forum. I am however stuck at the moment.
I have some javascript that is creating a window color and handle picker (click on the color swatch it changes the image, click on a handle and it does the same). Below the image is a description of the window selected. This text is being generated by the javascript by pulling the image titles.
Now the fun part. Below this picker I need to add a form that will be emailed using php. Within that email I need to pull the window description that is being generated by the javascript.
I have tried so many things today I have lost count. The last bit of code I tried was
<script>
$(document).ready(function() {
$("windowDesc").each(function() {
var html = jQuery(this).html();
});
});
</script>
And in the php mail file I added:
$windowtitle = $_GET['html'];
as well as trying
$windowtitle = $_POST['html'];
and I have also tried the following:
<script>
var content = $('#windowDesc').html();
$.ajax({
url: 'send_mail.php',
type: 'POST',
data: {
content: content
}
});
</script>
And in the php mail file I added:
$windowtitle = $_GET['content'];
as well as trying
$windowtitle = $_POST['content'];
Not to mention a plethora of other things.
Basically what I am trying to do is grab the content of the div that holds the generated text and email it. If any of the above are correct then I must be placing them in the wrong position or something. With the first one I have tried it inside the form, outside the form, before the div, after the div. Just haven't tried it on top of my head yet. It's been a long day, thanks in advance :o)
Sorry for the delay, been a busy two days. OK, so here is the code that handles the window color and handle picker:
var Color = "color";
var Handle = "handledescription";
var ColorDesc = "color";
var HandleDesc = "handle description"
function Window(Color,Handle,ColorDesc,HandleDesc) {
$('#windowPic').animate({opacity: 0}, 250, function () {
thePicSrc = "http://www.site.com/images/windows/" + Color + Handle + ".jpg";
$('#windowPic').attr('src', thePicSrc);
$('#windowDesc').html("<p>" + ColorDesc + " frame with " + HandleDesc + " hardware</p>");
$('#windowPic').animate({opacity: 1}, 250)
})
}
$(document).ready(function() {
$('#wColors li').click( function() {
Color = $(this).attr('id');
ColorDesc = $(this).attr('title');
Window(Color,Handle,ColorDesc,HandleDesc);
});
$('#wHandles li').click( function() {
Handle = $(this).attr('id');
HandleDesc = $(this).attr('title');
Window(Color,Handle,ColorDesc,HandleDesc);
});
});
You need a hidden input in your form:
<form id="send_email" action="send_email.php">
<input id="content" type="hidden" name="content"/>
... other inputs here
</form>
Then you can use Javascript to fill it in before submission:
$("#send_email").submit(function() {
$("#content").val($("#windowDesc").html());
}
<script>
var content = $('#windowDesc').html();
$.ajax({
url: 'send_mail.php',
type: 'POST',
data: content
});
</script>
It worked here.
I'm using jquery tabify with 4 tabs and each content same form calling via ajax.(assume form.php)
1st tab everything works fine with the form.
2nd,3rd and 4th tab failed to get input type="text" value
tabify field with (4 tabs here actually I make it short as the code is long):
$(document).ready(function () {
$('#general_information_tab').tabify();
});
function recp(refer,id,plan){
if(plan == 0)
{
$('.stgcontent').load('stage/stage_procedure1.php?plan_id=' + id + '&T_REFERID=' + refer );
}else{
$('.stgcontent').load('stage/new_taskstg.php?plan_id=' + id + '&T_ID=' + refer);
}
<div id="general_tab_content">
<ul id="general_information_tab" class="general_information_tab">
<li class="active"><a href="#one" onClick="recp('1','<?php echo $plan_id; ?>','0')" >Immediate Response Steps</a></li>
<div id="one" class="content_gi">
<div class="stg1">
<img src="images/task/add.ico" height="10px" width="10px" /> Add Task
<div class="stgcontent">
<script type="text/javascript">
recp('1','<?php echo $plan_id; ?>','0');
</script>
</div>
</div>
</div>
in new_taskstg.php
$(function(){
$(".newTaskSubmitBtn").click(function(){
var T_CONTENT = $(".task_name").val();
var T_REFERID = $(".refer").val();
var SAVE_PLAN = $(".plan").val();
var V_ID = $(".vendor").val();
var dataString='T_CONTENT=' + T_CONTENT + '&T_REFERID=' + T_REFERID + '&SAVE_PLAN=' + SAVE_PLAN + '&V_ID=' + V_ID;
alert(T_CONTENT + T_REFERID + SAVE_PLAN + V_ID);
if(T_CONTENT=='' || T_REFERID=='' || SAVE_PLAN=='' || V_ID=='')
{
//ERROR MESSAGE
$(".fail").show();
$(".success").hide();
}
else
{
$.ajax({
type: "POST",
url: "stage/insert.php",
data: dataString,
success: function(data){
//SUCCESS MESSAGE
$(".success").show();
$(".fail").hide();
}
});
}
return false;
});
});
form field code:
<input type="text" name="task_name" class="form_input task_name" />
TEST I DID :
As above var T_CONTENT = $(".task_name").val(); and prompt like this alert(T_CONTENT); what it shows on 1st tab it able to capture it while the 2nd 3rd and 4th tab failed...
Was suspecting multiple instances problem...
Problem Solved. Mian point is to avoid from multiple instances since tabify couldn't differentiate which tab the form is and it takes 4 tabs together. So to solve my case I just use unique id in 4 forms.