I am creating a chat application using Node.js, and would like to have a file upload feature. While I can get the file uploaded, the browser would always be redirected to another link or page refreshed, and this of course disrupts the chat.
First I tried using Express to do it:
index.html:
<form id="fileSendButton" action="/" method="post" enctype="multipart/form-data">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
app.js:
app.post('/', function(req, res){
//some validation and rename file
res.send();
return false;
});
Next I tried using AJAX, but still couldnt do it, whenever the AJAX POST to the Node.js server, it would reload the page. My AJAX code anyway:
index.html:
$.ajax({
type: "POST",
url: "/",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("chatText").innerHTML = res;
}
});
return false;
Third I went to look at Uploadify, but didnt want to add Flash dependancy to my site, so I didnt implement it.
Anyone can help me please? I dont want a page reload when a file is uploaded.
You can do it with a dynamically created hidden frame on the client side.
see here for a detailed howto with expressjs.
Uploadify now has a pure HTML5 play.
Related
I'm learning to use the Phoenix framework, and I'm trying to do an AJAX post to a controller action - however, I'm running into a problem with the CSRF protection.
For starters, I'm not using a form - just want to pass text from an input to the controller:
<input type="text" id="raw-input" />
<button id="send-button">Send it!</button>
<script>
$("#send-button").click(function(){
var input = $("#raw-input").val();
$.ajax({
url: "/test/process",
type: "POST",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader("X-CSRF-Token", $("meta[name='csrf-token']").attr("content"))},
data: {"input" : input},
success: function(response){
console.log(response);
}
});
});
</script>
The controller (not worried about doing anything input yet... just want to verify a successful post!):
def process(conn, %{"input" => input}) do
IO.puts "got it!"
end
And the router:
post "/test/process", TestController, :process
I pretty much lifted the $.ajax call from a Rails app where it was working fine, but it's not doing the trick here - running this returns a 403 error and logs (Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Request Forgery) token, make sure all requests include a valid '_csrf_token' param or 'x-csrf-token' header.
Can anyone offer any guidance? Thank you!
This is because Phoenix does not create a meta tag with the CSRF token by default. They're only included in forms generated by Phoenix's helper functions, and they're in a hidden input.
To get a CSRF token programatically in Phoenix, you can call Plug.CSRFProtection.get_csrf_token/0. There are many ways to pass this to your JS. You can add a meta tag to your layout to include it in every page but that might not be very efficient since it'll be generated for all pages. You can also just store it in a JS variable in the views that you require them in:
<input type="text" id="raw-input" />
<button id="send-button">Send it!</button>
<script>
$("#send-button").click(function(){
var CSRF_TOKEN = <%= raw Poison.encode!(Plug.CSRFProtection.get_csrf_token()) %>;
var input = $("#raw-input").val();
$.ajax({
url: "/test/process",
type: "POST",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", CSRF_TOKEN);
},
data: {"input" : input},
success: function(response){
console.log(response);
}
});
});
</script>
Phoenix already has helper csrf_meta_tag. Include it in the layout like so:
<html lang="en">
<head>
<%= csrf_meta_tag %>
...
And then use it in your js like so: $("meta[name='csrf-token']").attr("content")
If you want to skip the CSRF token check (in case you are developing APIs only) then you can comment out below line -
plug :protect_from_forgery
inside your respective _web/router.ex
Despite the fact that there are lots of questions in stackoverflow related to XMLHttpRequest and same-origin-policy error, I didn't find solution for my issue. Even though the The same origin policy wiki gives a great reference to the related subject, I wasn't able to find proper way.
The issue is that WebKit based browsers and IE raise bellow issue when I try to submit form data to google forms. However, the mentioned browsers successfully submit the data and I have it in my spreadsheet.
XMLHttpRequest cannot load https://docs.google.com/a/<myDomain>/forms/d/<myFormKey>/formResponse.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:9000' is therefore not allowed access.
On the other hand FireFox does the job and returns status code: 200 OK. The question is how can I solve the issue, that WebKit based browsers and IE show status code 0 OK or 200 OK?
here is the code that I am using
HTML:
<form name="quickMessageForm" submit="postQuickMessageToGoogle()" >
<input type="text" name="name" id="name"><br>
<input type="email" name="email" id="email">
<textarea name="content" id="content"></textarea>
<button type="submit">Submit</button>
</form>
JavaScript
$scope.postQuickMessageToGoogle = function() {
$.ajax({
url: 'https://docs.google.com/a/<myDomain>/forms/d/<myFormKey>/formResponse',
data: {
'entry.397424023' : $scope.quickMessage.name,
'entry.1127838473' : $scope.quickMessage.email,
'entry.1078099467' : $scope.quickMessage.content
},
type: 'POST',
dataType: 'xml',
statusCode: {
0: function (){
successSubmit(
$scope.quickMessage.name,
$scope.quickMessage.email,
$scope.quickMessage.content
);
},
200: function (){
successSubmit(
$scope.quickMessage.name,
$scope.quickMessage.email,
$scope.quickMessage.content
);
}
}
});
}
I had the same issue and I solved it following iShow's comment on this post.
the problem seemed in the dataType: 'xml'. When I changed it to the dataType: 'jsonp' the problem was solved.
I’m trying to pass a hidden value that is from database to another PHP file using AJAX with GET method. But it keeps saying undefined variable. I couldn’t use a normal POST method as requirements do not want a button but a normal url link.
<script type="text/javascript">
$(document).ready(function() {
$("#edit").click(function(){
$.ajax({
type:"GET",
url:"editItem.php",
data:"itemid=" + $(this.find(":selected").val()),
cache: false,
success: function(msg){
}
});
});
});
</script>
<input type="hidden" name="itemid" id="edit"/>
Edit
The ajax call is established successfully. But when i try to get some response from the php there is a problem. In the .php file i have, <?php echo 'hello'; ?>. When i alert the parameter in the success function, it gives me the entire php file. The datatype requested in the ajax call is "text". Please let me know where i am making a mistake..
Code:
<script>
$(document).ready(function()
{
/* Attach a submit handler to the form */
//$("#foo").submit(function(event) {
$('form').on('submit', function(event){
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "ajaxSamplephp.php",
type: "post",
data: values,
datatype: "text",
success: function(data){
alert("success");
$("#result").html('Submitted successfully');
alert(data);
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
});
</script>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<div id="result">RESULT</div>
</body>
PHP File
<?php
echo 'Hi I am some random';
?>
OUTPUT: <?echo 'Hi I am some random'; ?> in alert window
GOT THE OUTPUT: My URL was the problem. I use wamp server and Eclipse PDT. The workspace was there in a different location so i coulnt get the output.
And in php file i have given echo json_encode('[{"key":"value"}]'); In the ajax call, i have changed the data type to 'json'. But alerting like alert(data.key); gives me 'undefined' - message. Help would be greatly appreciated...
UPDATE (to answer second part of question): Do JSON.parse(data) to generate a JavaScript object from your JSON. Then you can use the object returned by the method to get the properties.
I'd check to see that your web server is configured to use PHP.
This could mean you have to install the PHP package (using something like sudo apt-get install php5) or enable PHP in your web server's configuration (I believe the libapache2-mod-php5 package on Ubuntu configures it for you).
I try to implement an ajax request in my django app to get the number of spectators of a flash video recorder I implemented in my app. This number is in an xml file.
Here the js I used did in my template:
var url = window.location.pathname.split('/');
var id = url[2]; // The id of my video is www.mysite/video/ID.com
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxmlfiles",
success: parseXml
});
}, 2000);
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id) {
$(".DubScore").html($(this).attr("count"))
}
});
}
And in my html:
<div class="DubScore"> </div>
The xml file renders:
<streams>
<user id="3" count="1"/>
</streams>
The problem is nothing appears. I really don't know what I did wrong.
Any advice would be great,
EDIT:
When I run my js console, I can see the number of spectators, as I wanted. So the only problem is that it doesn't display this number into my div. The problem is between the js and the html. If you have any idea on how to fix it, it would be great. Thanks