So I have a simple search form at the top of my document which is ment for tags. It looks like this:
<div id="search">
<form id="srch">
<input type="text" placeholder="No filthy keywords pls." id="sbx"/>
<i class="fa fa-search"></i>
</form>
</div>
And I want the user to write a tag into the "search" field and when he presses the submit button it gets the photos based on the tag he supplied and fetches photos from flickr and fills a #container div with them. The jQuery I have so far looks like this:
var searchTerm = $("#sbx").val();
var Flickurl = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=376b144109ffe90065a254606c9aae3d&";
var tags = "&tags=" + searchTerm;
var tagmode = "&tagmode=any";
var jsonFormat = "&format=json";
var FinalURL = Flickurl + tags + tagmode + jsonFormat;
$(document).ready(function() {
$("#btn").click(function(event){
$.getJSON('FinalURL', function(photo) {
$('#content').append('<img src="' + 'https://www.flickr.com/photos/' + photo.owner + '/' + photo.id + '"/>');
});
});
});
I cannot find any help anywhere, I'm doing this as a schools project and I have never, ever done anything with API's I think I'm misunderstanding something in the jquery and api documentation because this is not doing anything at all lol..
I will be super happy if there is anyone who could help me with this, I feel like the code should be good but maybe I'm missing something small.. ?
You are fetching the string 'FinalURL', which will be resolved to CURRENT_URL/FinalURL, try this
$.getJSON(FinalURL, ... (without the quotes ')
Ok i found some other errors too.
Change your var jsonFormat to this "&format=json&nojsoncallback=1" to get jsonrawdata from the api.
The json returned isn't one photo, it's a list of all photos, so to access one photo you have to do this: response.photos.photo[NUMBER]
Your url is pointing to a flickr page and not to an image source, it should be like this: https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
I fixed your errors in this fiddle: JSFiddle
Something like this will work. You just needed to change how you were populating the url queries into a javascript object.
http://jsfiddle.net/669jy9am/
Obviously this won't work on JSFiddle, but if you put that into your own page, it should work.
<div id="search">
<form class="search--form">
<input type="text" placeholder="No filthy keywords pls." id="sbx" />
<button type="submit" id="btn">Search<i class="fa fa-search"></i>
</button>
</form>
function searchFlickr() {
var searchTerm = $("#sbx").val();
var Flickurl = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=376b144109ffe90065a254606c9aae3d&";
$("form").submit(function (event) {
event.preventDefault();
var searchTerm = $('#sbx').val();
$.ajax({
url: 'Flickrurl',
data: {
format: "json",
jsoncallback: 1,
tags: searchTerm
},
}).done(function (data) {
//Populate the images with the data
});
});
}
$(document).ready(function () {
searchFlickr();
});
Related
I dynamically created a survey form using jquery and I want to submit the form via ajax and append my own data to it. I'm doing that because the created survey has questions in it and each question has a certain number of answers. But if you just submit the form you get an array of questions and an array of answers but there is no way to tell which answer belongs to which question. To deal with this problem, I've tried to create my own array, or rather a map where the questions are the keys and each question has its own answers as values. I didn't find a better way to accomplish that as to just use ajax to change the submit. As the title suggests, that didn't work, it just doesn't go through, there are no error messages.
$('.survey').submit(function(event){
event.preventDefault();
var map = new Array();
var q;
var form = $(this);
$('div[name="question"]').each(function(){
q = $(this).find('.question')[0].value;
map["q"] = new Array();
$(this).find('.answer').each(function(){
map["q"].push($(this).val()+"");
});
});
var data = form.serializeArray();
data["questions"] = JSON.stringify(map);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data
});
});
Thats the code in question that doesn't work and here is the jsfiddle for the whole program: https://jsfiddle.net/e9tbcwdj
Everything works fine except the submit. When I dont stringify my map I can see via alert that map got successfully appended to data and that data["questions"]["q"][0], for example, shows the expected result. Thats why I'm pretty sure the problem is the serialization, but I'm not really sure how to serialize my "map" since stringify didn't do the job. I'm always a little helpless when it comes to serialization. Should I maybe use the map function?
except using a class use id in ur form
var form = $('#surveyForm');
in ur html form add this id
<form method="POST" action="<?=base_url()?>start" class="survey" id="surveyForm">
<input type="hidden" name="action" value="add">
<input type="button" class="addQst" value="Add question">
<input type="submit" class="submitForm" value="Generate">
</form>
And give a name to ur question and answer input
var question = $('<input type="text" class="question" name="quest">');
var answer = $('<input type="text" class="answer" name="answr">');
Full Code
$(document).ready(function () {
$('.survey').submit(function(event){
event.preventDefault();
var map = new Array();
var q;
var form = $('#surveyForm');
$('div[name="question"]').each(function(){
q = $(this).find('.question')[0].value;
map["q"] = new Array();
$(this).find('.answer').each(function(){
map["q"].push($(this).val()+"");
});
});
var data = form.serializeArray();
console.log(data)
data["questions"] = JSON.stringify(map);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data
});
});
$('.addQst').click(function () {
var wrapperQuestion = $('<div name="question">');
var removeQuestion = $('<input type="button" class="rmvQst" value="Delete">');
var question = $('<input type="text" class="question" name="quest">');
var addAnswer =$('<input type="button" class="addAsw" value="Add answer">');
addAnswer.click(function() {
var wrapperAnswer = $('<div>');
var answer = $('<input type="text" class="answer" name="answr">');
var removeAnswer = $('<input type="button" class="rmvAsw" value="Delete">');
removeAnswer.click(function() {
$(this).parent().remove();
});
wrapperAnswer.append(answer);
wrapperAnswer.append(removeAnswer);
$(this).before(wrapperAnswer);
});
removeQuestion.click(function() {
$(this).parent().remove();
});
wrapperQuestion.append(question);
wrapperQuestion.append(removeQuestion);
wrapperQuestion.append($('<div>').append(addAnswer));
$(this).before(wrapperQuestion);
});
});
Hope this will help
New Updated Answer
$('.survey').submit(function(event){
event.preventDefault();
var map = new Array();
var q;
var form = $('#surveyForm');
$('div[name="question"]').each(function(){
q = $(this).find('.question')[0].value;
q = [];
$(this).find('.answer').each(function(){
q.push($(this).val()+"");
});
map.push(q)
});
var data = form.serializeArray();
data["questions"] = JSON.stringify(map);
console.log(data["questions"])
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: data
});
});
Thank you sayalok for all the trouble you've went through because of me, but I've got my problem now: My code works fine. I put a var_dump on the php page I was posting to, but because I used ajax and never changed pages, just posted to the php page, I never saw the var_dump and therefore thought, the submit didn't go through. Still, thank you for your help.
I am writing a small code with JavaScript (using jQuery and Knockout) and HTML that takes user input (GitHub username), checks if the input is valid against a GitHub api, and displays the user's GitHub avatar and username (linked to the matching profile on GitHub). The display replaces the form in which the user entered the username.The original HTML before the user inputs is:
<div id="inputSection">
<form>
<p>
GitHub Username:
<input type="text" name="username" value="" placeholder="username" id="un"/>
<button type="button" id="submitButton">Login</button>
</p>
</form>
</div>
And the code to replace it is this:
$("#submitButton").click(function() {
var username = document.getElementById('un').value;
var inputForm = $(document.getElementById('inputSection'));
$.ajax( {
...
success: function () {
alert("Welcome, " + username);
var userURL = 'https://github.com/' + username;
var inputContent = $('<a data-bind="attr: {href: userURL}"><img data-bind="attr: {src: avatar_url}" height=\"30\" width=\"30\"/>' + username + '</a>');
$(inputForm.replaceWith(inputContent));
}
});
});
It seems to work for the most part. After the alert welcomes the user by username, the form disappears from the webpage. It is replaced by the username, which is formatted like a link. However, it does not function as one. Clicking it does not do anything. Also, the user's avatar, despite showing a box of the set size on the webpage, does not appear.The solution is likely very simple and obvious, but as I only started learning these languages and libraries this week, I am not sure what is going wrong. Knockout should be running on the HTML page that calls the JavaScript page, and the ajax is working with regards to other functions, so I assume that's fine. The value "avatar_url" is a part of the api requested with ajax at https://api.github.com/users.I've tried all sorts of different things to no effect. If you want any more information or have a suggestion to make this question better, please comment. I'm new to coding and Stack Overflow, but I want to make both my programs and my questions as good as possible. Thank you for your time.
EDIT: 1. I originally failed to set a size for the image, resulting in a 0x0 image. This has been corrected, though the image itself still does not display. 2. When I first put in my code, I tried to make it easier to read by excluding where some variables had been renamed for other, unrelated portions and just making all the names match between the two relevant snippets. I did not catch them all. They should all match now.
Short answer:
You’re inserting an html element with data-binds without explicitly initializing its bindings. Use ko.applyBindings(vm, node) on the newly injected part of the DOM.
Long answer:
If you're new to coding and to both jQuery and knockout, I'd suggest not using both libraries at once. Here’s why:
If you want to use knockout, you'll have to stick to a certain kind of software architecture:
Simplify dynamic JavaScript UIs with the Model-View-View Model (MVVM) (http://knockoutjs.com/)
jQuery, on the other hand, is more of a toolbox. It doesn't dictate an architectural pattern.
It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. (https://jquery.com/)
This might sound a bit lame, and isn't really an answer, but I'll show you the differences between solving your problem the “knockout way”, and “the jQuery way”. I’ll start with the latter, since it’s closest to your current approach:
The jQuery approach (note that I'm skipping the Ajax part)
Find the elements you need to make your UI interactive. Attach event listeners to buttons, modify the DOM when new data is available.
$(document).ready(function() {
// Notice that you don't need document.getElementById
var submitButton = $("#loginButton");
var userNameInput = $("#un");
var inputSection = $("#inputSection");
var getContentString = function(userName) {
var userUrl = "https://github.com/" + userName;
var avatarUrl = "...";
// Inject the user specific attributes
return "<a href=`" + userUrl + "`><img src=`" + avatarUrl + "` height='30' width='30'/>" + userName + "</a>";
};
var onSubmitClick = function(event) {
var userName = userNameInput.val();
var onSuccess = function() {
// Create new <a> element and replace the form with the new HTML
var inputContent = $(getContentString(userName));
inputSection.replaceWith(inputContent);
};
/*
$.ajax({
success: onSuccess
});
*/
//Just call onSuccess to circumvent unimplemented ajax:
onSuccess();
};
submitButton.click(onSubmitClick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="inputSection">
<p>
GitHub Username:
<input type="text" name="username" value="" placeholder="username" id="un" />
<button type="button" id="loginButton">Login</button>
</p>
</form>
The knockout approach
Create a viewmodel for your user. Bind the input and compute the other properties automatically. Attach event listeners through data-binds. Use if, visible or template bindings to swap out parts of the UI.
var UserViewModel = function() {
this.userName = ko.observable("");
this.confirmed = ko.observable(false);
this.userUrl = ko.computed(function() {
return "https://github.com/" + this.userName();
}, this);
this.avatarUrl = ko.computed(function() {
return "???" + this.userName();
}, this);
};
UserViewModel.prototype.confirm = function() {
/* ajax (disabled for example)
$.ajax({
success: this.confirmed.bind(null, true)
});
*/
this.confirmed(true);
};
var viewModel = {
user: new UserViewModel()
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="with: user">
<!-- ko ifnot: confirmed -->
<form>
<p>
GitHub Username:
<input data-bind="value: userName" type="text" placeholder="username" />
<button data-bind="click: confirm">Login</button>
</p>
</form>
<!-- /ko -->
<!-- ko if: confirmed -->
<a data-bind="attr: { href: userUrl }">
<img data-bind="attr: {src: avatarUrl }" />
<span data-bind="text: userName"></span>
</a>
<!-- /ko -->
</div>
With help from user3297291's jQuery answer above, I eventually came to this. The answer was good and necessary for this progression; some parts just did not work for this situation (mostly simple compatibility issues with other code not included in this sample). Though this is a very specific question, I thought the solution should be included. Note that I have decided to stay away from Knockout for now.
The HTML suggestion to attach the id to the form rather than the div is a good move.
$("#submitButton").click(function inputForm() {
var username = $("#un").val();
function makeUserContent(user, profile, avatar) { //arguments are data from ajax
//writes a string without the messy quotes within quotes within quotes problem
//much clearer than trying to handle the jQuery and string all at once
return "<img src=" + avatar + " height='30' width='30' />" + user + "";
}
function submitUsername() {
$.ajax({
...
success: function correntInformation(data) {
//data is what the ajax gets, which is passed for use
alert("Welcome, " + username + ".");
//calls to make the string with the data gotten by ajax
var inputContent = $(makeUserContent(data.login, data.html_url, data.avatar_url));
$("#inputSection").replaceWith(inputContent);
}
})
}
submitUsername();
})
The biggest things I took away from this problem is this: simplify strings, hold and use data, work with one library at a time (until experienced with both).
I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO
I have my AJAX form it works great.
Every time I submit the form It returns the result inside the <div id="message"></div>, but it gets complicated when I have multiple forms. So I was wondering if their is a way to indicate inside the form what <div> to return the message to.
Here is my AJAX.js
$("form#ajaxForm").on("submit", function() {
var form = $(this),
url = form.attr("action"),
type = form.attr("method");
data = {};
form.find("[name]").each(function(index, value){
var input = $(this),
name = input.attr("name"),
value = input.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$("#message").html(response); //I would like to interactively switch the return div, from #message to like #message2
$("body, html").animate({
scrollTop: $( $("#message") ).offset().top - 5000
}, 600);
}
});
return false;
});
In the form I would like to indicate where the return div is, like
<form action="../forms/add_event_form.php" method="post" id="ajaxForm">
//Can I add an input somewhere here? To indicate where I want the return to go too? Like <input type="hidden" value="message2" name="return">
<input type="text" class="formI" name="date" id="dateI" placeholder="Date">
<input type="submit" name="submit" class="btn btn-primary" value="Add">
</form>
Thank you for reading this. Have a good day! And Thank you in advance for your responses.
Yes, it will not work automatically, but you can add some information to the form and then use it to decide where to put returned HTML. Doing that with additional inputs may not be the best way though, as it can be achieved with far less impact on the DOM: with an attribute on the form itself.
Here's an example of how you may do that.
$(".ajaxForm").on("submit", function(e) {
e.preventDefault();
var form = $(this);
// using jQuery's `data()` to get an ID of response element from the 'data-response' attribute
var responseElementId = form.data("response");
var response = $(responseElementId);
response.html(produceResponse(form));
// function that produces some html response
// you'll use AJAX request to the server for that
// so don't mind its complexity or bugs
function produceResponse(form) {
var data = form.find("input").map(function(i, el) {
return "'" + el.name + "': " + el.value;
});
return "<p>You've submitted:\n<pre>" + Array.prototype.join.call(data, ",\n") + "</pre></p>";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form #1</h2>
<form action="#" class="ajaxForm" data-response="#response1">
<input name="first-name" type="text">
<button>Submit</button>
</form>
<div id="response1"></div>
<h2>Form #2</h2>
<form action="#" class="ajaxForm" data-response="#response2">
<input name="last-name" type="text">
<button>Submit</button>
</form>
<div id="response2"></div>
Here I use a data attribute because it was designed for cases like this: to store arbitrary data related to the element, but which doesn't have any defined meaning for the browser. Accessing data stored in such way is really convenient with its HTML5 API, but because of pretty low support from IE (it has it only starting from the version 11), one may use jQuery's method data() to do the same.
I have a litte problem with my ajax request and I haven't found a solution yet.
What I am trying to accomplish:
I have simple search form, when I submit I send the data to a PHP file which returns the result as json. Then I add the returned data in a clickable list and when I click on one list item I want to display the data in a new div. This actually works fine. Even if I start a new search I get the correct json objects and the list updates as expected but now I have following problem. If I start a new search without refreshing the whole page and again click on a list item, in the console log i see that the new but also the previous data is still kinda stored in the list or wherever and this is the problem because I then display the wrong data if I click on the list items.
I hope you understand my question and I am thankful for every hint. And btw, is my approach even possible or is there a better way to solve this?
Javascript code
$('#searchbar').submit(function(e){
e.preventDefault();
var query = $('#searchQuery').val();
if (query != ''){
loadData();
}else{
alert('Empty searchform!');
}
});
function loadData(){
var query = $('#searchQuery').val();
$.ajax({
type: "POST",
url: "search.php",
data: {'query': query},
dataType: 'json'
}).done(function(res) {
console.log(res);
resetInfos();
generateList(res);
$('.list-group').on('click', '.list-group-item', function(e){
var index = $(this).index();
console.log(res[index].Name);
$('#locationName').text(res[index].Name);
$('#locationAddress').text(res[index].Zip
+ ' '
+ res[index].State);
$('#locationContact').text(res[index].Internet);
init_map(res[index].Latitude, res[index].Longitude);
});
});
}
function resetInfos(){
$('.list-group').empty();
$('#listItems').remove();
$('#searchQuery').val('');
$('#locationName').text('');
$('#locationAddress').text('');
$('#locationContact').text('');
}
function generateList(result){
$.each(result, function(i){
$('.list-group').append('<li class="list-group-item" id="listItems">'
+ result[i].Name
+ ", "
+ result[i].Zip
+ " "
+ result[i].State);
});
}
HTML search form
<form id="searchbar">
<div class="input-group form-group-lg">
<input type="text" id="searchQuery" name="query" class="form-control" autocomplete="off" placeholder="Name, ZIP, State">
<span class="input-group-btn"><button class="btn btn-success btn-lg" id="searchButton" type="submit">Search</button></span>
</div>
<form>
Ok I solved it. I had to remove the click event handler with
$('.list-group').off('click');
in my resetInfos function.
You are using id selector to remove multiple elements.
$('#listItems').remove();
It will only remove the first matched reference. Please add some class to li element and then use class selector to remove.