Modifying HTML form action with jQuery/Javascript - javascript

I am trying to create a post form in HTML using a RESTful express route, something akin to /game/:gameID/node/:nodeRow/:nodeCol/update to update a given node in a given game.
Here's the route code:
app.post("/game/:gameID/node/:nodeRow/:nodeCol/update", function(request, response) {
gameHandler.updateNode(request, response)
});
The reason I'm doing this in HTML is because I haven't created the functionality yet in the actual client (mobile game) so I need something to test it. However, I have not figured out how to make the HTML form so that I can enter the data in the form to replace :gameID, :nodeRow, and :nodeCol without just going to the URL manually, like /game/3/node/2/5/update.
This is a post request and I would like other data to be contained in the form to specify the property to update as well as the new value.
How can I do this, or am I thinking about it wrong?
Edit:
Changed the question title to be more useful.

Try
app.post("/game/:gameID/node/:nodeRow/:nodeCol/update", function(request, response) {
console.log({gameID: request.params.gameID, nodeRow: request.params.nodeRow,nodeCol: request.params.nodeCol, body: request.body});
response.send({gameID: request.params.gameID, nodeRow: request.params.nodeRow,nodeCol: request.params.nodeCol, body: request.body});
});
Sorry I misunderstood your question. I thought you are having difficulties in parsing node parameters in node.
Anyway, there are different ways you can achieve this. Of course you need support of javascript, either pure javascript or jQuery.
Here is an example
<form id="myform">
<input name="gameID" id="gameID" />
<input name="nodeRow" id="nodeRow" />
<input name="nodeCol" id="nodeCol" />
<button name="action" value="bar" onclick="submitForm();">Go</button>
</form>
and javascript (using jQuery) will be
<javascript>
function submitForm(){
$("#myform").attr('action',
'/game/' + $("#gameID").val() + '/node/' + $("#nodeRow").val()
+ '/' + $("nodeCol").val() + '/update');
$("#myform").submit();
}
</javascript>

The way to pass data in a POST request is to push it from the html form controls and retrieve the values from the body of the request. The HTML below defines a form with your variables which you can hand-key from a browser:
<html><body>
<form method="post" action="/game/update" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">gameID</span>
<input type="text" class="form-control" name="gameID" placeholder="<gameID>" value="123456">
</div>
</div>
<div class="input-group">
<span class="input-group-addon">nodeRow</span>
<input type="text" class="form-control" name="nodeRow" placeholder="<nodeRow>" value="1">
</div>
</div>
<div class="input-group">
<span class="input-group-addon">nodeCol</span>
<input type="text" class="form-control" name="nodeCol" placeholder="<gameID" value="1">
</div>
</div>
<hr>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</body></html>
Then you can write a handler along the lines of what's below. Clicking submit will fire the POST request off, and pulling the variables out of the request body can be done as shown below.
app.post("/game/update", function(request, response) {
updateNodeHandler(request, response)
});
function updateNodeHandler(request, response) {
var nodeID = request.body.nodeID;
var nodeRow = request.body.nodeRow;
var nodeCol = request.body.nodeCol;
// Additional logic goes here...
}

Related

Scraping data from input value

