JQuery Form Submission with enter key AJAX API - javascript

I've tried various solutions, but none are suitable for my particular case!
How can I make it so that when the user presses 'Enter' the form submits & searches.
I also want to try and remove the JavaScript from the HTML document, and move it to the ajax.js document & select it.
I'm unsure of the correct syntax to do so.
I am using rotten tomatoes API with AJAX by the way.
search.php
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="button" id="button" value="Go!" onClick="filmlist(this.form)">
</form>
ajax.js
function filmlist (form) {
$('#films table').empty(); //removes previous search results before adding the new ones.
var apikey = "frceg2d5djxezaedgm3qq94h";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = form.inputbox.value; //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
// receives the results
function searchCallback(data) {
$('#films table').append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$('#films table').append('<tr><td width="70" rowspan="2"><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '."><img class="ajaximage" src="'
+ movie.posters.thumbnail + '" /></a></td><td class="ajaxfilmlisttitle"><h3><a href="' + movie.links.alternate +
'" title="Click here to view film information for ' + movie.title + '.">' + movie.title + '</a></h3>Release year: '
+ movie.year + '</td></tr><tr><td class="ajaxfilmlistinfo">Audience Score: ' + movie.ratings.audience_score +
'%<br>' + 'Cinema Release Date: ' + movie.release_dates.theater +
'<br>Runtime: ' + movie.runtime + ' minutes</td></tr>');
});
}
}

$("form").submit(function(){
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
return false;
});
or you can just return false at the end of your filmlist function.

You can detect an enter keypress in the #inputbox element with the following jQuery code:
$('#inputbox').keyup(function(e)
{
if(e.keyCode == 13)
{
//do your stuff
}
});
You can also use $('#inputbox').change() to directly load movies when the user is typing.
Do not forget that some old or mobile browser do not have JavaScript support. Always build an server side solution as fallback.

Related

Fix Ajax call not binding the result to a HTML id

I am writing some jQuery and Java code that sends an ajax call to my Java backend to do a procedure and then sends the results back to my jQuery. However, when I run a debug I notice that the information is being sent from Java to jQuery successfully, the issue is the jQuery is cutting off the remaing words after the first space. Below is my code and the result.
Jquery:
function fillInGPData() {
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "/ajax/getGPdata",
data : JSON.stringify(""),
success : function(result) {
console.log("Result Selector: " + result);
console.log(result == null);
$.each(result, function(i, obj) {
console.log("Object: " + obj);
console.log("Tier: " + obj.tier);
console.log( "Selname: " + obj.selname);
console.log("Query: " + obj.query);
console.log("Description: " + obj.description);
console.log("Comment: " + obj.comments);
$(".tableBody1").append(
"<tr id=" + obj.selname + ">"
+ "<td class='sm-width-td'>"
+ obj.selname + "</td>" + "</tr>");
});
},
error : function(err) {
console.log(err);
}
});
}
Result:
<tr id="Windows" file="" share=""><td class="sm-width-td">Windows File Share</td></tr>
So its the obj.selname that is giving the issue. For example, if I pass Windows File Server, it will only show Windows for the ID. That where the problem is. I just need help figuring out why that is the case.

One page app doesn't refresh with Ajax and SQL requests (online only)

I'm trying to build a trip organiser. It's a one page app. There are a list of trips, with their activities on one side, and the Google Map on the other side.
Screenshot here : http://hpics.li/fc1b59c
I have two main files : one called app.js, where I trigger events with forms and click on buttons. Then I get or send data to travelAPI.php, where I send and retrieve data from the database.
When I add a trip or an activity; I empty the whole list, then I retrieve all the trips and activities again from the DB.
In my local environment, everything works fine. But when I tried to put it online, it's a mess. SQL requests work fine, but my trips list doesn't update, and I don't understand why. Actually, the list seems to refresh, but with the same results, and without the trip I just added. (But the trip is pushed into the database)
To display the new trip, I need to clear Google Chrome cache.
I tried to analyse this issue with Postman extension, but it seems to come from the client side.
Ajax request:
function insertTrip() {
$.ajax({
url: 'travelAPI.php?call=insertTrip',
type: 'POST',
data: {
cityName: $("input[name=cityName]").val(),
date: $("input[name=date]").val(),
dateUpdatePlace: $.now()
},
success: function() {
initTripList();
}
});
};
initTripList method:
function initTripList() {
$("#tripList").html('');
var listPlace = new Array();
$.ajax({
type: "GET",
url: "travelAPI.php?call=getTrips",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
$("#tripList").append('<div class="trip" data-id="' + data[i].idPlace + '"><div class="headingName"><p class="tripName">' + data[i].namePlace + '</p><img class="editNameAction" src="imgs/edit.png" width="30px" alt="edit"></div><div class="editName" style="display:none"><input type="text" name="tripName" value="Text to edit"><img class="confirmEditName" src="imgs/validate.png" width="30px" alt="valider"></div><p class="tripDate">' + data[i].datePlace + '</p><div class="editDate" style="display:none"><input type="text" name="tripDate" value="Text to edit"><img class="confirmEditDate" src="imgs/validate.png" width="30px" alt="valider"></div><ul><li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li></ul></div>');
} else {
if ($.inArray(data[i].idPlace, listPlace) != -1) {
$('.trip[data-id="' + data[i].idPlace + '"] ul').append('<li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li>');
} else {
$("#tripList").append('<div class="trip" data-id="' + data[i].idPlace + '"><div class="headingName"><p class="tripName">' + data[i].namePlace + '</p><img class="editNameAction" src="imgs/edit.png" width="30px" alt="edit"></div><div class="editName" style="display:none"><input type="text" name="tripName" value="Text to edit"><img class="confirmEditName" src="imgs/validate.png" width="30px" alt="valider"></div><p class="tripDate">' + data[i].datePlace + '</p><div class="editDate" style="display:none"><input type="text" name="tripDate" value="Text to edit"><img class="confirmEditDate" src="imgs/validate.png" width="30px" alt="valider"></div><ul><li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li></ul></div>');
}
}
listPlace.push(data[i].idPlace);
}
}
});
setTimeout(function() {
initTripListSec();
}, 100);
};

