Now that I can utilize the search function for reddit's API, I want the user to input their own query. I'm new to javascript and I think the problem with my code is that the API search function is being ran before the user even inputs the query.
HTML:
<div id="site-content">
<form name="RedditSearch">
Enter your query:
<input type="text" name="query" onkeydown="if (event.keyCode == 13) document.getElementById('search').click()"/>
<input type="button" id="search" value="Search" onclick="searchquery();" />
</form>
</div>
Javascript:
var container = $('#site-content')
function searchquery()
{
var query = document.RedditSearch.query.value;
}
$.getJSON("http://www.reddit.com/search.json?q=" + query, function(data) {
$.each(data.data.children, function(i,item){
var title = item.data.title
var post = '<div>'+title+'</div>'
container.append(post)
});
});
Indeed, it appears that your getJSON query is executed when the page loads. At that time, the user hasn't input anything yet, so it is executed too early.
You need to add an event listener which will detect user input, and then perform the AJAX call to the reddit API.
Assuming your user inputs his keywords in a text area, you could use .change().
You can fine more informations here : http://api.jquery.com/category/events/ or here http://www.w3schools.com/jquery/event_change.asp
Example in your case : http://jsfiddle.net/2ECG6/1/
Related
I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >
I have a file called bpSearch. Inside bpSearch, I have a MODAL window, called addNewModal. Within addNewModal, I have 2 INPUT fields called partnerName and partnerCode. I have a button that once clicked, opens into another MODAL window, called searchPartnerModal.
Here is the a portion of the FORM inside addNewModal:
<form action="bpSearch.php" method="get">
<input type="text" readonly id="partnerName" name="partnerName" />
<input type="text" readonly id="partnerCode" name="partnerCode" />
Go
</form>
When the user clicks GO, it opens searchPartnerModal.
searchPartnerModal is where the user will enter either a code or a name (doesn't have to be both). But upon hitting SEARCH, I use an AJAX call that returns JSON that I parse and eventually return in a UL field called pNames. We're still inside searchPartnerModal.
Here is the FORM inside searchPartnerModal:
<form action="bpSearch.php" method="get">
<input type="text" id="pNameSearch" name="pNameSearch" />
<input type="text" id="pCodeSearch" name="pCodeSearch" />
<input type="button" class="btn" id="pSearch" name="pSearch" value="search" />
</form>
When the user enters a name, I use jquery to send it over to a PHP script that will then return the data in a UL tag.
Here is the jquery that will search if the user enters a name:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pNames').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li><a id="getPInfo" href="javascript:;"
onclick="getPInfo()" data-selname="'+item.FULL_NAME+'"
data-selcode="'+item.PARTNER_CODE+'">'
+ item.FULL_NAME + ' - '
+ item.PARTNER_CODE + '</a></li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
With this code, I am able to send the name to search the database table for a valid name. The data is returned via JSON and is parsed and displayed inside the UL tag (called pNames) as LI tags, each with an A tag with their own data-attributes, called data-selname and data-selcode.
Now what I need to do is once the user clicks on one of the returned data links inside pNames, I need to send it back to the previous modal window, addNewModal.
This is where I'm stuck.
If you look inside the Jquery above, after I parsed the JSON, you will see that I created another Javascript function inside the A tag of each returned piece of data, called getPInfo().
Here is what I got so far for the function getPInfo() :
function getPInfo()
{
var selname = ($('#getPInfo').attr('data-selname'));
var selcode = ($('#getPInfo').attr('data-selcode'));
}
At this point, I can alert both variables (selname and selcode) and get them to display in an alert window.
What I want to do is send both of those variables back to addNewModal in the respective INPUT fields, called partnerName and partnerCode.
So selname will go to partnerName and selcode will go to partnerCode.
I didn't display the PHP script that returned the data.
Change the anchor id=getPInfo to class=getPInfo since you have multiple anchors. Next, handle the click event of the anchor and extract the data attributes and set the corresponding form elements in the addNewModal form. Following should work based on the markup i see so far.
$(function(){
$('body').on('click', 'a.getPInfo', function (e) {
var $a = $(e.srcElement || e.target);
$('#partnerName').val($a.attr('data-selname'));
$('#partnerCode').val($a.attr('data-selcode'));
$('#searchPartnerModal').modal('hide'); //assuming bootstrap modal
});
});
I've a form with two textboxes for API Key and for stock ticker. Please find below the code.
<h1>Stock</h1>
<form id="frmGetComp">
<p>API Key: <input type="text" id="txtAPI" value="" /></p>
<p>Stock: <input type="text" id="txtStock" value="" /></p>
<p><button id="btnCall">Call</button></p>
</form>
And below is the jquery code:
$(document).ready(function () {
var stockId='';
$("#txtStock").blur(function () {
stockId= $(this).val();
console.log(stockId);
});
$('#btnCall').click(function () {
var apiKey = $('#txtAPI').val();
stockId= $("#txtStock").val();
console.log(':::call clicked:::', stockId);
<assigning apikey statement> = apiKey;
<stockId is passed in api call to fetch stock information>
$('#frmGetComp').submit(false);
$('#frmGetComp').reset = true;
stockId= '';
$('#txtStock').val('');
});
});
Now in this form when I enter information first time it retruns correct data. When I change the value of stock and click call button, every time it returns the stock information of first stock. It never takes new value entered in stock textbox.
How do I get new value of stock textbox and get the information of that stock when call button is clicked ???
I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.
I'm fairly new to the whole Javascript scene. Followed along with those online javascript tutorial things like code academy offers so I'm going by what I learned off of there and what I have read through other tutorials. Read though a few other posts to try and help me but I can't figure it out
So here's my question,
I am trying to take a form input, send it to a javascript file, then the javascript file returns a string which then I wish to reload the frame with. I'm attempting to make a simple chrome extension for me and my friends.
When I click "View Grade!" I get an error:
No webpage was found for the web address: chrome-extension://gcgddggimojbfgpbdmpfkmiofmpinjgb/location.href=getURL(account)?
and I can't determine if my javascript isn't working right or I just don't know how to send to a URL outside the "chromium" (as I call it) world.
This is my html file:
<form action="location.href=getURL('account')">
PSU Account (i.e. xyz123): <input type:"text" id="account">
<input type="submit" value="View Grade!">
</form>
And this is my javascript file:
function getURL(account) {
var psuAccount = document.getElementById(psuAccount);
// I changed strA to the ***.***.*** for this post
var strA = 'https://***.***.***/section/Gradebook/Student/default.aspx?userId=';
var strB = '&reportMode=true';
var newURL = strA + psuAccount + strB);
return(newURL);
}
I think this is exactly what <form>s are for...no need for Javascript for something like this. Try:
<form action="https://***.***.***/section/Gradebook/Student/default.aspx" method="GET">
PSU Account (i.e. xyz123): <input type="text" name="userId" />
<input type="hidden" name="reportMode" value="true" />
<input type="submit" value="View Grade!" />
</form>
The submit mechanism will automatically use the action attribute of the form. Since the method is "GET", it will also add a querystring of key/value pairs for elements in the <form> with a name attribute. So with your form, it will add a key "userId" with the value as the textbox's current value at time of submission. It will also add a key "reportMode" with the value "true". So the final URL that will be submitted is:
https://***.***.***/section/Gradebook/Student/default.aspx?userMode=true&userId=SOME_INPUT_STRING
If you need to use Javascript, try:
<div>
PSU Account (i.e. xyz123): <input type:"text" id="account" />
<input type="button" value="View Grade!" onclick="getURL();" />
</div>
with:
function getURL() {
var psuAccount = document.getElementById("account").value;
var strA = 'https://***.***.***/section/Gradebook/Student/default.aspx?userId=';
var strB = '&reportMode=true';
var newURL = strA + psuAccount + strB;
window.location.href = newURL;
}