callback function after submitting a form - callback

I have the following form :
Is there a way to add a callback function to the form after it is submitted? Basically I am echoing the result of upload.php to an iframe and what I want to do is to get that information using a callback function.

You want to use Ajax to submit the post, and have the javascript catch the echo in a result and write out the HTML to the iframe.

As Gnostus says: use Ajax to submit the form, and attach a function for when the ajax has completed and has received a response... something like this (javascript)
// microsoft does their XMLHttpRequest differently, so make a different object for them.
var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// this point is reached when ajax has completed
var output = xmlhttp.responseText;
doWhateverFunctionYouLike(output);
}
xmlhttp.open("GET","http://some.url.here,true);
xmlhttp.send();
Don't forget to get the values out of your form, do something like:
val1 = form.getElementsByTagName("input")[0].value;
val2 = form.getElementsByTagName("input")[1].value;
and submit them with the ajax call...
xmlhttp.open("GET", "http://some.url.here/?a=" + val1 + "&b=" + val2, true);
you get the idea.

Related

Javascript injection goes wrong

In our Android project (download manager) we need to show built-in web browser so we able to catch downloads there with the all data (headers, cookies, post data) so we can handle them properly.
Unfortunately, WebView control we use does not provide any way to access POST data of the requests it makes.
So we use a hacky way to get this data. We inject this javascript code in the each html code the browser loads:
<script language="JavaScript">
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = formSubmitMonitor;
window.addEventListener('submit', function(e) {
formSubmitMonitor(e);
}, true);
function formSubmitMonitor(e) {
var frm = e ? e.target : this;
formSubmitMonitor_onsubmit(frm);
frm._submit();
}
function formSubmitMonitor_onsubmit(f) {
var data = "";
for (i = 0; i < f.elements.length; i++) {
var name = f.elements[i].name;
var value = f.elements[i].value;
//var type = f.elements[i].type;
if (name)
{
if (data !== "")
data += '&';
data += encodeURIComponent(name) + '=' + encodeURIComponent(value);
}
}
postDataMonitor.onBeforeSendPostData(
f.attributes['method'] === undefined ? null : f.attributes['method'].nodeValue,
new URL(f.action, document.baseURI).href,
data,
f.attributes['enctype'] === undefined ? null : f.attributes['enctype'].nodeValue);
}
XMLHttpRequest.prototype.origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
// these will be the key to retrieve the payload
this.recordedMethod = method;
this.recordedUrl = url;
this.origOpen(method, url, async, user, password);
};
XMLHttpRequest.prototype.origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
if (body)
{
postDataMonitor.onBeforeSendPostData(
this.recordedMethod,
this.recordedUrl,
body,
null);
}
this.origSend(body);
};
const origFetch = window.fetch;
window.fetch = function()
{
postDataMonitor.onBeforeSendPostData(
"POST",
"test",
"TEST",
null);
return origFetch.apply(this, arguments);
}
</script>
Generally, it works fine.
But in Google Mail web interface, it's not working for some unknown reason. E.g. when the user enters his login name and presses Next. I thought it's using Fetch API, so I've added interception for it too. But this did not help. Please note, that we do not need to intercept the user credentials, but we need to be able to intercept all, or nothing. Unfortunately, this is the way the whole system works there...
Addition #1.
I've found another way: don't override shouldInterceptRequest, but override onPageStarted instead and call evaluateJavascript there. That way it works even on Google Mail web site! But why the first method is not working then? We break HTML code somehow?

Jade + mongodb + express.js, delete form not working

My delete code is not working and I think not even firing as I don't see my console.log, I have an add button that works with a form and they look alike, this is why I don't get it.
app.js:
var db = monk('localhost:27017/mongodb');
Jade:
extends admin_menu
block content
h1.
Cocktail list
ul
each cocktail, i in cocktaillist
li
p= cocktail.name
form#form_delete_project(name="/admin/delete_cocktail", method="post", action="/admin/delete_cocktail")
input#input_name(type="hidden", placeholder="", name="_id", value="#{cocktail._id}")
button#submit_project(type="submit") delete
index.js:
router.post('/admin/delete_cocktail', function(req, res) {
console.log(id)
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var id = req.body._id;
// Set our collection
var collection = db.get('cocktailcollection');
// Submit to the DB
collection.remove({
"_id":id
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem removing the information to the database.");
}
else {
// And forward to success page
res.redirect("/admin/cocktail_list");
}
});
});
Jade is built on indentation. Since you are not indenting the items in your form it is not in you form. In html your code would look like this:
<form>
</form>
<input name="_id">
<button>
Since your input with _id is outside the form it is not being posted. That is why your console log is showing nothing. There is no req.body._id.And, of course, your submit-button is also outside the form. So it does nothing.
So, the first thing you should do is indent the code.

Google Form Responses in a Notification Email

