Does anybody have any idea why this is not allowing the form to submit? I'm attempting to use Rotten Tomatoes API with a user search function.
FORM IN PHP PAGE
<form name="myform" action="" method="GET"><h3>Search for a movie here:</h3><br>
<input type="text" id="inputbox" value="">
<input type="submit" name="submit" value="Go!">
JAVASCRIPT
$('form[name="myform"]').submit(function() {
$('#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 // if successful, run searchCallback function
});
// 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>');
});
};
});
I tested with this code and it works:
<form name="myform" action="" method="GET">
<h3>Search for a movie here:</h3>
<input type="text" id="inputbox" value="" />
<input type="submit" name="submit" value="Go!" />
</form>
<script>
$(function(){
$('form[name="myform"]').on('submit', function(e) {
e.preventDefault();
$('#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 = $('#inputbox').val(); //uses the value from the input box as the query search
// sends the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback // if successful, run searchCallback function
});
// 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>');
});
};
});
});
</script>
There were a couple of problems:
The form.inputbox.value did not work, change it to $('#inputbox').val()
Add e.preventDefault() to prevent the from from being submitted
There was a missing });
Change $('form[name="myform"]').submit(function() { to $('form[name="myform"]').on('submit', function(e) {
Related
I'm trying to retrieve multiple data from my remote php file and display them dynamically, i usually do this with jquery when i'm coding cordova. i'm using nativescript now.
This is the jquery code i use before
$.getJSON(serviceURL + 'getroutes.php?station='+station, function(data) {
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li>'+
'<img src="js/citybus.png" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + '</p>' +
'<p class="line2">' + difference + ' Out' + '</p>' +
'<p class="line3" style="color:'+ color +';margin-left:60px">' + SeatsLeft + ' seats left </p>' +
'<button style="display:'+ display +'" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '<center><img src="js/seat.jpg" style="height:15px;width:15px;"/></center>' + '</button>'
+ '<button data-id="' + employee.id + '" data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '<center><img src="js/bell.png" style="height:15px;width:15px;"/></center>' + '</button></li>');
if(index && index % 4 === 0) {
$('#employeeList').append('<center><div class="adSpace2" style="margin-top:2.5px;margin-bottom:2.5px;">'+'</div></center>');
}
});
setTimeout(function(){
scroll.refresh();
});
});
Please how do i do this with nativescript?
You'll want to use the Fetch API.
const Observable = require('tns-core-modules/data/observable').Observable
const model = new Observable()
function loaded(args) {
args.object.bindingContext = model
fetch(serviceURL + 'getroutes.php?station='+station).then(res => model.set('employees', res.items))
}
exports.loaded = loaded
And then in your View XML:
<Page xmlns="http://www.nativescript.org/tns.xsd" xmlns:lv="nativescript-ui-listview" aloaded="loaded">
<StackLayout>
<ListView items="{{employees}}">
<Label class="line1" text="{{firstName}}" />
</ListView>
</StackLayout>
</Page>
I am a final year student and am creating a food log web application for my major project. I have created a search function that allows me to search and display external API results, but now I wish to display them in a table, can anyone help please?
I would prefer if it would be a table that can be filtered, eg, the columns ordered ascending/descending?
Thanks
function get foodItem(userInput) {
var storedSearchItem;
$('.resultContainer').html('');
$.ajax({
type: 'GET',
async: false,
url: 'https://api.nutritionix.com/v1_1/search/'+userInput+'?'+
'fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=325062a4&appKey=bf1a30b2066602dc6f33db888cd53bd3',
success: function(d) {
storedSearchItem = d.hits;
}
});
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}//ends get result function
function searchValue() {
var formVal = document.getElementById('itemSearch').value; //value from search bar
getFoodItem(formVal);
}
$('#searchForm').submit(function(e) {
e.preventDefault();
});`
You need to append your table in the success function
your code will look like something like this
success: function(d) {
storedSearchItem = d.hits;
storedSearchItem.map(function(item) {
var x = item.fields
$('.resultContainer').append(
'<div class="itemBar">'+
'<h2>' + x.item_name + '<h2>' +
'<h3>Calories: ' + x.nf_calories + '<h3>' +
'<h3>Serving Size: ' + x.nf_serving_size_qty + ' ' + x.nf_serving_size_unit +'<h3>' +
'<h3>Total Fat: ' + x.nf_total_fat + '<h3>' +
'</div>'
);
});
}
I have a fullcalendar calendar where the click-events having sweet-alert 2 popups in the functions. The pop up boxes have multiple drop downs that are built using sweet-alert HTML functionality. Here's an example of the code,
eventClick: function (calEvent, jsEvent, view, date) {
var clickValue = calEvent.description;
if (clickValue != 'OWEDVALUE') {
var btn = "button";
drop = drop.replace("select-style-purple", "select-style-green");
options = options.replace("select-style-purple", "select-style-green");
var title = calEvent.title.replace("\n", "<br />");
swal({
title: moment(calEvent.start).format("MM/DD/YYYY"),
type: 'info',
inputClass: 'select-style-green',
inputValue: calEvent.teachNum,
html: title + '<br />' +
'Notes: ' + calEvent.description + '<br /><br />Select A New Teacher: <br /><br />' + options + '<p></p>Select A New Service: <br /><br />' + drop +
'<br /><br /><div style="border:2px solid green;" >Update Hours: ' +
'<input type="text" autofocus id="newHours" style="display:block !important;" class="sweet-alert-input"/>' +
'<input type="hidden" id="oldHours" value="' + calEvent.hours + '" /></div>' +
'<button type="' + btn + '" id="btnA" value="' + calEvent.id + '" style="background-color: #D46752 !important;" class="sweet-alert2-button">Delete Record</button> ' +
'<button type="' + btn + '" id="btnB" value="' + calEvent.id + '" class="sweet-alert2-button">Update Record</button> ' +
'<button type="' + btn + '" id="btnC" style="background-color: #B9B9B9 !important;" class="sweet-alert2-button">Cancel</button>',
showConfirmButton: false
});
$(this).css('border-color', 'red');
}
This is an example of one of the drop down boxes built in a javascript var.
options = '<select id="teacherDrop" class="select-style-green">';
for (var i = 0; i < record_array.length; i++) {
options += '<option value="' + record_array[i].teachNum + '" ';
if (record_array[i].teachName == data[0].teacher)
options = options + ' selected="selected" >' + record_array[i].teachName + 'TEST</option>';
else
options = options + '>' + record_array[i].teachName + 'TEST</option>';
}options += '</select>';
What I would like to do is to rebuild the drop downs(updating the selected value) after every click-event ajax call, so I need to rebuild the actual eventClick functions not the eventSources. I have tried multiple things to no avail.
Here is the function that gets called when one of the submit buttons gets pressed from the Sweet-Alert.
$(document).on('click', "#btnB", function () {
if ($.isNumeric($("#newHours").val())) {
var qString;
qString = "id=" + this.value;
qString += "&teacherId=" + $("#teacherDrop").val();
qString += "&hours=" + $("#newHours").val();
qString += "&service=" + $("#serviceDrop").val();
$.ajax({
type: "POST",
url: "_data_ManageHomebound_Students.aspx?qt=updateStudentRecord",
data: qString,
async: false,
success: function (data) {
data = JSON.parse(data);
swal.close();
$('#calendar').fullCalendar('removeEvents', data[0].id);
$("#calendar").fullCalendar('renderEvent', {
title: "Service Type: " + data[0].serviceType + "\nTeacher: " + data[0].teacher + "\nHours: " + $("#newHours").val(),
id: data[0].id,
start: data[0].start,
end: data[0].start,
allDay: data[0].allDay,
description: data[0].description,
teacher: data[0].teacher,
homeBoundPaidID: data[0].homeBoundPaidID,
teachNum: data[0].teachNum,
serviceType: data[0].serviceType,
color: 'green',
textColor: 'black'
}, false);
$('#ant').addClass('animated zoomInDown').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
$(this).removeClass('animated zoomInDown');
});
//Here I'm going to rebuild the service type drop down and try to recreate all click events.
var options;
options = '<select id="teacherDrop" class="select-style-green">';
for (var i = 0; i < record_array.length; i++) {
options += '<option value="' + record_array[i].teachNum + '" ';
if (record_array[i].teachName == data[0].teacher)
options = options + ' selected="selected" >' + record_array[i].teachName + 'REBUILT</option>';
else
options = options + '>' + record_array[i].teachName + 'REBUILT</option>';
}
options += '</select>';
var temp = $("#hoursGiven").val();
if ($("#newHours").val() >= $("#oldHours").val()) {
temp = parseFloat(temp) + (parseFloat($("#newHours").val()) - parseFloat($("#oldHours").val()));
} else {
temp = parseFloat(temp) - (parseFloat($("#oldHours").val()) - parseFloat($("#newHours").val()));
}
$("#hoursGiven").val("");
$("#hoursGiven").val(temp);
$("#hoursOwed").val(parseFloat($("#totHoursNeeded").val()) - parseFloat(temp))
}
});
} else {
sweetAlert({
title: "Oops!",
text: "Please Make Sure Pay Rate is Numeric. \nPlease fix form and try again.",
type: "error"
});
return false;
}
});
So after the Ajax is successful I rebuild the options var that holds the drop down information for Sweet-Alert. This is the point where I need all of the click-events to be rebuilt to use the updated code(options var). The purpose of this is I'm trying to get the drop downs to have a pre-selected value of the most recently used item(teacher, etc...).
I am trying to reload data every 5 seconds using jQuery. The URL for the JSON data can be found at http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json
This is the code I am trying:
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
One way to do it might look like this:
function getJson () {
$.getJSON("http://gdx.mlb.com/components/game/win/year_2015/month_11/day_11/master_scoreboard.json", function (json) {
$.each(json.data.games.game, function (i, value) {
$('#LMP').append('<div id="equipo"><div class="p1"><img src="img/lmp/' + value.away_name_abbrev + '.png' + '" alt=""></div><div class="p2"><div class="p2-1"> </div><div class="p2-2">' + value.status.inning + ' ' + value.status.top_inning + '</div><div class="clear"></div></div><div class="p3"><img src="img/lmp/' + value.home_name_abbrev + '.png' + '" alt=""></div><div class="clear"></div></div>');
});
});
}
var i = setInteval(getJson, 5000);
I'm trying to call a JavaScript function and then pass the value of the button clicked to that function but even though the function does exist its saying it doesn't and im not sure why. Basically I need to call the powerOn() function when the power on button is clicked and then return the status messages. All I need to know is why it won't call the function so I can make sure I get the basic response.
Also I'm not entirely sure why sortable returns a console error when im following the documentation on http://github.hubspot.com/sortable/api/options/:
ReferenceError: Sortable is not defined vmstatus:123
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5375
TypeError: powerOn is not a function
Code:
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#table-repeat-data').remove();
setInterval(update, 1000);
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
$('#table_name').append("<table class='table' id='table-repeat-data' data-sortable><thead><tr><th align='center' data-toggle='tooltip' data-placement='left' title=''> <b>VM Name</b></th><th align='center' data-toggle='tooltip' data-placement='left' title=''><b>PowerState </b> </th><th align='center' data-toggle='tooltip' data-placement='left' title='N'><b>Commands </b></th></tr></thead><tbody>");
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + on + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}else{
$('#table-repeat-data').append ('<tr><td id="' + json.vmlist[index][0] + '">' + json.vmlist[index][0] + '</td><td id="' + json.vmlist[index][2] + '1">' + off + '</td><td id="' + json.vmlist[index][2] + '">' + powerOn + ' ' + powerOff + ' ' + resetVM + '</td></tr>');
}
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
function update(){
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_customer : $("#selected_customer").val(),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
var on = '<img src={% static "icons/on2.jpg" %}>'
var off = '<img src={% static "icons/off.jpg" %}>'
for (var index = 0; index < json.vmlist.length; index++) {
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
var powerOff = '<button type="button" name="PowerOff" id="powerOff" class="btn btn-danger" value="' + json.vmlist[index][2] + '">Power Off</button>';
var resetVM = '<button type="button" name="ResetVM" id="ResetVM" class="btn btn-warning" value="' + json.vmlist[index][2] + '">ResetVM</button>';
if(json.vmlist[index][1] == 'poweredOn'){
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = on;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}else{
var get_element_id = json.vmlist[index][2] + '1';
document.getElementById(json.vmlist[index][0]).innerHTML = json.vmlist[index][0];
document.getElementById(get_element_id).innerHTML = off;
document.getElementById(json.vmlist[index][2]).innerHTML = powerOn + ' ' + powerOff + ' ' + resetVM;
}
}
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
function powerOn() {
console.log('powerOn');
console.log(this.val());
$.ajax({
url : "/vmstatus/",
type : "POST",
dataType: "json",
data : {
selected_vm : $(this).val(),
username : '{{user_name}}',
ip_address: '{{ip}}',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
console.log(json.server_response);
},
error : function(xhr,errmsg,err) {
console.log('Bad');
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
Sortable.init();
var dataTable;
dataTable = document.querySelector('#table-repeat-data');
Sortable.initTable(dataTable);
</script>
Try changing the name of your function, or changing the name of your variable of the same name. It's possible that it is getting confused as to which one you actually mean due to scope.
var powerOn = '<button type="button" name="PowerOn" id="powerOn" onClick="powerOn()" class="btn btn-primary" value="' + json.vmlist[index][2] + '">Power On</button>';
function powerOn() {...}
which one is powerOn? They both are. It's possible that your function is later overridden to a string value and then it is no longer valid to try and call it like it was a function.