HTML submit text used for Javascript query with API - javascript

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>

Related

Javascript dynamic switch doubling Ajax calls

I am having a problem with a jQuery click function. When a user clicks a HTML button, my jQuery dynamically loads some styled checkbox's/toggle switches based upon their corresponding on/off state stored in a database.
I then added a click function to each dynamically loaded toggle switch so that when a user clicks it, it updates the database with the new state, it then, with Ajax, calls the GetAllSwitches function again loading the current state of the switches from the DB back into the resultScreen.
It works, updates the state in the DB correctly, but the program remembers previous 'clicks' and runs them all again followed by the new click state every time a user clicks. So on the first click it makes 1 http request, 2nd 2, 3rd 4, 4th 8 etc. The problem being after a few clicks the ajax calls become huge.
I'm not that experienced in Javascript so I am aware my code is verbose and I am clearly missing something, but are there any fixes or better approaches to this?
In summary what I want to achieve is:
User clicks allSwitches
Ajax call to a database which returns all objects with a toggle switch on screen
Have the toggle switch's clickable which updates the database with new state
Allow the switches to be clicked as many times as the user likes only making one update to the DB
HTML
<fieldset>
<legend> Get All Lights Dynamically</legend>
<input type="button" value="Show All" id="allSwitches"/>
</fieldset>
<fieldset>
<div id='resultScreen'></div>
</fieldset>
JavaScript
$(document).ready(function(){
$("#allSwitches").click(function(){
$.ajax({
url: 'GetAll',
type: 'GET',
dataType: 'text',
success: function(data) {
getAllSwitches(data)
});
});
});
function getAllSwitches(data){
var tr;
myData = $.parseJSON(data);
for(var i = 0; i < myData.length; i++){
tr = $('<tr/>');
if(myData[i].state=="On"){
tr.append('<div id="togs' + i + '">' + '<label class="switch">' +
'<input type="checkbox" class="' + myData[i].lightName +'" checked>' +
'<div class="slider round"></div>'
+'</label>' + '</div>');
tr.append("<td>" + myData[i].lightName +
" is " + myData[i].state + "</td>");
$('#resultScreen').append(tr);
var className = '.' + myData[i]lightName;
var lightName = myData[i].lightName;
var state = "Off";
upTog(className, lightName, state);
} else if (myData[i].state=="Off"){
tr.append('<label class="switch">' +
'<input type="checkbox" class="' + myData[i].lightName +'" >' +
'<div class="slider round"></div>'
+'</label>');
tr.append("<td>" + myData[i].lightName +
" is " + myData[i].state + "</td>");
$('#resultScreen').append(tr);
var className = '.' + myData[i].lightName;
var lightName = myData[i].lightName;
var state = "On";
upTog(className, lightName, state);
}
}
}
function upTog(className, lightName, state){
$(document).on('click', className, function() {
$.ajax({
url: 'UpdateLight?lightName=' + lightName + "&state=" + state,
type: 'POST',
dataType: 'text',
success:function(data){
$.ajax({
url: 'GetAll',
type: 'GET',
dataType: 'text',
success: function(data) {
$('#resultScreen').empty();
getAllSwitches(data);
}});
}
})
});
}
Many thanks.
The easiest way to do it is to unbind the previous click before set the new one.
Change upToge() body like this:
$(className).unbind( "click" );
$(className).on('click', function () {
/* Your ajax call here */
});
You're adding the click handler to the className, which is not changing when you empty the #resultsScreen div. You can see how the handlers pile up in this jsbin: http://jsbin.com/hizigutogi/edit?js,console,output (fill the div, click the red box, empty it, fill it again, and click it a few more times)
Try passing the reference to the jQuery object tr into upTog and adding the click handler onto it directly, instead of attaching it to the class name.

JSON parse will not execute with JavaScript

This is my current code, any help would be greatly appreciated. I need to call my listApp.json file and parse it. I want to display my list which currently has one link. I'm new to this.
<script type = "text/javascript">
// If the .js files are linked correctly, we should see the following output inside the JavaScript Console
console.log("starting...");
// Gets the .json file and applies the function
var json;
// When the document is ready then run the function
$(document).ready(function(){
// Standard jQuery ajax technique to load a .json file
$.ajax({
type: "GET", // Requests data from a specified resource
url: "include/listApp.json", // Gets the file on which the url is directed to
dataType: "json", // Data Type needs to be json in this case. This can be xml
success: jsonParser // If successful then run the, 'jsonParser' function
});
});
// Actual parse function
function jsonParser(data) {
JSON = data;
$(JSON).find("games").each(function (){
games = $(this);
var name = $(games).find("name").text();
var url = $(games).find("url").text();
var id = $(ganes).find("id").text();
console.log(name);
// Appends list + link + name
$("#myList").append('<li>'+ ""+name+""+'</li>');
$('#myList').listview('refresh');
$("#pages").append('<div data-role="page" id = "'+ id +'"><img src = '+ url +'> test</div>');
});
}
</script>
Since data is an object, you can access the games array using data.listApp.games and iterate over it using $.each(), then inside the loop callback you will the game object as second param and you can access its properties using member operator
function jsonParser(data) {
$.each(data.listApp.games, function (i, game) {
var name = game.name;
var url = game.url;
var id = game.id;
console.log(name);
// Appends list + link + name
$("#myList").append('<li>' + "" + name + "" + '</li>');
$('#myList').listview('refresh');
$("#pages").append('<div data-role="page" id = "' + id + '"><img src = ' + url + '> test</div>');
});
}

Retrieving Movies Via Rotten Tomatoes API

I would like to know how to retrieve movies from the Rotten Tomatoes Api using JavaScript/JQuery. I have looked over the documentation and looked at the examples but i am still no wiser as API's are new to me. If someone could give me an example of the following that would be great:
http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=[your_api_key]&limit=1
(I am aware i need to input my api key for it to function)
Thanks
Based on the example API on the Website, I created this sample code for your purpose - Getting Top Box Office Earning Movie. limit=1 will return only the first movie on the sorted list.
To see the entire XML that contains all the JSON key/value you could retrieve, use this link
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
var apikey = "YourApiKeyHERE";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with apikey
var moviesSearchUrl = baseUrl + '/lists/movies/box_office.json?apikey=' + apikey + '&limit=1';
$(document).ready(function() {
// send off the query
$.ajax({
url: moviesSearchUrl,
dataType: "jsonp",
success: searchCallback
});
});
// callback for when we get back the results
function searchCallback(data) {
$(document.body).append('Found ' + data.total + ' results for Top Box Office Earning Movie');
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>
</head>
<body>
</body>
</html>

How to get the value value of a button clicked Javascript or Jquery

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);
}