HTML submit text used for Javascript query with API

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>

Using slice() to only return the first 5 results

Currently I have a site that when a button is clicked it returns the lastest movies and tv shows that are airing.
Right now the api I am using returns a whole page of values up to 20 results from my research of the api there is no limit function all i want to do is have 5 of those results be returned
I have been told that the slice() function may work.
Also any other why that you think my work would be nice aswell if you can figure out another way
I have included a jsfiddle but removed my api key
jsfiddle - http://jsfiddle.net/xvTe9/
Here's all my code just without my api key
<html>
<head>
<title>Sample Seach</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/now_playing',
input,
movieName,
key = '?api_key=API KEY HERE';
$('#search').click(function() {
var input = $('#titlesearch').val(),
movieName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+movieName' ,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_title + '</h4></td></tr>';
});
$('#searchresult').html(table);
}
});
});
});
// tv show search
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'tv/on_the_air',
input,
tvName,
key = '?api_key=API KEY HERE';
$('#search').click(function() {
var input = $('#titlesearch').val(),
tvName = encodeURI(input);
$.ajax({
url: url + mode + key + '&query='+tvName,
dataType: 'jsonp',
success: function(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_name + '</h4></td></tr>';
});
$('#searchresulttv').html(table);
}
});
});
});
</script>
<script text="text/javascript">
// When the more button is click this runs a search using the title of the movie it is next to
$('.results-img').live('click', '.results-img', function() {
getImdbInfo( $(this).closest('tr').find('.results-title').text());
});
//The function below takes the entered title and searchs imdb for a match then it displays as followed
function getImdbInfo(Title) {
var url = "http://www.omdbapi.com/?t=" + Title + "&plot=full";
$.ajax({
url: url,
cache: false,
dataType: "jsonp",
success: function(data) {
var str = "";
str += "<h2><center>Title :" +data.Title+ "</center></h2>";
str += "<center><img src='" + data.Poster + "' /></center><br />";
str += "<h4><center>Plot :</center></h4><p>" +data.Plot+ "</p>";
$("#chosenresult").html(str);
},
error: function (request, status, error) { alert(status + ", " + error); }
});
}
</script>
</head>
<body>
<center>
<h1>Movie and Tv Search</h1>
<button id="search">Search</button>
</center>
<div id="chosenresult"></div>
<div id="searchresult" style="float:left;"></div>
<div id="searchresulttv" style="float:right;"></div>
</body>
</html>
Screenshot of results that i want just the 5
Use slice to first reduce the array which must be iterated in the callback function of ajax.
var results = data.results.slice(0,5);
$.each(results, function( key, value ) {
table += '<tr><td class="results-img"><img src="http://image.tmdb.org/t/p/w500' + value.poster_path +'" alt="" width="130" height="150"></td><td class="results-title"><h4>' + value.original_name + '</h4></td></tr>';
});
Assuming you've stored the results in an array,
arr.slice(0,5)
will return the first five elements.
Using your current $.each you could do:
$.each(data.results, function (index, value) {
table += '<tr>
<td class="results-img">
<img src="http://image.tmdb.org/t/p/w500' + value.poster_path + '" alt="" width="130" height="150">
</td>
<td class="results-title">
<h4>' + value.original_name + '</h4>
</td>
</tr>';
return (index !== 6);
});

Ajax post not sending data out

var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
I have checked and made sure that dataString was sending out correct stuff, however, the ajax was just not sending out any data, no error whatsoever. Even when I changed the url to an invalid one it still went to my success function.
You should pass data as an object instead of a string when you are sending via POST
Example:
data = {
'edulevel': edulevel,
'course': course
(.....)
};
I have made some changes and now this is working your callback function was success() and jQuery was trying to find the function, either you can write your function at same place or you can write a stand alone function and assign it to sucess:, if you are still getting problem try to change your url, if your current files location is /files/file.php
then your veriamateur.php must be /files/process/veriamateur.php
var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: function(){ alert('success');},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});

Categories

Resources