Submitting an image to Facebook with Javascript and HTML form - javascript

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

Related

Getting around CORS with embedded google forms

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.

Redirecting form submission to URL after sending the details to database

I am working on a popup newsletter signup. I already have the similar signup form in another page. I used the exact code and it works great. Once I submit the form, two actions has to happen.
Sending the form details to database
Redirecting to thank you page.
With the existing code(this is from a ecommerce website, I cannot manipulate the code), I can send the details to database - perfectly works fine, but
it is not redirecting to Thank You page, instead redirecting to the page hardcoded in the database(assigned to "action". Is there a way out?
This is the code.
<form name="MailingList" method="post" action="http://www.mywebsite.com/MailingList_subscribe.asp">
<input type="text" name="emailaddress" placeholder="Email Address" maxlength="100" size="28"> <br>
<input type="submit" name="Submit" value="Submit" width="260px">
</form>
Instead of this - http://www.mywebsite.com/MailingList_subscribe.asp, I would like to redirect to "www.mywebsite/thankyou.html" . If I assign www.mywebsite.com/ThankYou.html to "action" , then the form is getting redirected to Thank you page, but not sending the information to the database. I have to use HTML, I cannot call from outside file. I guess I need to use PHP, but I am unclear with the code.
Sorry my mind is all over the place, I guess I explained it clearly. Apologies if my question is unclear. Thanks
Give id to your form like formId and you can do this using jQuery,
Download the jQuery latest version from JQuery repo and then place the jquery.min.js file in your resources folder.
Updated
<script src="yourResourcesFolderPath/jquery.min.js"></script>
// above code will use the jQuery plugin online
// chances are that the file path might be wrong according to where you put the js file
// A simple way to try this is put your file in the same folder of your html file and then change above code to
// <script src="jquery.min.js"></script> change file name according to downloaded file name.
<script>
$(document).ready(function(){ // will run the below code after all html loaded
$('#formId').submit(function(){ // will be called upon form submission
$.ajax({
type: "POST",
url: "http://www.mywebsite.com/MailingList_subscribe.asp",
context: document.body
}).success(function() {
// this will be called when you return from your server submit code
location.href = "www.mywebsite.com/ThankYou.html";
});
});
)};
</script>

How to use form submit to load img tag using post?

I have an interactive plotting form like below:
<form method="post">
<img src="plot.cgi" alt="[plot]">
<input type="text" name="plot_settings" value="Type plot settings here.">
<input type="submit" name="submit" value="plot it">
</form>
(Simplified to the bare minimum above to show the point.)
The image is generated by plot.cgi, which sends the browser the new plot. At present, the user clicks the "plot it" button and the whole page reloads, but I'd like just the image to reload. Obviously, I could script each input into a GET request address and replace the img src with that, but post is more desirable, and it seems there should be a more elegant way to make use of the form's submit mechanism.
Is there a way to load the img using POST instead of setting a GET string to it's src?
(jQuery is okay.)
jQuery('form[method="post"]').submit( function( evt ) {
var url = jQuery(this).target();
var data = jQuery(this).serialize();
jQuery.post( url, data, function(data) {
jQuery(this).find('img').src( data.plotURL ); // use server-generated URL for plot img
});
evt.preventDefault();
}

Prevent accidental close of browser window while submitting

I have a page, on which a user can submit a form, containing a video. I've placed a "please wait, uploading now" message while the video is uploading, but apparently, that isn't enough.
SO: I want to make sure that the user doesn't accidentally navigate away from the page, so I've used this code:
window.onbeforeunload = function() {
return "Please make sure, the video has finished uploading before closing this window";
};
There's just a problem: The system contains two separate .php files; a form and a upload/thank-you page. This means that if I place the code on the form, it executes the code too early (when the submit-button is pressed) and if I place it on in the send.php-file, it executes too late since the video has to upload before the head-tag is run.
Any good ideas?
P.S. A possible solution could be to place the code on the form page and call the page using AJAX and the file handling ability workaround, but I have a feeling that this workaround might have caused dropped videos - so I play it safe.
Situation solved!
I removed the submit-functionality of the button and replaced it with this:
<input type="button" name="button" id="button" value="Send video" onclick="sendInformation();" />
I then created a javascript, which was submitting the information, but at the same time, initializing the onbeforeunload-code.
document.getElementById("pleasewait").style.visibility = 'visible';
document.getElementById("myForm").submit();
window.onbeforeunload = function(e) {
return "Please make sure, the video has finished uploading before closing this window.";
};
It also has the undesired effect, that the onbeforeunload-code is invalidated, the moment the upload.php page has loaded completely - so the user isn't asked twice when closing a succesful upload.
It works flawlessly.
Can you add the JS code when the user submits the form?
<form action="upload.php">
<input type="file" name="myfile" />
<input type="submit" />
</form>
upload.php
<?php
// Validate the data, copy the file, etc.
echo '<script>window.onbeforeunload = function(e) { return "Please make sure, the video has finished uploading before closing this window"; }</script>';
?>
That should work. However, I think you should give the option to leave:
<?php
echo '<script>window.onbeforeunload = function(e) { return confirm("Do you want to leave?"); }</script>';
?>

Detect successful html form submission using POST to cross-domain script from PhoneGap, mobile jQuery app

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.

Categories