I'm using the Form Notifications add-on in a Google Form. I've edited the Code.gs and CreatorNotification.html files and all works fine - when a Google Form is submitted I get an email. Now I'm trying to get some of the fields from that Form submission into the email. But with the edits I've added below, the email notification stops working.
In the Code.gs script I have:
function sendCreatorNotification() {
var form = FormApp.getActiveForm();
var settings = PropertiesService.getDocumentProperties();
var responseStep = settings.getProperty('responseStep');
responseStep = responseStep ? parseInt(responseStep) : 10;
function onFormSubmit(e) {
//Get information from form and set as variables
var First_Name = e.value[2];
// If the total number of form responses is an even multiple of the
// response step setting, send a notification email(s) to the form
// creator(s). For example, if the response step is 10, notifications
// will be sent when there are 10, 20, 30, etc. total form responses
// received.
if (form.getResponses().length % responseStep == 0) {
var addresses = settings.getProperty('creatorEmail').split(',');
if (MailApp.getRemainingDailyQuota() > addresses.length) {
var template = HtmlService.createTemplateFromFile('CreatorNotification');
template.summary = form.getSummaryUrl();
template.responses = form.getResponses().length;
template.title = form.getTitle();
template.responseStep = responseStep;
template.formUrl = form.getEditUrl();
template.notice = NOTICE;
template.firstname = First_Name;
var message = template.evaluate();
MailApp.sendEmail(settings.getProperty('creatorEmail'),
form.getTitle() + ': Case submission',
message.getContent(), {
name: ADDON_TITLE,
htmlBody: message.getContent()
});
}
}
}
}
In the CreatorNotification.html I have:
<p><i>Form Notifications</i> (a Google Forms add-on) has detected that the form
titled <b><?= title ?></b> has received
<?= responses ?> responses so far.</p>
<p>Summary of form responses</p>
<p>First Name:</p> <?= firstname ?>
Any direction would be appreciated.
You are trying to run two triggers. That "Add-on" code creates a trigger. The Add-on creates an "Installable" trigger. You already have one trigger set up for the form being submitted. The onFormSubmit(e) function is a "Simple" trigger. So, you have two triggers set up to run when a form is submitted. So, you created a conflict. If you look in the RESOURCES menu, under CURRENT PROJECT's TRIGGERS, you should see a trigger defined for the sendCreatorNotification() function.
Here's what you can try. You don't need a seperate onFormSubmit(e) simple trigger. The sendCreatorNotification() function, has the event object available to it. Just add e to the sendCreatorNotification() function:
sendCreatorNotification(e)
The write your code to get the value out of e.

Submit a Form to Custom URL in Laravel 4

I have a simple form which allows the User to enter from_date and to_date.Lets say a user enters 2014-09-01 and 2014-09-10 respectively.
How can I get this form submit to a URL ../from_date/2014-09-01/to_date/2014-09-10
You cannot do that but if you need to do something like this, you need to submit to standard class Controller and then resubmit it using redirection:
public function resubmit() {
Redirect::to('/from_date/'.Input::get('from_date').'/to_date/'.Input::get('to_date'))->withInput();
}
But to be honest I don't know why you try to do that. Usually you post data to static url and display content using dynamic urls with pretty urls.
To change the URL once the page has already loaded, you will need to use javascript, as you won't be able to do this using Laravel/PHP because you need access to the dates, which are only selected after the page has loaded.
If your form is similar to:
<form id="dateForm" onsubmit="return submitDateForm()">
<input type="text" id="from_date" name="from_date">
<input type="text" id="to_date" name="to_date">
</form>
Assuming you are using POST for the form submission, and have already imported jQuery, then insert into your view (or a separate .js file which you import) the following jQuery:
function submitDateForm() {
var from_date = $( '#from_date' ).val();
var to_date = $( '#to_date' ).val();
//Send the request
var request = $.post("../from_date/" + from_date + "/to_date/" + to_date);
//prevent the form from submitting itself normally
return false;
}

How to get StatusDescription of HttpStatusCodeResult by JavaScript

I have a form created using Ajax.BeginForm()
<% using (Ajax.BeginForm("UpdateCompanyShop", "CompanyShop", FormMethod.Post,
new AjaxOptions { OnSuccess = "updateList", OnFailure = "onError",
UpdateTargetId="slist", LoadingElementId = "loading" }))
controller action code is like below:
if(string.IsNullOrEmpty(company.Address))
return new HttpStatusCodeResult(418, "Please fill in address");
else if (company.DistrictID < 0)
return new HttpStatusCodeResult(418, "Please select district");
else
return new HttpStatusCodeResult(418, "Error saving data");
I used OnFailure="onError" in AjaxOptions and I have my client-side script like this
function onError(response, status, error) {
var statusDescription = ***something***;
alert(statusDescription);
}
I use debugger in the JavaScript but cannot find the StatusDescription (the 2nd parameter in HttpStatusCodeResult)
Any idea how I can get status description? Or I should not use HttpStatusCodeResult at all? What is the proper way to return error (apart from validation) in AJAX submit?
Use response.statusText:
function onError(response, status, error) {
alert("Oops! " + response.statusText);
}
I wrote a post that provides somewhat more detail and a couple of examples:
Dealing with javascript or JSON results after an AJAX call with Ajax.ActionLink, unobtrusive AJAX and MVC 3
I have the same problem. I think the statusDescription should be response.responseText in the JavaScript OnFailure handler. When you do the following the responseText is not empty, but it's not a really nice solution imo:
Response.StatusCode = 400;
return Json("error message here", JsonRequestBehavior.AllowGet);