Sinatra: Present Form input without redirecting - javascript

I am trying to make a website, where a user can input some data. I would then run a number of methods on this data using sinatra and then display the results on the same input page (i.e. without refreshing (or redirecting) the page - as such the input data is still the form).
I understand that I would probably have to use javascript to watch the submit button and use that to stop the redirection.
I know ruby quit well, but do not know javascript that well; so please bear with me.
I have done quite a bit of research on this, but I haven't got anything to work. (This question is similar, but I haven't even been able to successfully use that).
This is the my sinatra file. Currently, pressing the submit button redirects to an another page.
require 'sinatra'
get '/' do
erb :search
end
post '/' do
#the_input = "<h2>ID header</h2>#{params[:input]}"
end
__END__
## search
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="/#result" method="post">
<input type="text" name="input">
<input type="submit">
</form>
<div class="result" id="result" style="display: none;">
<div class="content">
<!-- this is where the Results should display... -->
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#result').submit(function(){
//parse AJAX URL
var action = $(this).attr('action');
var index = action.indexOf('#');
var url = action.slice(0, index);
var hash = action.slice(index, action.length);
$('.result').show();
$('.result .content').html(index);
})
})
</script>
</body>
</html>
I would really be grateful if someone could help me to get this to work so that the input of the form is displayed into the content div. Any explanation of what you are doing would also be extremely helpful.
Many Thanks for all your help.

This may help you
Basically prevent default redirecting.

Related

Redirect to a SubDirectory via Form Input in JavaScript

