I am trying to get my search box to work and do a getJSON on text search and title. but in the console log, I get text=undefined?title=undefined. so it is not displaying any JSON. Not sure if my click is working correctly or if I have to make my JSON objects?
Script
<script>
var searchstring = $('input[type="text"]', this).val();
var url = "https://data.edu/api/v1/metadata";
url += "?text=" + searchstring;
url += "?title=" + searchstring;
$(document).ready(function() {
$('button[type="button"]').click(function(event){
$.ajax({
type: "GET",
url: url,
success: function(res){
console.log(res);
var items = res.data.metadata;
var ins = "";
for (var i = 0; i < items.length; i++){
ins += "<div>";
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "Title" + items[i].title;
ins += "</div><br />";
};
$('#results').html(ins);
}
});
});
});
</script>
html
<form class="destinations-form" role="search" >
<div class="input-line">
<input id="searchForm" type="text" class="form-input check-value" placeholder="Search Documents" />
<button type="button" class="form-submit btn btn-special" "</button>
</div>
</form>
<div class="container">
<div class="hero-text align-center">
<div id="results"></div>
</div>
</div>
json
data: [
{
collection_id: "ADGM-1552427432270-483",
metadata:{
year: "2019",
files: text ,
title: text,
},
The problem is because you only read the values from the field when the page first loads and it is empty. To fix this, move that logic inside the click handler.
The next issue is that you should remove this from $('input[type="text"]', this). You don't need a contextual selector here, and this one is incorrect regardless.
Also note that a valid querystring starts with ? and separates each value with &, so your url concatenation needs to be amended slightly. In addition you shouldn't update the url value on every click. If you do it this way your AJAX request will only work once.
Lastly the metadata in your response is an object, not an array. data is the array so you need to loop over that instead. The loop can also be simplified by using map(). Try this:
$(document).ready(function() {
const url = "https://data.edu/api/v1/metadata";
$('button[type="button"]').on('click', function(e) {
let searchstring = $('input[type="text"]').val();
let requestUrl = url + `?text=${searchstring}&title=${searchstring}`;
$.ajax({
type: 'GET',
url: requestUrl,
success: function(res) {
let html = res.data.map(item => `<div>Title ${item.metadata.title}</div><br />`);
$('#results').html(html);
}
});
});
});
Related
I'm working on the wikipedia viewer for free code camp and I'm trying to make the search bar work.
Ideally I would just like to have the user type in some text, then have that become a string in my code when the user hits submit. This is the html for the search bar so far
<form method="get">
<input type="text" placeholder="Search articles" class="srchbox" name="Search" id="searchbar">
<button type="submit" class="btn">Search</button>
</form>
and the api setup I have to make the search
var apiURL = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&generator=search&search=" + textInput;
$(document).ready(function() {
$.ajax({
url: apiURL,
dataType: "jsonp",
success: function(data) {
var wikiAPI = JSON.stringify(data, null, 3);
console.log(wikiAPI);
var wikiHTML = "";
for (i=0; i < data[1].length; i++)
{
wikiHTML += ("<a href =\"" + data[3][i] + "\" target=\"_blank\">")
wikiHTML += "<div class = \"wikicontent container-fluid\" style = \"color:black;\">";
wikiHTML += ("<h2>" + data[1][i] + "</h2>");
wikiHTML += ("<h3>" + data[2][i] + "</h3>");
wikiHTML += "</div></a>"
}
$("#articles").html(wikiHTML);
I'm a bit lost on how to pull this off so any help would be great. Thank you!
You can use submit event, set query to #searchbar .value
$("form").on("submit", function(e) {
e.preventDefault();
if (this.searchbar.value.length) {
var url = "https://en.wikipedia.org/w/api.php?format=json"
+ "&action=opensearch&generator=search&search="
+ this.searchbar.value;
$.ajax({url:url, /* settings */});
}
});
For a project, I am trying to make a HTML form that when a movie is searched it can access the Rotten Tomatoes API and queries the user's submitted text and returns with the movie.
The javascript* code from Rotten Tomatoes was provided
<script>
var apikey = "[apikey]";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with our apikey
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = "Gone With The Wind";
$(document).ready(function() {
// send off the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
});
// callback for when we get back the results
function searchCallback(data) {
$(document.body).append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$(document.body).append('<h1>' + movie.title + '</h1>');
$(document.body).append('<img src="' + movie.posters.thumbnail + '" />');
});
}
</script>
I have an API key, my question is how would I be able to create a form that would change out the value for var query = "Gone With The Wind"; as the user submitted an input search with a HTML form such as this:
<input id="search">
<input type="submit" value="Submit">
Also would this be able to lead to another HTML page once searched?
complete rewrite ...
You should wrap the supplied (and modified) code in a function which you can then call through an event binding, like a submit event on your input form.
Below you will find a complete and working example of how you could do it. I replaced the given URL with a publicly available one from spotify. As a consequence I had to modify the callback function a little bit and also the dataType paramater in the $.ajax() argument object was changed to 'json' (instead of originally: 'jsonp').
At the end of the lookformovie() function you will find return false;. This prevents the submit event from actually happening, so the user stays on the same page.
function lookformovie(ev){ // ev is supplied by the triggered event
console.log('go, look!');
// the following WOULD be important, if this function was triggered
// by a click on a form element and you wanted to avoid the event to
// "bubble up" to higher element layers like the form itself.
// In this particular example it is superfluous
ev.stopPropagation();
var apikey = "[apikey]";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with our apikey
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
// --- start of spotify-fix ---
moviesSearchUrl="https://api.spotify.com/v1/search?type=track";
// --- end of spotify-fix -----
// the following gets the contents of your changed input field:
var query=$('#search').val();
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "json", // spotify-fix, was: "jsonp"
success: searchCallback
});
return false; // this prevents the submit event from leaving or reloading the page!
}
// modified callback (spotify-fix!!):
function searchCallback(data){
console.log('callback here');
$('#out').html(data.tracks.items.map(
function(t){ return t.name;}).join('<br>\n'));
}
// original movie callback for Rotten Tomatoes:
function searchCallback_inactive(data) {var str='';
str+='Found ' + data.total + ' results.';
var movies = data.movies;
$.each(movies, function(index, movie) {
str+='<h1>' + movie.title + '</h1>';
str+='<img src="' + movie.posters.thumbnail + '" />';
});
$('#out').html(str);
}
$(function(){
$('form').on('submit',lookformovie);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search" value="james brown">
<input type="submit" value="get tracks">
</form>
<div id="out"></div>
You might have noticed that I placed several console.log() statements at various places into the code. This helped me during debugging to see which part of the functionality actually worked, and where something got stuck. To see the output you need to have your developer console opened of course.
You can construct form, with input element named "q", then handle form submit event.
<form action="http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=API_KEY" method="get">
<input id="search" name="q">
<input type="submit" value="Submit">
</form>
I've edited this question from the original OP to better represent my issue.
How can I pass the variable data-uid with AJAX ?
Right now the variable doesnt get passed.
var uid = $(this).data("uid"); doesn't work = undefined
var uid = '199'; gets passed. works.
is it possible to have something like : var uid = $uid; ?
HTML
<form>
<fieldset>
<textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
<button type="submit" id="add" value="Update" name="submit" />OK</button>
</fieldset>
</form>
JS
$(function() {
$("#add").click(function() {
var boxval = $("#post_form").val();
var uid = $(this).data("uid"); // this needs to be changed
var dataString = 'post_form=' + boxval + '&uid=' + uid;
if (boxval == '') {
return false;
} else {
$.ajax({
type: "POST",
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
return false;
});
});
problem in your code in:
var uid = $(this).data("uid");
you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it
you shoud use:
var uid = $('#post_form').attr('data-uid');
or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way
Looks like your issue is with the data attribute that should be data-uid="somevalue" Like.
Check this fiddle to see if this solves your main problem
I retrieve from a php file some headline datas (main headlines, each of them has sub headlines).
The data I receive works fine, but when I want to generate a collapsible-set in jquery (mobile), it doesn't show the beautiful theme... just plain text?!
Here's my HTML file:
<div data-role="collapsible-set" data-content-theme="d" id="headlinegroup">
And here's my javascript file:
$.ajax({
type: "POST",
url: "headline_getter.php",
dataType: 'json',
cache: false,
success: function(data1){
console.log ("debug 2");
var i = 0;
var $elements = '';
$.each(data1[i].main, function() {
console.log ("debug 3 ");
$elements += ($('div[data-role=collapsible-set]#headlinegroup').append('<div data-role="collapsible"><h3>' + data1[i].main + '</h3><div data-role="fieldcontain"><fieldset data-role="controlgroup" id="headlinegroup'+[i]+'">'));
var j = 0;
$.each(data1[i].sub, function() {
console.log ("debug 4");
$elements += ('<label><input type="checkbox" name="headlines[]" data-mini="true" value="' + data1[i].mid[j] + '"/>' + data1[i].sub[j] + '</label>');
j++;
});
$elements += ('</fieldset></div></div>');
$elements.collapsible();
i++;
});
}
});
I don't really know where the problem is. I've read some thread here at stackoverflow and added the .collapsible attribut but it don't work... theres just plain text.
Thanks in advance. Best regards, john.
have you tried to add .trigger('create') at the end of every element you append?
I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}