Make javascript validation happen sooner on click?

So I have a form as such:
<form action="URL" name=myform method=post onsubmit="return validateFormOnSubmit(this)" autocomplete=off>
When the form is submitted, it checks for validation.
Earlier though, I have code like this:
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function() {
var fname = $("input#first_name").val();
var lname = $("input#last_name").val();
var email = $("input#email").val();
var leadsource = $("input#leadsource").val();
var country = $("input#country").val();
var phone = $("input#phone").val();
var oid = $("input#oid").val();
var retURL = $("input#retURL").val();
var crazy
= $("input#00N40000001mCkP").val();
var dataString = '&email=' + email + '&phone=' + phone + '&oid=' + oid + '&retURL=' + retURL + '&leadsource=' + leadsource + '&country=' + country; //alert (dataString);return false; $.ajax({
type: "POST",
url: "MYURL.php?first_name="
+ fname + "&last_name=" + lname,
data: dataString,
success: function(response) { $(myform).submit(); }
});
return false; });
}); </script>
Essentially whats happening is, the form data is initially sent to a different url through an AJAX submit prior to completing the real form. On success of the ajax push - the form is submitted, and then the form is validated.
I need the form validation to have right when #submitbutton is clicked though - prior to the ajax request. Any ideas?
That code should work just fine. If you want to add it to a onclick= property on the element (I wouldn't, but if you insist), you can use this syntax to reference the form:
<input type="submit" onclick="return validateFormOnSubmit(this.parentNode)" />
And you'd have to do an e.preventDefault() and return false (maybe just one?) from the validateFormOnSubmit() function.
Take a look at preventDefault . Also, you can call validateFormOnSubmit in the anon function above and return false if it validation doesn't pass.
you should put some " " around your form tags attributes, and give it an id!
just call your validate function as the first line in your button click handler :)
$("#submitbutton").click(function(e) {
if( validateFormOnSubmit($('#myform'))){
//do all the posting stuff
}
else{
e.preventDefault();
return false;
}

Categories

Resources