When this project was first started we thought it would be super easy but after two days of failure, we are stumped.
Environment: MacBookPro - WordPress with Thrive Themes Architect
Goal: Create a simple form that allows visitors to input the name of a subdirectory into a form that instantly redirects them to that subdirectory upon clicking on the submit button.
Purpose: When a partner gives out their website URL which includes a subdirectory name sometimes the person fails to put in the subdirectory name and they go to the main site instead. This form would make it easy for them to get to the right place so that the right partner gets proper credit.
Theories: Could the redirect be being blocked by Browser security protocols or something? Is the coding off in some way? Is the method flawed?
Three of Many Failed Coding Attempts:
<script type="text/javascript">
function Redirect(){
var subDirectory= document.getElementById("sub_directory").value;
window.location.href= "https://www.thewatercoach.com/" + subDirectory;
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
Results: The page simply refreshes or reloads the pre-existing URL, but doesn't work at all.
<script type="text/javascript">
function Redirect(){
var subDirectory= document.getElementById("sub_directory").value;
window.location.replace(subDirectory);
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
Results: The page simply refreshes or reloads the pre-existing URL, but doesn't work at all.
<script type="text/javascript">
function Redirect(){
var subLink = document.getElementById("sub_Link");
var subDirectory= document.getElementById("sub_directory").value;
subLink.href = "https://www.theWaterCoach.com/" + subDirectory;
subLink.click();
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
<a id="sub_Link" href="https://www.theWaterCoach.com/">.</a>
Results: This Coding Example did work reliably with FireFox but not on Chrome or Safari. It does not work via Chrome on a PC either. For testing purposes, you can enter Becca into the text box.
Any ideas or solutions will be greatly appreciated!
The submit button is located inside a form tag. Therefore, when you click submit, the browser simply sends a GET request to your homepage. The Javascript code to redirect got executed, but then it is terminated right before the GET request is sent.
Solution: You have to prevent the form from being submitted. Find out how: read this stackoverflow question.

How to get a DIV element from an external webpage in HTML file?

Apologies in advance if this question has been asked earlier. I did find some similar questions on web but I couldn't figure out the answer still. You can say I have never dealt with anything beyond basic HTML. So any help would be appreciated.
I have a HTML file (Say text.html) only for personal use. In the file, there will be an input box for entering text and a submit button. I want that if I clicks on submit, it opens a particular hyperlink from an external webpage based on the input text. I guess it's like "I am feeling Lucky" of Google.
Example: If the user enters "Test" and clicks on Submit, it should open the second result from the page "https://www.google.com/search?q=test"
Here is my HTML:
<!DOCTYPE html>
<html>
<body style="background-color:beige">
<h1 style="text-align:center"><font size="14">Test</font></h1>
<style type="text/css">
</style>
<form id="form">
<div align="center" style="vertical-align:bottom">
<input type="text"
value="Test"
id="input"
style="height:50px;width:200px;font-size:14pt;">
</div>
</form>
<TABLE BORDER="0">
<TD><button class="button" id="button01">SUBMIT</button></TD>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
</script>
Also, here is the example of the div element from the page on which the hyperlink I want to open is on:
<div id="XYZ" class="contentEditValue" style="float:left;width:180px;">
2nd Result
</div>
I have read that it can be achieved with PHP or Jquery and all but they are not something I have ever worked on. Thank you very much in advance for any help!
Appreciate any other alternatives as well.
You shouldn't be able to do that because of security. If that (reading content from iframes, other browser windows...) would be possible, an attacker could add JS keylogger to your internet banking login or read your messages on Facebook. CORS (https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is used to block these requests and if the website doesn't say explicitly that you are allowed to do something with its content, most browsers won't allow you that.
You have are missing a }); to close the ready() function
<script type="text/javascript">
$(document).ready(function(){
$('#button01').click(function(e) {
var inputvalue = $("#input").val();
window.open("https://www.google.com/search?q="+inputvalue);
});
});
</script>
Here's a basic example of how to do this in PHP.
Taking JavaScript/JQuery out of the picture, let's just say you have a basic form:
<form>
<input type="text" value="Test" name="input">
<input type="submit">
</form>
Without specifying action or method attributes on the <form> tag, the form will make an HTTP GET request to the URL of the page it is on, so for this example the PHP code will be on the same page as the form. Here's a more detailed description of sending form data if you're interested.
Now that you have a way to pass the input to the PHP script*, there are three basic parts to this problem.
Make a request to the page you want with a query string including your input
http_build_query is an easy way to construct a properly encoded query string to use with your request. For this example we'll use file_get_contents to make the request. There are other ways to do it, including cURL, but let's keep it simple.
$query = http_build_query(['q' => $_GET['input']]);
$page = file_get_contents('http://www.example.com/?' . $query);
I'm not using Google for this example because it's a bit more complicated to find the right links in the response and follow them. (Partially because they don't really want you to do it that way.)
Find the link you want in the response
Don't try to find the link in the response with regex. You'll have problems with it, come back to Stack Overflow to try to solve them, and people will tell you that you shouldn't be using regex, so just skip that part and use a DOM parser.
$doc = new DomDocument;
$doc->loadHTML($page);
$links = $doc->getElementsByTagName('a');
$url = $links[0]->getAttribute('href');
I used getElementsByTagName() to find links, but if the page is more complex an xpath query will work better. Also, I used the first link ($links[0]) because example.com only has one link. $links[1] would get you the second link if it existed.
Follow the link
header("Location: $url");
exit;
If everything goes well, you'll end up where you want to be. But there are a lot of things that can go wrong. If you're requesting a resource that you have no control over, it can change at any time without any advance warning to you, so your code that finds the link may stop working. You may get blocked from making requests. Scraping links from sites like this violates the terms of service on many sites, so check that out beforehand. You may find that the site offers a web API, which should be a much better way to access its content than this.
*You don't really need a form for this; you can just pass the input parameter in the URL to your page.

Return to the previous page with inputs

Really unsure about the title question. Feel free to suggest. :)
Hi guys! I created a very simple code, that would represent my web.
Here is my home page:
<html>
<script type="text/javascript">
function getPage(linkPage,variables,divName){
$.get(linkPage + "?" + variables,function(data){$(divName).html(data);});
}
function show(){
//functionName("path","data","idName");
getPage("AjaxPages/hi.php","","#container");
}
</script>
<body>
<div id="container">
First Name<input type="text" />
<input type="button" value="next" onClick="show();"/>
</div>
</body>
</html>
Basically, it ask for information, Name for example. When the button NEXT is click it will call a javascript function that will call a certain page or the NEXT PAGE that will load on the div with the Id Container.
NEXT PAGE
On the next page, it will then ask another question, like Last Name for example. But then, I want to go back to the previous page to make same changes.
HERE is the code:
<script type="text/javascript">
function show(){
ajaxgetdata("index.php","","#container1");
}
</script>
<div id="container">
Last Name<input type="text" />
what to make changes on the previous page?<input type="button" value="back" onClick="show();"/>
</div>
When button back is clicked, it will just call the previous page, but will not include the text that you input on the textbox.
I know that it happens because it just call the page..
Is there a way? that when back button is clicked, it will reload the previous page, with all the contents/inputs.
:) :( :'( :/ :|
Don't load any additional pages. Do everything with AJAX.
If you don't want, some server-side script may help :D
If you can use HTML5 in your site, you can take a look at the History API which can handle navigation and fires a "popstate" event, to which you can pass data.
There's a good example here:
http://diveintohtml5.info/history.html
You could do something like this:
window.addEventListener("popstate", function(e) {
if(!e.state || !e.state.firstName) {
return;
}
document.getElementById('firstName').value = e.state.firstName;
});
That even will trigger everytime you go back or forward, and you could just organize some function or array with the information you need.
Hope it helps.

Need help getting the name of a included jsp page in javascript

I have this code for a .jsp page:
<f:view>
<div class="portletBody">
<h:form id="editSectionForm" onsubmit="return numCheck(document.forms[0].elements['editSectionForm:sectionTable:0:maxEnrollmentInput'].id)">
<sakai:flowState bean="#{editSectionBean}"/>
<t:aliasBean alias="#{viewName}" value="editSection">
<%# include file="/inc/navMenu.jspf"%>
</t:aliasBean>
<h3><h:outputText value="#{msgs.edit_section_page_header}"/></h3>
<%# include file="/inc/globalMessages.jspf"%>
<t:aliasBean alias="#{bean}" value="#{editSectionBean}">
<%# include file="/inc/sectionEditor.jspf"%>
</t:aliasBean>
<t:div styleClass="act">
<h:commandButton
action="#{editSectionBean.update}"
value="#{msgs.update}"
styleClass="active"
onclick="reEnableLimits();" />
<h:commandButton action="overview" value="#{msgs.cancel}" immediate="true" />
</t:div>
</h:form>
</div>
</f:view>
and I have some javascript code that runs in the /inc/sectionEditor.jspf file. In some of that code in the sectionEdtior file, I need to somehow grab the id of this form. editSectionForm. I can't hard code it because the /inc/sectionEditor.jspf code runs in more than one page.
So pretty much, I need the javascript code in /inc/sectionEditor.jspf to be able to grab the id of the form it is currently in.
i.e:
If I'm in the editSectionForm page, it'll tell me that im in that page, if I'm in addSection Form page, it'll tell me that I'm on that page.
I'm not sure I fully understand the question. Are you trying to get the current page you are in, as in the url?
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
Or do you have multiple forms on the same page?
I actually figured out another way for my situation. For anyone that's ever used Sakai, they know the beast that it is.
I see you already use document.forms[0] in your jsp page, so, making assumption there is one form only, you may use the same construction inside a script section of your 'subpages' also, i.e. using document.forms[0].id will give you the id of the form.
<!DOCTYPE html>
<html>
<body>
<form id="editSectionForm">
<div id="sectionEditor">
<script type="text/javascript">
var formId = document.forms[0].id;
console.log(formId);
</script>
</div>
</form>
</body>
</html>

jquery form submit

I have a jquery fancyzoom box. In that box ,I have a contact form which sends an email on submission. But I am not able to call form submit function due to fancyzoom.
Code is like :
("req_quote.php")
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/fancyzoom.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#popup1_link').fancyZoom({width:610});
$("#submit").css('cursor', 'pointer');
$('.reqfrm').submit( function(){
alert("hell");
});
});
</script>
<body>
<form class="reqfrm" id="frm">
<input type="text" name="name" />
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Above file is included in "index.php" which contains the actual link to open the form in fancyzoom box.
(index.php)
< a href="#popup1" id="popup1_link">< div class="blink">Request a Quote< /a>"
If I remove $('#popup1_link').fancyZoom({width:610}); then i get alert on submission otherwise it goes on form action directly.
Are you getting any JavaScript errors with the fancyZoom call in? Are you including the script file you need to use it? It's hard to say without seeing some more data, or a jsbin / jsfiddle.
The form is submitted in the fancybox js file.
As mentioned by Raul, you need to provide more info for us to help out. You could try any of these things:
See if you can reproduce this issue within a simple html file, that doesn't have any of the extra stuff that your current page may have. If the issue still persists, put it into jsFiddle and post the link here.
If you haven't already, install the Firebug addon for Firefox, and use it's console to check for any JS errors.
Have a look at the jsFiddle that I've created. Is this similar to what you are doing? Mine works wihtout any issues.

Categories