there is website which has:
<html>
<body>
<form action="/action_page.php">
First name: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="John"></strong></div>
Last name: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="Miller"></strong></div>
Email: <div class="col-md-8 col-sm-8 col-xs-6"><strong><input type="text" class="no-style" value="j.miller#gmail.com"></strong></div>
<input type="submit" value="Send">
</form>
</body>
</html>
Is it possible to scrape data from input value (John, Miller, j.miller#gmail.com) and show it in my page (maybe putting that site into iframe and scrape from it?) or maybe using something like:
// Get HTML from page
$.get( 'http://example.com/', function( html ) {
// Loop through elements you want to scrape content from
$(html).find("ul").find("li").each( function(){
var text = $(this).text();
// Do something with content
} )
} );
I don't know. I am not good with javascript. And there is bonus: input values on every refresh are different. Can I extract somehow data from 100 refresh or something? Thank you for any help!
i will assume that you need to get the data from the input element and then use it somewhere else in your site
you could easily do so using the jquery .val() function
here is some sample code
<form id="my-form">
name: <input type="text" id='test-input'/>
<input type="submit" />
</form>
<script>
var input;
$('#my-form').on('submit', function() {
input = $('#test-input').val();
});
</script>
you could then use the variable anyway you want, whether it is to cache data or for improving user experience
Get the value and var _value = $('#elementId').val(); and use it anywhere on the page $('#elementID').val(_value); or $('selector').text(_value);

How To use Query string in java script?

I have Created calculator project. I have only two pages. Now my question how to pass input field value to another page? trying too many ways its Not Working.
What to do to pass input fields values from one page to another page?
My input fields code Looks Like
<p class="pull-right">DPA Minimum Buyer Contribution<br /></p>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6" style="padding-right:1%">
<input type="text" id="txtLocationContactName5" class="txt"/>
</div>
<div class="col-md-3" style="padding-left:0%">
Another page name default_results.php I have created input fields
<div class="col-md-5 padding-rht">
Minimum Buyer Contribution
</div>
<div class="col-md-2 padding-Zero">
<input type="text" id="txtCustomerName3" class="txt" />
</div>
I have tired in jQuery script
<script>
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "default_results.php?id=" + encodeURIComponent($("#txtLocationContactName5").val()) + "&technology=" + encodeURIComponent($("#txtCustomerName3").val());
window.location.href = url;
});
});
</script
but Not working so how to pass value one page to other page ?
You're making life hard for yourself! A simple form is needed to help you pass data to another page :). See here for info on html Forms - http://www.w3schools.com/html/html_forms.asp
Here is a simple example for you:
<form action="page_2_link" method="POST">
<input type="text" name="field1" value="easy">
<input type="submit" name="button1" value="Submit">
</form>
Then on the second page you can do this to retrieve the form data:
<?php
$blah = $_POST['field1']; // this now has the posted fields value
?>
I have given the second page answer in PHP as you have used this as a tag for this question, so I hope you are using this or my answer won't work.

On submit, remote call php - why aren't $_POST values being posted?

