I'm trying to send form data to google via an embedded form.
I found this post that seems to answer my question but I'm getting CORS errors. Is there a way to solve this?
Other posts seem to say that CORS isn't an issue but I'm getting the errors.
Here is my code:
-JS-
function ajax_post() {
var field1 = $('#email').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/xxxxxxxxxxxxxxxxxxxxxx/formResponse",
data: {"entry.xxxxxxxxxx": field1},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
-HTML-
<form id="emailForm" target="_self" onsubmit="" action="javascript: ajax_post()">
<input id="email" type="text" autocomplete="off" tabindex="0" name="entry.xxxxxxxxxx" required>
<button id="send" type="submit">Submit</button>
</form>
The “No 'Access-Control-Allow-Origin' header is present on the requested resource” message indicates that responses from https://docs.google.com/forms/d/e/xxxx/formResponse URLs currently don’t include the Access-Control-Allow-Origin response header, so browsers won’t allow your frontend JavaScript code to access the response.
Given that, from your frontend code there’s no way you can tell if the POST request succeeds or not. But barring any other problems, it seems like the request will always succeed. If the request doesn’t reach the server at all (due to some network error) then you’ll hit a different failure condition that is observable from your frontend code so you can actually catch it.
So the way you know the request has successfully reached the server is just that you don’t get any other failure that’s observable from your frontend code.
I've found that it's actually easier to just POST the form with a hidden iframe as its target, and capture that iframe reload when the response is submitted.
For example, if this is your form:
<form id="my-form" target="my-response-iframe" action="https://docs.google.com/forms/u/1/d/e/<YOUR-ID>/formResponse" method="post">
<input type="text" name="entry.12345678" value="" required>
<input type="submit">
</form>
Then include an iframe on the same page, with the same id AND name you put as target in the form:
<iframe id="my-response-iframe" name="my-response-iframe"></iframe>
When the form is submitted, it should reload that iframe with the "Your response has been recorded." page from Google. We can catch that reload with JavaScript, so include this after your form and iframe:
<script type="text/javascript">
// set the target on the form to point to a hidden iframe
// some browsers need the target set via JavaScript, no idea why...
document.getElementById('my-form').target = 'my-response-iframe';
// detect when the iframe reloads
var iframe = document.getElementById('my-response-iframe');
if (iframe) {
iframe.onload = function () {
// now you can do stuff, such as displaying a message or redirecting to a new page.
}
}
</script>
You can't check whether the response was submitted correctly because you can't inspect the contents of a cross-origin iframe (that'd be a huge security risk), so just assume that if this iframe reloads, the response was ok.
You can hide the iframe with the following CSS:
visibility: hidden
height: 1px;
Much cleaner if you ask me, with no console errors or failed requests.
Related
I have spent hours chasing this and hope someone has a simple answer. I am using fetch to execute a routine. The server does not seem to populate the post values. I simplified the code to try and isolate it. A simple html form makes js request which issues a fetch including post of username and pwd. The values get passed to the server but the target php page has the $_POST array empty. Code follows. Any ideas?
web page initiating the request
***
<html>
<head>
<script src="/js/2.js"></script>
</head>
<body>
<h1>Who are you?</h1>
<form action="" method=POST>
<label>User Name</label>
<input id=username type=text autocomplete='username' name=username>
<label>Password</label>
<input id=pwd type=password autocomplete='current-password' name=pwd>
<input type=submit value="log in" onclick="login();">
</form>
</body>
</html>***
javascript fetching the response from the php page
***
async function login(){
let content = "username=buddy&pwd=xxxxxxxxx";
let response = await fetch("http://example.com/lib/2.php",{method: "POST", body: content });
var text = await response.text();
if(text == 1){
window.open("http://example.com", "_self");
}else{
alert(text);
}
}***
**php page where post does not populate**
***
<?php
echo "user name is ".$_POST['username'];
?>***
UPDATE: It turns out there was nothing wrong with the code in the first place. The introduction of formdata working was a fluke. On further testing, it failed as well. In fact, execution of the code sometimes worked and sometimes did not. I traced the problem down to the user of session_start. I need to do more research on the use of session_start so I am not sure why it causes the problem but I suspect that the $_POST is being associated with the session id and some of the time the session ids match and the post is visible and in other cases the session ids are different and the post is missing.
I’m going crazy with image upload to Facebook. I’ve tried HTML5 drag and drop methods, Dropzone.js, as well as uploading to my own server before submitting the image via PHP. But the only one I can make work (because of my inexperience, I’ll admit) and that doesn't involve uploading the image to my own server, is by using a HTML form as shown in the Facebook documentation:
<form id=“upload_form” enctype="multipart/form-data" action=“https://graph.facebook.com/event_id/photos?access_token=an_access_token” method="POST">
Please choose a photo
<input name="source" type="file"><br/><br/>
Say something about this photo:
<input name="message" type="text" value=""><br/><br/>
<input type="submit" value="Upload"/><br/>
</form>
I dynamically generate it in Javascript and use var’s to fill in event_id and access_token.
This works fine, so all my permissions and authorising are correct. Now what I’d like to do is handle the response because the browser does as you’d expect when the user clicks submit and displays basic text showing the post id and whatnot.
So, I created a button and bound the following to it’s click event:
var fd = document.getElementById('upload_form');
if (fd) {
console.log('Sending');
var XHR = new XMLHttpRequest();
XHR.addEventListener('load', function(data) {
console.log('XHR finished:');
console.log(data);
});
XHR.addEventListener('error', function(data) {
console.log('XHR ERROR:');
console.log(data);
});
var graph_url = 'https://graph.facebook.com/'+event_id+'/photos?access_token=' + access_token;
XHR.open('POST', graph_url);
XHR.send(fd);
}
Once the user has selected an image and clicks my button to execute the above XHR completes the send and reports as finished, but Facebook replies with:
(#324)Requires upload file.
Please can someone show me where I’ve gone wrong - it’s been a problem for days now!
If you willing to use jquery and jquery.ajaxForm plugin
<!-- You form code stay Make sure your form.action url is valid ajaxForm use that as url -->
<form id=“upload_form” enctype="multipart/form-data" action=“https://graph.facebook.com/event_id/photos?access_token=an_access_token” method="POST">
Please choose a photo
<input name="source" type="file"><br/><br/>
Say something about this photo:
<input name="message" type="text" value=""><br/><br/>
<input type="submit" value="Upload"/><br/>
</form>
//your javascript to upload the image togather with message
// put this in a button, not submit button
$('#upload_form').ajaxForm({
complete: function(data) {
//process fb response
}
});
I suggest you use Fiddler to catch both connections, with and without XMLHttpRequest and see which is the actual difference between both request, I don't actually know what XHR.send(fd); does, but maybe it's sending the form content itself, not submitting it?
Fiddler is a very useful tool when connecting to external APIs
I want to send a login form to a site without having the page redirect to that site but rather just display a blank page instead. I have been looking around and noticed jquery would help me with this but I haven't found a way to get it to work quite right so I was hoping for some advice. This is what I have right now.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form id="myForm" action="placeholderurl" method="post">
<input type="hidden" name="username" value = "placeholder"/>
<input type ="hidden" name="password" value = "placeholder"/>
<input type="submit"/>
</form>
<script>
$(document).ready(function() {
$('#myForm').submit(function(e) {
e.preventDefault();
var formdata = $('#myForm').serialize();
$.ajax({
url: "placeholderurl",
type: "POST",
data: formdata,
cache: false,
success: function(data) {
alert("yeah");
//?code to display blank page after successful login??
},
error: function(){
alert("noo");
}
});
});
});
</script>
</head>
</html>
Currently, the code always goes into the "noo" error block. I'm not sure how to extract more information out of the error so I don't know exactly what is going wrong. Any advice/tips would be appreciated.
*Edit
The placeholderurl and placeholder are filled in with the correct information in my actual code. Also, the url I want to post to is not in the same domain as the function is being called from so ajax may not work for this(comment from Archer). Since this is the case, is there another way to get the desired behavior that I can try without using ajax. Thanks again.
I'd suggest watching your network traffic in something like Fiddler, Firebug, or Chrome's developer tools and see what the response is that is causing the error. I'm guessing your placeholderurl is on a different domain and your call is failing due to that.
I know there are many topics about it, but none of them worked. I need just to get iframe content(not source code).
I have a form, that posts some parameters to another server and I target it to iframe(that lies on the same page). So I receive server responce code storred in my iframe without page refresh:
<form name='vin_form' id='file_upload_form' action='*****' method='post'>
<input name='name1' value='value1'>
<input name='name2' value='value2' type='hidden'>
<input name='name3' value='value3' type='hidden'>
<div onclick=\"document.getElementById('file_upload_form').target = 'upload_target'; document.vin_form.submit();\">Send form</div>
</form>";
<iframe id='upload_target' name='upload_target'></iframe>
To get iframe content I used everything, but nothing worked:
jQuery('#upload_target').load(function()
{
alert(jQuery('#upload_target').contents().find('body').html());
var myIFrame = document.getElementById('upload_target');
var content = myIFrame.contentWindow.document.body.innerHTML;
alert(content);
alert(window.frames.upload_target.document.body);
}
);
I read about "same origin policy", but I think it shouldn't be forbidden in my case, because I can access that page by url and read all the code, so why I can't do it programmatically?
P.S.: Are there some other ways to get form responce code from another server? (php curl doesn't work because of some site framework defence)
*update - try this:
var t = document.getElementById("upload_target");
var y =( t.contentWindow || t.contentDocument);
alert(y.document.body.innerHTML)
I'm making a PhoneGap mobile jQuery-based iOS app for evaluating courses at my uni.
The university provides a course evaluation platform that uses a regular html-form with method="POST".
As the script belongs to and is hosted by my uni I cannot edit it nor read it.
<form action="http://example.com/script/kurt2/receive.php" method="post" target="result" onsubmit="" id="klinikkurt">
<input type="hidden" name="id" value="4136" />
<input type="range" name="q1" value="" min="1" max="6" data-track-theme="d" data-theme="d"/>
</form>
On successful submission the script redirects to a thank you-page, this renders the app useless. Adding a target to the form and a hidden iframe keeps the app usable on submission.
I would like to display a thank you message and reset the form in the app upon successful submission the problem (and my question) is that I don't know how to detect a successful form submission.
I've tried using an onLoad event on the iframe, and while this will execute javascript on successful submission it will also execute the function on initial load.
UPDATE
Per Elijah's suggestion I've been trying (unsuccessfully) to achieve this using jQuery's .ajax
This is my code:
HTML: As above but I've removed the action-attribute on the form.
Javascript:
$("#klinikkurt").submit(function() {
var dataString = $("#klinikkurt").serialize();
$.ajax({
url: 'https://doit.medfarm.uu.se/script/kurt2/receive.php',
type: "POST",
data: dataString,
success: function() {
$('#kk').load('index.html');
}
});
return false;
});
On submit nothing happens but a refresh.
how about using AJAX to submit the form content? This would allow you to handle the result of the HTTP request in your JS instead of the browser handling it directly...
Social bookmarking sites like Digg and Reddit let the users decide the main content of the site by voting on content that the users like. They use AJAX to handle all of the voting, so that the users are able to voice their opinions on a number of stories quickly and easily.