Calling inside a method another method ReactJS - javascript

First of all I am new to React so if there's something to improve tell me.
I have a login form that sends the information with ajax to php,I want to catch the error and update a p element althought i cannot find the way to do it.
When it's wrong the message that I send with php i want to call another method however it says undefined.
var APP = React.createClass({
getInitialState:function(){
return{user:'',pass:'',message:''};
},
setUser:function(e){
this.setState({user:e.target.value});
},
setPass:function(e){
this.setState({pass:e.target.value});
},
setErrors:function(errors){
alert('calling');
this.setState({message:errors});
},
handleForm:function(e){
e.preventDefault();
var username = this.state.user;
var password = this.state.pass;
$.ajax({
'url':'prg/loginJSON.php',
'type':'POST',
data:{'username':username,'password':password},
success:function(result){
if(result.error){
window.location.href="http://localhost/learnSeries/home.html";
sessionStorage.setItem('cookiePass',result.token);
}
else{
this.setErrors(result.message);
}
},
error:function(xhr){
console.log('error ajax' +xhr.responseText);
}
});
},
render:function(){
return(
<form onSubmit={this.handleForm} id="loginForm" method="post" action="" role="form">
<label className="is-required">User</label>
<input type="text" name="username" onChange={this.setUser} id="username" required placeholder="User"></input>
<label className="is-required">Password</label>
<input type="password" name="password" onChange={this.setPass} id="password" required placeholder="Password"></input>
<input type="submit" value="Log In"></input>
<p>{this.state.message}</p>
</form>
)
}
});
React.render(<APP />, document.getElementById('site'));

The this in the success function is not the same as when you started the request with $.ajax. You have to remember it and use it instead of this later on (in my
handleForm:function(e){
// ...
// -->
var self = this;
// <--
$.ajax({
// ...
success:function(result){
if(result.error){
// ...
}
else{
// -->
self.setErrors(result.message);
// <--
}
},
// ...
});

Related

redirecting user to different page after pressing submit using vue.js

I am trying to redirect a user to a different page after they input there correct user information and then pressing the submit button using (window.location.href) to redirect but the page keeps reloading after the form has been submitted
<form id="login" method="post">
<h1>Login students</h1>
<label for ="username">username:</label>
<input required type="username" id="username" v-model="username">
<br><br>
<label for="password">password: </label>
<input required type="password" id="password" v-model='password'>
<br><br>
<button v-on:click='onSubmit'>submit</button>
</form>
var loginApp = new Vue({
el: '#login',
data: {
username: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var newUser = this.username;
var passcheck = this.password;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser & user.password === passcheck
})) {
//alert('Welcome back-' + newUser);
//window.location.href = '<index.html>' + '' + newUser;
window.location.href = "index.html";
} else {
alert('Incorrect username or password');
}
}
}
}
});
the proble is with
<form id="login" method="post">
the form doesn't have an action defined, so it makes the browsers refresh.
you need to prevent the default action either through the form element
<form v-on:submit.prevent>
or through your onsubmit handler:
methods: {
onSubmit: function (e) {
e.preventDefault()
//...
}
}

Polymer Iron-Form response

