ReactJS ExpressJS - Ajax Form - ajax

Due to my starting level with React and Node/Express and, above all, time restriction, I'm developing a single page application without database, so I have only static pages.
I've configured react-router to have clear url, using the hash (http://localhost:8080/#/contacts) i avoid also server calls:
let history = createHistory({
queryKey: false
});
I've got the necessity to send mail from my form. To do this I've found nodemailer and I need to invoke it from an ajax call.
Just to do some pratique with React i've configured my ajax call in my componentDidMount function:
openForm() {
$('#contacts-form').on('submit', function(){
$.ajax({
url: '/mail',
type: 'post',
data: { msg: $('#data').val() },
success: function(data){
console.log(data);
},
error: function(){
console.log('err form');
}
});
return false;
});
}
componentDidMount() {
this.openForm();
}
Now, after I've installed body-parser and set my form's action to "/mail", in my server.js I've configured my .post route
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/mail', function(req, res){
res.send('ajax call recived');
});
So now once I try to submit my form, my ajax call fails, in the console, I get this error:
POST http://localhost:8080/mail 404 (Not Found)
err form
It's the first time I'm working with these tools, where I'm doing wrong?

Related

PWA doesn't execute jQuery form on success event every time

I have a working installable PWA. Here's my service worker's fetch code:
self.addEventListener('fetch', async e => {
e.respondWith(
fetch(e.request)
.catch(error => {
console.log(error);
return caches.match(e.request) ;
})
);
});
In another JS file I have form handling logic (this file also registers the service worker):
$("#myForm").submit(function (e) {
console.log("form submit");
let url = $(this).attr("action");
let method = $(this).attr("method");
let data = $(this).serialize();
$.ajax({
type: method,
url: url,
data: data,
success: function (response) {
console.log("SUCCESS");
},
error: function(err) {
console.log(err);
}
});
});
The problem is that sometimes the form callback is not triggered, but the form submission is triggered every time (based on the "form submit" in console).
I think figured it out. I forgot to disable the generic form submission event.
I added this in the event handling:
e.preventDefault();

Ajax call in Openshift throws 404 error

I'm trying to make a simple Ajax call in my app on Openshift. This is my ajax call which is triggered by pressing a button:
$.ajax({
url: 'http://my-site-name.rhcloud.com/asciimo',
method: 'POST',
data: {attr:"value"}
});
And this is node in my server.js file:
self.createRoutes = function() {
self.routes['/asciimo'] = function(req, res) {
res.send('done');
};
};
Everything works when I go to my-site-name.rhcloud.com/asciimo, but if I click a button (to get there) I get:
POST http://my-site-name.rhcloud.com/asciimo 404 (Not Found)
even though the link clearly works on it's own.
Change your method to GET
method: 'GET',
When you go to the URL directly in your browser, you are issuing a GET request, not a POST.
I know what the problem was now. In ajax there is a POST request and self.routes['/asciimo'] (given as a template by Openshift) deals with GET requests only. What solved the problem was simply rewriting my function as a separate POST function:
self.addpost = function() {
self.app.post('/asciimo', function(req, res){
res.send('done');
});
};

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

Ajax request error when changepage

guys. I have a juerymobile multi-page, and I have a button in #page-index, when click it, will send a ajax request to server, and changepage to #page-column, It run will in PC, but when i deploy the multi-page in phonegap, the button click can just run only twice, code is below:
function test()
{
$.mobile.changePage('#page_column');
$.ajax({
url: "http://192.168.168.120:8090/fcmobile/getTest",
dataType: "json"
}).done(function(data) {
alert(data.content);
});
}
I found if I remove $.mobile.changePage('#page_column');, the ajax request can be run well any times. but when I add the changePage code, it only can be run twice, in third time, ajax request can't even be send. Dose anybody know reason?
AJAX is made to be asynchronous, so no need to set async to false to get it working. Use events instead.
For example:
function test () {
$.ajax({
'url': "http://192.168.168.120:8090/fcmobile/getTest",
'dataType': 'json',
'success': function (json_data) {
$(document).trigger('test_json_data_loaded');
console.log(data);
}
});
}
$(document).on('test_json_data_loaded', function () {
$.mobile.changePage('#page_column');
});
When you set async to false, you're basically making it so that every time this AJAX request is made, the user will have to wait until all the data is fully loaded before the application/website can do/execute anything else...not good.

Request facebook permissions/login after ajax form validation (in ajax response)

It is working right now , but I have some feedback of user saying that the facebook popup is blocked by the browser
So what I am doing right now: I have a form that is being validated via ajax (making a call to a php page) , then if the response is successful, it ask for the user login/permissions. I assume that the popup is sometime blocked because the browser consider the ajax response not as an user action.
So my code looks like this :
$("#submit").click(function (event) {
event.preventDefault();
$.ajax({
url: url,
type: type,
data: form_data,
success: function(result){
if(result==""){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me/permissions', function (response) { ... });
} else if (response.status === 'not_authorized') {
FB.login(function (response) { ... });
}
}
}
}
});
Any idea other than putting the facebook calls before the form validation?
You can make ajax request as synchronous call. I don't like it though
btw, what kind of validation you are doing?

Resources