What I want to be abl
e to do is passing the form data to a php file and then having the results passed back into app so that the user isnt directly accessing the php file at any point.
This is what I came up with but I cant get it too pass the data. I used chrome with -disable-web-security. It always returns false so I guess the data isnt being passed to the php file. Any help would be great. Also. when it forwards to the results page, it goes blank after a few seconds. thank you.
HTML
<form id="form" method="POST" data-ajax="false" data-transition="pop" data-direction="reverse">
<fieldset>
<label for="name" class="ui-hidden-accessible">Name</label>
<input type="text" name="name" id="name" value="" class="required" placeholder="Name"/>
<label for="email" class="ui-hidden-accessible">E-Mail</label>
<input type="email" name="email" id="email" value="" class="required" placeholder="E-Mail"/>
<label for="memory" class="ui-hidden-accessible">Memory</label>
<textarea name="memory" name="memory" id="memory" class="required" placeholder="Your Memory..."></textarea>
<label for="submit" class="ui-hidden-accessible">Submit</label>
<input type="submit" name="submit" id="submit" value="SEND">
</fieldset>
</form>
JS
$(document).on('pagebeforeshow', '#formPage', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#name').val().length > 0 && $('#email').val().length > 0 && $('#memory').val().length > 0){
var that = $(this),
contents = that.serialize();
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({
url: 'http://www....',
dataType: 'json',
type: 'post',
data: contents,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function(data) {
console.log(data);
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
PHP
header('Content-type: text/javascript');
$json = array(
'success' => false,
'result' => 0
);
if(isset($_POST['name'], $_POST['email'], $_POST['memory'])){
$name = $_POST['name'];
$email = $_POST['email'];
$memory = $_POST['memory'];
$json['success'] = true;
$json['result'] = $name;
}
echo json_encode($json);
You are not serializing the form data correctly and the result is that the contents variable is empty.
Change this code:
var that = $(this),
contents = that.serialize();
To this:
//var that = $(this), // <-- delete this line
contents = $('#form').serialize();
YOU ALSO NEED TO FIX ..
You haven't realized it yet but you have created a multiple click binding issue by placing your click handler in the bagebeforeshow event. In order to prevent that from occuring you need to
Change this code:
$(document).on('pagebeforeshow', '#formPage', function(){
To this:
$(document).on('pageinit', '#formPage', function(){
This way your $(document).on('click', '#submit', function() { is only ever bound once regardless of how many times a user leaves and returns to the '#formPage' page
EDITED
No, the data submitted to your backend PHP program via ajax is not json encoded. It is standard HTTP POST data and is accessed via $_POST (or $_REQUEST).
I have your code (with the changes I outlined in my answer above) working on my server. I have placed the two files I setup to test your code in a pastbin for your reference:
The php file:
(edit the path to the included javascript file for your environment)
sandbox_ajax_form.php
The javascript file:
(edit the path that the form data is sent to)
sandbox_ajax_form.js
Related
I have a HTML code setup within my Google Apps Script project which basically validates the userid and password provided that pair exists in the gSheet or not and according to the verification I either show an alert or redirect to another web-page. When I deploy the code as a web-app, HTML renders just fine, submit button works and executes the gs code however it does not return the value back to the withSuccessHandler function of JS inside the script tag in the HTML code.
I have read a couple of very identical queries in the forum and followed exactly the same path, however I couldn't be able to succeed. For example like this post
It seems there's something that my eyes and mind cannot see - what is it?
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<form id="user_login">
<input type="text" name="userid" id="userid" placeholder="enter username"/>
<input type="text" name="pswrd" id="pswrd" placeholder="enter password"/>
<input type="submit" name="login" id="login" value="LOGIN"/>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$('#login').click(function() {
console.log("Form submitted...");
google.script.run
.withSuccessHandler(function(response) {
console.log(response);
if (response == true) {
window.open("http://www.google.com", "_self");
} else {
alert("Some alert message here")
}
})
.checkName({
userid: $('#userid').val(),
pswrd: $('#pswrd').val()
});
});
</script>
</body>
</html>
And here is the gs functions
var html;
var verified;
function doGet() {
html = HtmlService.createTemplateFromFile('myformtest').evaluate().setTitle('Web App').setSandboxMode(HtmlService.SandboxMode.NATIVE);
return html
}
function checkName(form){
Logger.log("Form info > "+JSON.stringify(form));
Logger.log("Userid > "+form.userid);
Logger.log("Pwd > "+form.pswrd);
verified = false;
var ss = SpreadsheetApp.openById("1rard7vdpjmfrN81oi2ARhMlLGdNSxC7MqoIw2soj25E").getSheetByName("names");
var values = ss.getDataRange().getValues();
for(n=1;n<values.length;++n){
var username = values[n][0]; // 1 is the index of the column starting from 0
var password = values[n][1];
Logger.log("username: "+username+" | password: "+password);
if (username == form.userid && password == form.pswrd) {
Logger.log("User found in Row("+(n + 1)+")");
verified = true;
break;
}
}
Logger.log("User verified? "+verified);
return verified
}
I can log that the JS is fired correctly with passing the form parameters to the gs function correctly and the gs function executed correctly as well. However, it does not return the true/false value back to the handler function inside the JS.
I expect that when the checkName function is executed, to return the variable's value back to the JS that is to be processed within the withSuccessHandler function and resulting with either redirecting to a definite URL or displaying an alert message.
I am trying to learn AngularJS and require help in passing user entered text box text value after button click to append to a string url value while calling the http service.
I'm trying to add in the following way but it is showing me a value of undefined while appending the URl with the user entered text from the text box.
Here is my HtmlPage1.html
<form ng-submit="abc(inputValue)">
<input type="text" name="name" ng-model="inputValue" />
<button type="submit">Test</button>
</form>
and my script file Script.js
var app = angular.module("repos", [])
.controller("reposController", function ($scope, $http, $log) {
$scope.inputValue = null;
$scope.abc = function (value) {
$scope.inputValue = value;
};
$http({
method:'GET',
url: 'https://api.github.com/users/'+$scope.inputValue+'/repos'
})
.then(function (response) {
$scope.repos = response.data;
$log.info(response);
});
});
Can anyone help me in this regard on how to get the right value that the user has entered to appended to the URL?
Thanks in advance.
Your get call is placed before you enter any value. In order to call the API with inputValue, place the get call inside the button click.
Also, you do not have to pass the inputValue into the function from HTML, Angular's 2 way binding will do the job for you.
Ex:
HTML
<form ng-submit="abc()">
<input type="text" name="name" ng-model="inputValue" />
<button type="submit">Test</button>
</form>
JS:
var app = angular.module("repos", [])
.controller("reposController", function ($scope, $http, $log) {
$scope.inputValue = null;
$scope.abc = function () {
$log.info($scope.inputValue) // you will have your updated value here
$http({
method:'GET',
url: 'https://api.github.com/users/'+$scope.inputValue+'/repos'
})
.then(function (response) {
$scope.repos = response.data;
$log.info(response);
});
});
};
I hope this helps.
Just remember that you have the code on your controller thanks to 2 way binding.
There you will set up an object for models. Ad later you can use them to submit data.
In order for you to understand what I am trying to explain I made an example, I hope it Helps
In your code:
Set the ng-model on the input tag
<input type="text" name="name" ng-model="vm.data.inputValue" />
On your controller make it available as in my example
vm.data ={};
Then use a function to send it using ng-click.
<button type="submit" ng-click="vm.submit()">Test</button>
I am sure there are more ways to do this.
I am not that good, explaining so I made an example, that I hope helps:
https://jsfiddle.net/moplin/r0vda86d/
my example is basically the same but I prefer not to use $scope.
Alright let's put it this way: How can I "redirect" a user to another page, "MyPage.php" after submitting a form that looks like this:
<form action="http://www.example.com/APageICanNotEdit.php" method="POST">
<input type="submit" name="send" value="Go" />
</form>
Please note that, I don't have control over the URL provided in the action attribute. It's an external source. Which means, I cannot edit the "APageICanNotEdit.php" file.
Here is what I want:
User will click on submit button (Labeled as Go)
action="http://www.example.com/APageICanNotEdit.php" - this action
must be performed, if possible, without displaying the contents of it.
I want the user to reach "MyPage.php" safely after
"APageICanNotEdit.php" is executed.
I need a solution without changing the URL in action, cause that
defeats the purpose.
use an hidden parameter like
<input type="hidden" name="action" value="1" />
Your form will look like this:
<form action="http://www.example.com/form-manager.php" method="POST">
</form>
Yout form manager will look like this:
if ($_POST['action'] == "1")
require_once('ThePHPFileIDoNotWantToBeLoadedOnBrowser.php");
Seeing your comment, you can do it with an AJAX call:
$(document).on('submit' , 'form[action="http://www.example.com/ThePHPFileIDoNotWantToBeLoadedOnBrowser.php"]' , function(e){
var formData = $(this).serialize(); // if you need any of the vars
$.ajax({
url:'someOtherURL.php',
type:'POST',
datatype:'json',
data: formData,
success : function(data){
for(var i = 0; i < data.length; i++){
console.log(data);
}
},
error : function(s , i , error){
console.log(error);
}
});
return true; // keep normal behavior
});
I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!
The HTML:
<form>
<input type="hidden" name="gid" value="12345678">
<input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global">
<input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True">
<input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)">
<input type="submit" name="signup" value="signup" class="email_submit_button">
</form>
Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:
$(".email_submit_button").click(function(){
var uemail = $('.email_input_field').val();
window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True";
return false;
}
});
I see you'r using jQuery so you can use the $.post to post to the server like this:
var url = "http://example.com/automated/action.jsp"
var data ={
"gid": form.gid,
"action": register,
"uemail": form.uemail,
"errorPage": "/automated/action.jsp",
"user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn,
"user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp
};
var success_func = function(data){
//do what you want with the returned data
};
$.post(url, data, success_func);
Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.
EDIT:
I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.
$(".email_submit_button").submit(function(e) {
// stop form from submitting
e.preventDefault();
// Grab all values
var uemail = $('.email_input_field').val();
// make a POST ajax call
$.ajax({
type: "POST",
url: "YOUR URL", // set your URL here
data: {
uemail: uemail // send along this data (can add more data separated by comma)
},
beforeSend: function ( xhr ) {
// maybe tell the user that the request is being processed
$("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>");
}
}).done(function( response ) {
// do something with the received data/response
//$("#status").html(response);
});
});
Not sure if ".email_submit_button" is the class given to the submit button or the form.. you need to use the id or class given to the form and not the submit button.. hope this helps
I am trying to assign different actions to same html form according to different submit buttons.
Can I do something like this ?
<FORM>
------
<INPUT type="submit" value="DoSomething" action="DoSomething.pl" method="POST">
<INPUT type="submit" value="DoSomethingElse" action="DoSomethingElse.pl" method="POST">
<FORM/>
Just in case someone else finds this post:
If you're using HTML5, this is now easier thanks to the formaction attribute. This attribute applies to input and button elements of type="submit" and forces the form to submit to the location specified in the formaction attribute of the clicked element.
Then only drawback of this attribute is that it's not supported by Internet Explorer 9 and lower, but this limitation can be easily overcome using a little JavaScript.
Example:
<form method="post" action="go_default">
<input type="submit" value="Go Left" formaction="go_left" />
<input type="submit" value="Go Right" formaction="go_right" />
</form>
For IE 9 and lower:
<script type="text/javascript">
$(function () {
var $submit = $('form [type="submit"][formaction]');
$submit.click(function() {
var $this = $(this),
action = $this.prop('formaction'),
$form = $this.closest('form');
$form.prop('action', action).submit();
});
});
</script>
No. A form has only one action (action being a property of the form, not the submit button).
The target of the action can do different things on the basis of the values in the form. So, you might want to start naming your submit buttons.
Learn HTML before you even think about writing and deploying a CGI script.
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="action" value="DoSomething">
<input type="submit" name="action" value="DoSomethingElse">
</form>
Note also that choosing an action based on the value of the submit button is a losing strategy if you wish to internationalize the application because the value of a submit button is what the UA displays to humans.
Therefore, script should decide what to do on the basis of some other input element's value.
For example, CGI::Application looks at a run_mode parameter.
Alternatively, you can use different names for your submit buttons as Alec suggests. In that case, you need to check which submit button was pressed by going through the names of the parameters passed to your script which, IMHO, makes the dispatch slightly more cumbersome. It also means it is possible for someone to pass values for all submit buttons to your script (not via the user interface, but via curl or wget or similar programs.
For example, given the HTML
<form method="POST" action="/cgi-bin/script">
<input type="submit" name="submit_left" value="Go Left">
<input type="submit" name="submit_right" value="Go Right">
</form>
here is how your script may handle form submission:
#!/usr/bin/perl
use strict; use warnings;
use CGI::Simple;
my $cgi = CGI::Simple->new;
my %dispatch = (
left => \&handle_left,
right => \&handle_right,
);
my #actions = grep s/^action_(right|left)\z/$1/, $cgi->param;
my $handler = \&handle_invalid_action;
if ( #actions == 1) {
my ($action) = #actions;
if ( exists $dispatch{ $action } ) {
$handler = $dispatch{ $action };
}
}
else {
$handler = \&handle_too_many_actions;
}
$handler->($cgi);
sub handle_left { }
sub handle_right { }
sub handle_invalid_action { }
# because it may indicate someone trying to abuse your script
sub handle_too_many_actions { }
You can also use Ajax for this, and every button has assigned an ajax function that calls it's own php script and you don't even need to refresh the page or redirect, like in this example that i have tried:
HTML:
<input type="submit" value="Make other thing" onclick="ajax_post1();"/>
<input type="submit" value="Make something" onclick="ajax_post2();"/>
<div id="script1Response"></div>
<div id="script2Response"></div>
Javascript functions:
//the first function
function ajax_post1(){
var hr = new XMLHttpRequest();
//take the values from the html input elements you want to use
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
//the script that will process the data
var url="php_script1.php";
//the variable that will contain the information for the php script
var dataVar="var1="+v1+"&var2="+v2;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script1Response").innerHTML = script_response;
}
}
// Send the data to php_script1.php
hr.send(dataVar); // Actually execute the request
document.getElementById("script1Response").innerHTML = "processing...";
}
//the second function
function ajax_post2(){
var v1=document.getElementbyId("element1").value;
var v2=document.getElementbyId("element2").value;
var url="php_script2.php";
var dataVar="var1="+v1+"&var2="+v2;
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var script_response = hr.responseText;
document.getElementById("script2Response").innerHTML = script_response;
}
}
hr.send(dataVar);
document.getElementById("script2Response").innerHTML = "processing...";
}
The php files will have to contain some variables that will store the values sent by dataVar parameter like this:
$var1_=$_POST['var1']; //the var1 from the dataVar parameter
$var2_=$_POST['var2']; //the var2 from the dataVar parameter
The example I used can be found here:
https://www.youtube.com/watch?v=woNQ2MA_0XU.