Using axios to submit a form without - forms

As you can see the code blow I tried to submit the form using axios but every time i try to submit the form i get a bad request error. but if submit this way it works! BUT then it redirect to /api/user/.
I'm using Next.js.
<Form
// onSubmit={(e) => {
// e.preventDefault();
// axios({
// method: "POST",
// url: "/api/user",
// data: {
// name: e.currentTarget.userName.value,
// email: e.currentTarget.userEmail.value,
// password: e.currentTarget.usePass.value,
// },
// }).then((res) => {
// prompt("Success", JSON.stringify(res.data));
// });
// }}
action="/api/user"
method="POST"
>

Related

Flask redirect after ajax request success

I develop a mapping app, the front-end is created with Flask. When searching the external backend (create with the django framework) with ajax requests. I would like redirect the url after return from the ajax response (if success or not). But, I don't know the best way for this !
submitHandler: function () {
/********* GET USER TOKEN WITH AJAX REQUEST**********/
$.ajax({
method: 'POST',
url: "url for get token",
data: {
username: $('#email-log').val(),
password: $('#password-log').val()
},
success: function (response) {
if(response.d == true) {
localStorage["username"] = $('#username-log').val();
localStorage["user_token"] = response['token'];
window.location = "{{url_for('maps')}}";
}
},
});
},
Where do I do this redirection?
In ajax request, in the form action = "", using url_for() somewhere ?
I'm lost in all these methods
If you only want to redirect after Ajax success you can do this:
$.ajax({
// do what you want,
success: function(){
window.location.href = "/url/for/route/" //redirect url
// or
window.location.replace("url/for/route")
}
});

Move to another hbs in ember after the authentication is done

I have an app in which I have include a fb login.I am using ember-simple-auth for authorization and session manganement.I am able to authenticate the user and move to my "feed" hbs .The problem is when I open the app on another tab it is rendering the login page.How do I implement where if the user is authenticated it directly move to "feed" hbs.Similary to facebook,instagram where user login for the first time and after that they are redirect to feed page until they logout.
autheticator.js
const { RSVP } = Ember;
const { service } = Ember.inject;
export default Torii.extend({
torii: service('torii'),
authenticate() {
return new RSVP.Promise((resolve, reject) => {
this._super(...arguments).then((data) => {
console.log(data.accessToken)
raw({
url: 'http://example.com/api/socialsignup/',
type: 'POST',
dataType: 'json',
data: { 'access_token':'CAAQBoaAUyfoBAEs04M','provider':'facebook'}
}).then((response) => {
console.log(response)
resolve({
// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
access_token: response.access_token,
// jscs:enable requireCamelCaseOrUpperCaseIdentifiers
provider: data.provider
});
}, reject);
}, reject);
});
}
});
router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('index',{path:'/'});
this.route("aboutus",{path:'/aboutus'});
this.route('feed',{path:'/feed'});
});
export default Router;
You need to use the application-route-mixin.js in the route that will be the first shown after login and authenticated-route-mixin.js for all the routes that need to be logged to see them. Check this example for further information.

Form - new page on submit button

Last year i build a form for one of our costumers, when visitors submitted the form they
got a message on the same page. But now he asks me if it is possible to
make a succes page if the form is filled in correctly.
I can't make it work. It's a bit out of my league.
So i hope anyone of you can help me out!
$(document).ready(function() {
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact/contact2.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(500, function() { $(this).hide(); });
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Uw bericht is verzonden, we nemen z.s.m. contact met u op!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(500);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
<form id="ajax-contact-form" target="_blank" method="post" action="javascript:alert('success!');" >
Instead of displaying the "success" message, redirect to a new page:
window.location = successPageUrl;
Just redirect to success page after ajax success.

how to handle multipart/form-data in node.js

I am uploading image file from client side using multipart form data. I want to receieve and write it as a file in the server side using node.js.
<html>
<body>
<form action="url" method="post" enctype="multipart/form-data">
<input type="text" name="imageName">
<input type="file" name="sam">
</form>
</body>
</html>
This is my client side code. How to handle this file in server side.
It is repeated question below link.
Uploading images using Node.js, Express, and Mongoose
Here is example:
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
If your question is not solve then please visit this link . This is a nice article about file uploading.
You can use request module for sending a multipart request. Here is the sample code:
var jsonUpload = { };
var formData = {
'file': fs.createReadStream(fileName),
'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
"url": "https://upload/url",
"method": "POST",
"headers": {
"Authorization": "Bearer " + accessToken
},
"formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
if (err) {
console.log('Error ', err);
} else {
console.log('upload successful', body)
}
});

Jquery, Validate, Submit Form to PHP (Ajax Problem)

Very early days playing Javascript, Jquery and Validate.
I am using the Submit Button onClick method for form submission.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using the submit, in case no data or not every field has been tested.
The logic is working, but the AJAX call does not appear to be working. I have stripped down the PHP to
<?php
touch('phpTouch.txt');
phpinfo();
sleep(30;)
?>
The javascript is
$(document).ready(function () {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
dataType: "json",
success: function () {
alert("SUCCESS:");
},
error: function () {
alert("ERROR: ");
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
return false; // Prevent the default SUBMIT function occurring (is this a fact ??)
};
Can anyone advise as to what I am doing wrong.
Thanks
Do these things
Change onClick="submitForm()" on the HTML markup to onclick="submitForm(event)"
Now change the submitForm function like this.
function submitForm(evt) {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').valid() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
contentType: "application/json;",
success: function () {
alert("SUCCESS:");
},
error: function (a, b, c) {
alert(a.statusText);
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
evt.preventDefault();
};
Please note these things
Check .valid() to determine form validity
Call .preventDefault() instead of return false; ( Its more jQuery-ish )