So, I'm a bit in unfamiliar territory with json and remote calls but the url and datatype is correct and... it is clearly arriving at target. BUT.!
It's a very simple form with 3 visible and 2 hidden fields.
<form id="subChange" action="#" method="POST">
<div style="clear:both;">first name</div>
<div>
<input id="fart" type="text" style="margin:4px;width:90%;" name="newFirst" value="" data-validetta="required,characters,remote[check_update]">
</div> last name<BR>
<div>
<input type="text" style="margin:4px;width:90%;" name="newLast" value="" data-validetta="required,characters,remote[check_update]">
</div> eMail<BR>
<div>
<input type="hidden" name="oldName" value="Conor" data-validetta="remote[check_update]">
</div>
<div>
<input type="hidden" name="oldEmail" value="cburkeg#gmail.com" data-validetta="remote[check_update]">
</div>
<div>
<input type="text" style="margin:4px;width:90%;" name="newEmail" value="" data-validetta="required,email,remote[check_update]">
</div>
<div style="margin-top:12px">
<input type="submit" name="sub_change" value="change it" data-validetta="remote[check_update]">
</div>
</form>
Here is the js
<script type="text/javascript">
$(function(){
$("#subChange").validetta({
realTime : true,
bubbleLoc:"right",
onValid : function( event ){
event.preventDefault();
$("#changeDIV").html("thanks Conor <P>Your subscription has been updated");
},
remote : { check_update : { type : "POST", url : "checkNewsUpdate.php", datatype : "json" }}
});
})
</script>
With fields filled we test Submit; name='sub_change' value='change it'
if (isset($_POST['sub_change'])) {
$count = count($_POST);
$postdata = file_get_contents("php://input"); //... write to file, etc.
}
output -
$count: 1
$postdata: sub_change=change+it
What happened to the other fields?
My only current working solution is to set each field with the remote call and set a $_POST validation (done auto., in real time) for each input which writes to a remote file. On submit we then call the contents of that file. Only trouble is it misses the 2 hidden files - there is no auto trigger :(
This is a clumsy work-around (that doesn't even work).
I thought about setting the hidden fields as an ID but getting the value with PHP is a trial. There must be something real simple I am missing here.

Angular form submitting twice (ajax get request)

I have a controller that for some reason is submitting a form twice via a get request in AngularJs. I can see in my database that the form is being submitted twice, and also in the console network tab, it is logging the two submission, however, the first submission has the "Request Method" of OPTIONS, and the 2nd is GET. I think this may be a clue. I'm a bit confused, because i'm not passing in any 'options' into the get method, just the URL I am submitting to.
Html:
<div class="row">
<div ng-controller="groupEditCtrl">
<form class="span11" name="" novalidate ng-submit="createArtifact()">
<legend>Create a new group</legend>
<div class="row">
<div class="span5">
<div class="control-group">
<div class="controls">
<input name="text" type="text" placeholder="Group Name" required ng-model="artifact.group_name" />
</div>
</div>
</div>
<div class="span5">
<p>
<small>What your artifact will look like:</small><br />
{{artifact.group_name}}
</p>
</div>
</div>
<input name="token" type="hidden" required ng-model="window.token" />
<div class="control-group">
<div class="controls controls-row">
<button type="submit" class="btn" value="Submit" title="Submit">
<span>Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
Controller:
'use strict';
function groupEditCtrl($scope, $http, $routeParams, $cookie) {
$scope.createArtifact = function(){
var requestURL = window.base_url + "/Group/CreateGroup?callback=JSON_CALLBACK&token=" + window.token + "&group_name=" + $scope.artifact.group_name;
$http.get( requestURL ).
success(function(data, status, headers, config) {
console.log('You have successfully submitted a Cause/CreateCause');
}).
error(function(data,status,headers,config){
console.log('You have FAILED submitting a Cause/CreateCause');
});
}
};
A HTTP Options request is asking the server for the allowed methods that it can communicate with the server upon (amongst other things) so it's a normal thing to happen.
The Options request shouldn't change anything in your backend but it may well be logged as you're seeing. Double check that it isn't changing anything (and if it is then your backend may be configured wrong, and you should ask another question if it is!).
There's nothing wrong with your angular setup/use regarding the OPTIONS then GET.
For me headers: {'Content-Type': undefined} Work, And I don't see it call twice again.
$http.post("index.php", {id : $scope.A},{
headers: {'Content-Type': undefined}})
.success(function (response) {
$scope.OK = response.POLL;
}
}
Turns out this was an issue with the custom api being built that I wasn't aware of.

jQuery autocomplete for innerHTML generated textbox

I realize similar questions have been asked thousands times and yet it doesn't seem to work for me. I have a textbox called "movieTitle", it is generated via Javascript by clicking a button. And I'm calling jQueryUI autocomplete on that textbox just like in the official example http://jqueryui.com/autocomplete/#remote.
It works well if I hardcode "movieTitle" in the original page; however it just fails when I create "movieTitle" by changing the innerHTML of the div "formsArea". searchMovies.php is the same with search.php from the example. I had tried many answers from internet and from here. I learned that I would have to use .on() to bind the dynamic element "movieTitle". Still it doesn't seem to work. Even the alert("hahaha") works. Thanks for your time. :) Here's my script:
$(function()
{
$(document).on('focus', '#movieTitle', function(){
//alert("hahaha");
$("#movieTitle").autocomplete({
source: "../searchMovies.php",
minLength: 2
});
}
);
window.onload = main;
function main()
{
document.getElementById("movieQuery").onclick = function(){showForms(this.value);};
document.getElementById("oscarQuery").onclick = function(){showForms(this.value);};
// displays query forms based on user choice of radio buttons
function showForms(str)
{
var heredoc = "";
if (str === "movie")
{
heredoc = '\
<h1>Movie Query</h1>\
<form action="processQuery.php" method="get">\
<div class="ui-widget">\
<label for="movieTitle"><strong>Name: </strong></label>\
<input type="text" id="movieTitle" name="movieTitle" />\
<input type="submit" name="submitMovie" value="Submit" />\
</div>\
</form>';
//document.getElementById("formsArea").innerHTML = heredoc;
//$("#formsArea").append(heredoc);
$("#formsArea").html(heredoc);
}
else if (str === "oscar")
{
heredoc = '\
<h1>Oscar Query</h1>\
<form action="processQuery.php" method="get">\
<strong>Name: </strong>\
<input type="text" name="oscarTitle" />\
<input type="submit" name="submitOscar" value="Submit"/>\
</form>';
document.getElementById("formsArea").innerHTML = heredoc;
}
}
}
});
The HTML is:
<form action=$scriptName method="get">
<label for="movieQuery"><input type="radio" name="query" id="movieQuery" value="movie" />Movie Query</label>
<label for="oscarQuery"><input type="radio" name="query" id="oscarQuery" value="oscar" />Oscar Query</label>
</form>
<div id="formsArea">
<b>Please choose a query.</b>
</div>
You should check for the URL you're sending an AJAX request to. The paths in script files are relative to the page they're being displayed in. So albeit your script is in /web/scripts/javascripts/js.js, when this file is included in /web/scripts/page.php, the path to /web/scripts/searchMovies.php should be searchMovies.php instead of ../searchMovies.php because your script is being used in /web/scripts/.
Good ways to avoid such confusion is to
a. use absolute URL
b. the URL that're relative to root of your domain (that start with a /),
c. or define your domain's path in a variable, var domain_path = 'http://www.mysite.com/' and use it in your scripts.
I hope it clarifies things :)
Relative Paths in Javascript in an external file

Categories