I am so confused. I have a form and for now, I send a value into my javascript function. It works with a specific name "bookDate" but whenever I decide to change the name, it gives me an index unidentified error.
HTML FILE:
<input name="submit" type="button" onClick="postBooking('postbooking.php','targetDiv', pickUpDate.value, pickUpTime.value) " value="Book a Cab!">
Javascript:
function postBooking(dataSource, divID, bookingDate, bookingTime) {
if (xhr) {
var place = document.getElementById(divID);
var url = dataSource + "?bookDate=" + bookingDate + "&bookTime=" + bookingTime;
xhr.open("GET", url, true);
PHP:
$pickUpDate = $_GET["bookDate"];
$pickUpTime = $_GET["bookTime"];
echo $pickUpDate." ".$pickUpTime;
In the javascript, when I change "bookDate" into another name (I change the php GET as well to match) it starts to give an index unidentified message when I click my button. It works fine the way it is so I'm so confused why only that name works.
Related
I want to pass a checked value (upon hitting the submit button) to the .js function. The .js function should then take that checked value and query data from a sqlite db and AWS to populate the current webpage.
Here is what I think is happening in the posted code below. After checking a single box and hitting submit, the checked value is being passed to function getQuestionData(). Within getQuestionData(), an endpoint is created using the passed value then function appendInnerHTML is called to populate the page with queried data.
The error I get is
unreachable code after return statement[Learn More]
applied to the 4th line from the bottom ---- q.append('img').
I also noticed that whichever box is checked, my local URL changes. For example, if the box with Coordinate Geometry is checked, the url changes to
http://127.0.0.1:5000/?topic=Coordinate+Geometry
I had some help setting this up so I'm not 100% clear on the fundamentals, if that wasn't already obvious..
CODE
HTML
<form id="checkboxes">
<input type="submit" id="submitTopic" onsubmit="getQuestionData(this.value)">
</form>
.js
function getQuestionData() {
sampleValue = $('input[id=submitTopic]:checked').val()
//document.getElementById("submitTopic").value;
document.getElementById("question").innerHTML = ""
document.getElementById("solve").innerHTML = ""
var endPointQuestionData = '/api/v1/questions/' + sampleValue
Plotly.d3.json(endPointQuestionData, function(error, response) {
if (error) return console.warn(error);
appendInnerHMTL(response)
});
};
//populates webpage with data from sqlite db
function appendInnerHMTL(response) {
d3.select("#solve")
.append('h2')
.text("Solve.")
for (var i = 0; i < response.length; i++){
q = d3.select("#question")
d = q.append('div')
.append('strong')
.text(response[i]['id'])
d.append('div')
button = d.append('input')
.attr('class','button')
.attr('type','button')
.attr('value','Show Answer')
.attr('onclick','showAnswer('+ i + ')')
shownAnswer = d.append('div')
.attr('class','shownAnswer')
.text(response[i]['ans'])
document.getElementsByClassName('shownAnswer')[i].style.display='none';
//appends image from Amazon AWS to each id
q.append('img')
.attr('src', 'https://s3-us-west-1.amazonaws.com/actmath/' + response[i]['date'] + '/' + response[i]['id'] + '.JPG')
//retrieve .jpg file if .JPG file not found
.attr('onerror', 'this.oneerror=null;this.src=\"https://s3-us-west-1.amazonaws.com/actmath/' + response[i]['date'] + '/' + response[i]['id'] + '.jpg\";')
}
};
I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {
Ok so I'm making a video game and I want players to be able to select custom files within the game via a text input box. I was able to get everything to work but when I click the Load Level button it will take me to:
.../Custom Levels/undefined.html
I tried messing around with a few other ways but the only other thing I got was:
.../Custom Levels/[object HTMLInputElement].html
<div>
<p><input type="text" id="LVLNK" value="Level Name"></p>
<p><input type="button" id="MButton" value="Load Level" onclick="LDLVLNK()"></p>
</div>
<script>
var time = setInterval(10,gameLoop)
var LevelLink; /*put: "var LevelLink = document.getElementById("LVLNK");" to get other link example instead*/
function gameLoop()
{
LevelLink = document.getElementById("LVLNK").value;
}
function LDLVLNK()
{
window.location = "../Custom Levels/" + LevelLink + ".html";
}
The file I'm currently trying to access is named "CLevel1"
So I would place CLevel1 in the input box. The gameLoop would set the name toe the LevelLink variable that is then added to the full link in the window.location function located inside of the LDLVLNK function that is activated by the button.
You have the arguments to setInterval() backwards, it should be:
setInterval(gameLoop, 10);
But there's no reason for the LevelLink global variable. You can simply get the input value in LDLVLNK():
function LDLVLNK() {
var LevelLink = document.getElementById("LVLNK").value;
if (LevelLink) {
window.location = "../Custom Levels/" + LevelLink + ".html";
} else {
alert("Nowhere to go to");
}
}
I guess you could try the following :
function LDLVLNK(){
location.href = "../Custom Levels/" + LevelLink + ".html";
//here window is optional, location is a globally accessible object
}
BTW :
You got it wrong with setInterval, you should use setInterval(gameLoop, 10);(even though 10 is probably not very good/maintainable by the browser, try 100 and reduce the amount by a touch if it's too much)
I am a complete novice in jQuery and javascript, so if this sounds very silly or very simple thing to do please help me out with your expertise
$(document).ready(function(){
$('#add_button').click(function(){
var vol = $('input#cv').val();
var col = $('input#cc').val();
var comment = $('input#co').val();
var sample = $('#cv').attr('class');
var url = $('input#cv').attr('title');
if( (vol && col && comment) == ''){
alert('No data to update');
}else{
url = url.concat('volupdate=',vol,'&concupdate=',col,'&commupdate=',comment,'&sample=',sample);
alert(sample + " " + vol + " " + col +" "+ comment +" " + url);
}
});
});
html :
my $correct_vol = qq{<input type="text" name="cv" id="cv" size="6" class="$sample_name" title="/here/is/where/you/are">};
my $correct_conc = qq{<input type="text" name="cc" id="cc" size="6" class="$sample_name" title="/here/is/where/you/are">};
my $comments = qq{<input type="text" name="co" id="co" size="10" class="$sample_name" title="/here/is/where/you/are">};
my $update = q{<input type="submit" value="Update" id="add_button" class="add_now">};
These forms the last four columns in a big table. My question is: How should I return the url in jquery function to my perl?
if I use return url what should I expect ? And how should I handle the values passed from the url in my script? Thanks for your suggestions.
Your javascript code won't connect with your perl code by itself. The connections to perl will happen as it processes the form elements. So your values need to be passed via POST or GET, the same way they would be passed if you were doing this in an HTML + perl only solution.
What you can do in your javascript is to set the value of the form input that you need to pass. That would be accomplished via something like $("#inputElementID").val(url); (assuming that you give the input element an id of inputElementID in the html where you create it.
You could also submit the form through javascript, if it made sense to do so.
As to using return url, that will only end up returning the value of url to the javascript function that calls it (which, in this case, doesn't really exist since this is a document.ready() execution.
I'm currently trying to create a new set of cascading dropdown lists by following this tutorial :
http://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx
problem is it doesnt work and I'm basically illiterate on javascript (currently I dont have the time to sit and learn it), somehow the dropdown lists are not working, only the first one shows the first hierarchy info.
This is what I've done:
First the controller:
Here's the index method:
public ActionResult Index()
{
var list = repo.GetParentEstablishments();
ViewBag.Parent = (new SelectList(list.ToArray(),"EstablishmentId","Name"));
return View();
}
Here's the method that's supposed to return the list of children for the selected father:
[HttpPost]
public ActionResult Children(int parentId)
{
var parents = repo.GetChildrenEstablishments(parentId);
return Json(new SelectList(parents, "EstablishmentId", "Name"));
}
Here's the view for the index method:
#using (Html.BeginForm("Index", "Ticket", FormMethod.Post, new { id = "ParentChildrenFormID", data_childrenListAction = #Url.Action("ChildrenList") }))
{
<fieldset>
<legend> Parent/Children</legend>
#Html.DropDownList("Parents", ViewBag.Parent as SelectList, "Select a Parent", new {id="ParentsID"})
<div id="ChildrenDivId">
<label for="Children">Children </label>
<select id="ChildrenID" name="Children"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script src ="#Url.Content("~/Scripts/parentChildren.js")"></script>
And finally here's the script file:
$(function () {
$('#ChildrenDivId').hide();
$('#SubmitID').hide();
$('#ParentsID').change(function () {
var URL = $('#ParentChildrenFormID').data('childrenListAction');
$.getJSON(URL + '/' + $('#ParentsID').val(), function (data) {
var items = '<option>Select a Children</option>';
$.each(data, function (i, child) {
items += "<option value='" + child.value+ "'>" + child.Name + "</option>";
// state.Value cannot contain ' character. We are OK because state.Value = cnt++;
});
$('#ChildrenID').html(items);
$('#StatesDivID').show();
});
});
$('#ChildrenID').change(function () {
$('#SubmitID').show();
});
});
For what I've managed to understand from the javascript function, the div that has the label and dropdown for the children should appear hidden once the page is loaded and appear once the user selects a parent from the first list, currently this is not happening and instead everything shows up once the page is loaded. Also once I select a parent nothing happens on the second list, I can infer from this that the javascrip file is not being executed on the users browser, why isn't it being executed? what am I doing wrong?
Thank in advance, any help will be appreciated.
You have an error on the following line
items += "<option value='" + child.value + "'>" + child.Name + "</option>";
Which should be:
items += "<option value='" + child.Value + "'>" + child.Text + "</option>";
Since your controller action is returning a SelectList, this class is an IEnumerable<SelectListItem> where SelectListItem has 2 properties called Value and Text.
There's also another issue with your code. You have used the folllowing to construct the url to your controller action:
URL + '/' + $('#ParentsID').val()
which will result in an url of the form:
/SomeController/Children/123
But the action argument of your Children action is called parentId. If you are using the default route setup, only an {id} parameter will be sent as part og of the uri path (that's the default route pattern: {controller}/{action}/{id} and not {controller}/{action}/{parentid}). So you should either change your route setup or pass the parentId parameter like this:
$.getJSON(URL, { parentId: $('#ParentsID').val() }, function (data) {
...
});
Yet another issue with your code is that your Children conrtoller action is decorated with the [HttpPost] attribute but the $.getJSON method sends a GET request. So it won't work. You could use the $.post method instead:
$.post(URL, { parentId: $('#ParentsID').val() }, function (data) {
...
});
Another issue is that you are showing the StatesDivID but your actual div that was hidden is ChildrenDivId. Make sure you are showing the proper element:
$('#ChildrenDivId').show();
Also make sure you have the jQuery script referenced before your parentChildren.js script. Right now you have included your script inside the view but cannot see jQuery being included. Maybe you have it in your _Layout.
I would recommend you using a javascript debugging tool such as FireBug or Chrome developer toolbar to analyze your javascript code.