I'm using Polymer's Iron-Form component to submit this form I have created, but the problem is that the response from the php script won't output to the actual html. I'm stuck on how to do this and have tried many different things. What am I doing wrong? Here's my scrpits:
<dom-module id="user-signup">
<template>
<form is="iron-form" id="formGet" method="post" action="/core/register.php">
<paper-input char-counter autoValidate="true" error-message="{{item.error_name}}" label="Username" maxlength="25" required name="username"></paper-input>
<paper-input char-counter error-message="{{error_displayn}}" label="Display Name" maxlength="35" required name="displayname"></paper-input>
<paper-input char-counter error-message="{{error_password}}" label="Password" maxlength="25" required type="password" name="password"></paper-input>
<paper-input char-counter error-message="{{error_password}}" label="Confrim Password" maxlength="25" required type="password" name="cfmpassword"></paper-input>
<gold-email-input class="paper-input-input" label="Email" required name="email" auto-validate error-message="{{error_email}}"></gold-email-input>
<br />
<br>
<paper-button raised onclick="clickHandler(event)"><iron-icon icon="check"></iron-icon>Submit</paper-button>
</form>
</template>
<script>
function clickHandler(event) {
Polymer.dom(event).localTarget.parentElement.submit();
}
Polymer({
is: 'user-signup',
properties: {
error_name: {
type: String,
value:"Username Is Invalid!"
},
error_displayn: {
type: String,
value:"Display Name Is Invalid!"
},
error_password: {
type: String,
value:"Password Is Invalid!"
},
error_email: {
type: String,
value:"Email Is Invalid!"
}
},
listeners: {
'iron-form-response': 'formResponse',
'iron-form-submit': 'formSubmit',
'iron-form-error': 'formError'
},
formSubmit: function(event) {
var pmn = document.querySelector('#waitForResponse');
pmn.setAttribute("opened", "true");
console.log("Form was submitted");
},
formResponse: function(event) {
setTimeout(function(){
var pmn = document.querySelector('#waitForResponse');
pmn.removeAttribute("opened");
}, 5000)
console.log('There was a response');
var response = event.detail;
alert(response);
},
formError: function(event) {
console.log('Form Error, no actual response');
setTimeout(function(){document.querySelector('#errorToast').show();
var pmn = document.querySelector('#waitForResponse');
pmn.removeAttribute("opened");
}, 5000)
}
});
</script>
</dom-module>
Now the listeners work and when there is a response from the php page, the alert pops up but it says: [Object object]. Here is the php script:
<?php
$data[] = array(
"id" => $id,
"error_name" => $error_name,
"success" => true
);
echo 'dd';
?>
I have tried to echo $data as json but what didn't work either. I've tried to search it on Google and Stack but haven't found anything. What am I doing wrong?
according to the docs you have binded your listeners to a host element and not to form itself.
maybe this will help:
listeners: {
'formGet.iron-form-response': 'formResponse',
'formGet.iron-form-submit': 'formSubmit',
'formGet.iron-form-error': 'formError'
}
whats the model object, that your successful login call on php would return?
you could use the following, cosume the json coming back inside JS promise
$myPhpCallLogon.then(function(user) {
user.firstName...
user.id...
user.email...
var polyListUser = document.querySelector('#userView');
set watch vars in polyListUser element....
}
and then user your template to get the name,id, email etc into the dom of your element that displays the user.

call service rest on click with Backbone

I want to call a rest service (post) when I press on the button login but it doesn't launch any service it just add a "?" at the end of the url of my application.
here is my js :
(function ($) {
var authentication = Backbone.Model.extend({
defaults: {
Username: "",
Password: ""
},
url:'../../rest/login'
});
var LoginView = Backbone.View.extend({
model: new authentication(),
el: $("#login-form"),
events: {
"click button#login": "login"
},
login: function(){
alert("ici");
this.model.save({username: this.$el.find("#inUser")}, {
password: this.$el.find("#inPswd")}, {
success: function() {
/* update the view now */
},
error: function() {
/* handle the error code here */
}
});
}
})
})
(jQuery);
And here is my form :
<form class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="Username" id="inUser"></input>
<input type="password" class="form-control" placeholder="Password" id="inPswd"></input>
<button id="login">Login</button>
</div>
</form>
You have a problem with your .save() method call because you send username and password in two different objects.
Also to stop adding question mark ? sign (stop submitting your form) you need to add event.preventDefault(); and/or return false; to your button click handler.
Here is a fix:
login: function(event) {
event.preventDefault();
alert("ici");
this.model.save({
username: this.$el.find("#inUser"),
password: this.$el.find("#inPswd")
}, {
success: function() {
/* update the view now */
},
error: function() {
/* handle the error code here */
}
});
return false;
}

Prevent page reload after validation on backbone

I have this view:
return Backbone.Marionette.ItemView.extend({
template: template,
ui: {
form: '#login',
button: '#submitbutton'
},
onRender: function() {
this.ui.form.on('submit', function(e) {
// e.preventDefault();
mylogin = new login();
mylogin.save({boxid:$("#boxid").val(),password:$("#passwordid").val(),validate:true});
vent.trigger('navigate', 'home');
// if(myLogin.validationError) {
// vent.trigger('navigate', 'home');
// }
return false;
});
}
});
and this model:
return Backbone.Model.extend({
validate: function(attrs, options){
if(attrs.boxid.length < 10)
{
return "user id must be more than 10 characters";
// return "BoxID should be greater than 10";
}
else if(attrs.password.length < 10)
{
return "password must be more than 10 characters";
// return "Password should be greater than 10";
}
else if((attrs.boxid!=myBoxid)||(attrs.password!=myPassword))
{
return "Your login credentials are incorrect";
}
},
});
And this login html template:
<div class>
<div>Information</div>
<div>
<form id="login" name="login" method="post">
<div>
<label for="boxid">BoxID</label>
<input id="boxid" name="box" placeholder="Enter your box ID">
</div>
<div>
<label for="password">Password</label>
<input id="passwordid" type="password" name="password" placeholder="Password">
</div>
<label id="errormsg"></label>
<button id="submitbutton">Login</button>
</form>
</div>
</div>
The problem is that each time the user enters wrong credentials the page reloads, are there any way to prevent this?
To make this work you should but back the e.preventDefault(); line.
More important is that the model has no url function http://backbonejs.org/#Model-url
return Backbone.Model.extend({
url: function () {
// see the docs, it can be a url string or a function
}
validate: function(attrs, options){
},
});

jQuery post request (not AJAX)

In an ASP.NET MVC app I use jQuery for posting data on button-click:
<button onclick="addProducts()">Add products</button>
....
$.post('<%= Url.Action("AddToCart", "Cart") %>',
{
...
returnUrl: window.location.href
});
In the "AddToCart" action of "Cart" controller I use redirection to another View after posting:
public RedirectToRouteResult AddToCart(..., string returnUrl)
{
...
return RedirectToAction("Index", new { returnUrl });
}
All is okay, except this redirection. I stay on the same page after posting. I suspect it's due to AJAX type of "POST" request.
How to solve the problem with jQuery POST request blocking the redirection?
I created a $.form(url[, data[, method = 'POST']]) function which creates a hidden form, populates it with the specified data and attaches it to the <body>. Here are some examples:
$.form('/index')
<form action="/index" method="POST"></form>
$.form('/new', { title: 'Hello World', body: 'Foo Bar' })
<form action="/index" method="POST">
<input type="hidden" name="title" value="Hello World" />
<input type="hidden" name="body" value="Foo Bar" />
</form>
$.form('/info', { userIds: [1, 2, 3, 4] }, 'GET')
<form action="/info" method="GET">
<input type="hidden" name="userIds[]" value="1" />
<input type="hidden" name="userIds[]" value="2" />
<input type="hidden" name="userIds[]" value="3" />
<input type="hidden" name="userIds[]" value="4" />
</form>
$.form('/profile', { sender: { first: 'John', last: 'Smith', postIds: null },
receiver: { first: 'Foo', last: 'Bar', postIds: [1, 2] } })
<form action="/profile" method="POST">
<input type="hidden" name="sender[first]" value="John">
<input type="hidden" name="sender[last]" value="Smith">
<input type="hidden" name="receiver[first]" value="John">
<input type="hidden" name="receiver[last]" value="Smith">
<input type="hidden" name="receiver[postIds][]" value="1">
<input type="hidden" name="receiver[postIds][]" value="2">
</form>
With jQuery's .submit() method you can create and submit a form with a simple expression:
$.form('http://stackoverflow.com/search', { q: '[ajax]' }, 'GET').submit();
Here's the function definition:
jQuery(function($) { $.extend({
form: function(url, data, method) {
if (method == null) method = 'POST';
if (data == null) data = {};
var form = $('<form>').attr({
method: method,
action: url
}).css({
display: 'none'
});
var addData = function(name, data) {
if ($.isArray(data)) {
for (var i = 0; i < data.length; i++) {
var value = data[i];
addData(name + '[]', value);
}
} else if (typeof data === 'object') {
for (var key in data) {
if (data.hasOwnProperty(key)) {
addData(name + '[' + key + ']', data[key]);
}
}
} else if (data != null) {
form.append($('<input>').attr({
type: 'hidden',
name: String(name),
value: String(data)
}));
}
};
for (var key in data) {
if (data.hasOwnProperty(key)) {
addData(key, data[key]);
}
}
return form.appendTo('body');
}
}); });
$.post is an AJAX call.
Your best bet is to make the button a trigger for a form and just submit that using the post method.
An alternative would be to echo your new url from the server, but that defeats the point of AJAX.
Use jQuery.submit() to submit form: http://api.jquery.com/submit/
It looks like you are trying to Add Products to the cart and then redirect to your current page. My guess is is that is how you are updating the visual effect of your shopping cart. I would suggest adding the success handler on your $.post and then redirecting to the current page. If an error occurs on the server, you can send back the serialized error and handle it client side.
function addProducts() {
$.post('<%= Url.Action("AddToCart", "Cart") %>',{
returnUrl: window.location.href
}, function(data){
window.location.href = window.location.href
});
}
This will refresh your current page after your products are posted.
Here is a fiddle for reference: http://jsfiddle.net/brentmn/B4P6W/3/
If you're doing a full redirect after a post, then why do it with Ajax? You should be able to perform a tradtional POST here and have it successfully redirect.
If you really want an ajax request to go through and still redirect, a very easy and non-intrusive way to do that would be to return a JavascriptResult from your action instead of a RedirectResult:
return JavaScript("window.location = " + returnUrl);

Categories