Polymer Iron-Form response - javascript

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.

Related

jQuery validate only get triggered on the second submit

I have the jquery validation function in the javascript which will get called from react js function.
React JS
function handleFormSubmit(e){
e.preventDefault()
window.validateForm();
}
return (
<form id="contactForm" onSubmit={handleFormSubmit} novalidate="novalidate">
<input name="name" id="name" type="text" placeholder="Name" onChange={handleInputChange} />
<textarea name="address" id="address" cols="4" rows="4" placeholder="Address" onChange={handleInputChange}></textarea>
<button type="submit">Submit</button>
</form>
)
JavaScript
function validateForm(){
$("#contactForm").validate({
rules: {
name: { required: true },
address: { required: true }
},
messages: {
name: { required: "Name field is required" },
address: { required: "Address field is required" }
}
});
}
The first submit is calling the validateForm() function but it won't trigger the jquery validate(). It only get triggered on the second submit click.
The reason is because you are assigning the Validation on the first click. It assigns its own event listener. The second click runs it and you also reassign the validate code again.
You need to just call the code on document ready. So get rid of the on submit
I have the jQuery validation function in the javascript which will get called from react js function.
$(function () {
window.validateForm();
});
And seeing you are using jQuery with React, it is a bit more complicated than that.

JQuery validation form but not `submit` button

I'm using the JQuery.Validation plugin to validate some fields in a form, but I don't want to use a submit button, I want to use just an <input type="button"> and once clicked using JQuery I want to call my controller, the only thing is that it's not a submit button, so even if the fields are wrong or not validated it will call the controller even if the fields values are wrong, because I'm using the .click() event of JQuery when that button is clicked, I want when I have wrong values on the fields and the validation is showing an error message not to call my action controller even if the button is clicked, how can I reach this?
This is my html code:
<script src="~/js/jquery.validate.js"></script>
<form action="post" class="rightform newsletter" id="formSubscription">
<div class="title">
<img src="http://ligresources.blob.core.windows.net/public/UK/Content/Images/newsletter.png" alt="">NEWSLETTER
</div>
<input type="text" id="txtFullName" name="fullName" placeholder="Full name" required>
<input type="email" id="txtEmail" name="email" placeholder="Email address" required>
<button type="button" id="btnSubscription" data-url="#Url.Action("SubscriptionEmail","Email")" style="background-color:#f66804;">SUBSCRIBE TO NEWSLETTER</button>
</form>
This is the JQuery.Validation plugin code:
$(document).ready(function () {
$("#formSubscription").validate({
rules: {
email: {
required:true,
email:true
},
fullName: {
required:true
}
},
messages: {
email: {
required: "Please enter an email address",
email: "Please enter a valid email address"
}
}
});
});
And this is the JQuery function that I have for the moment to throw when the btnSubscription is clicked:
$(document).ready(function () {
$("#btnSubscription").click(function () {
SendSubscription();
}),
return false;
}),
function SendSubscription() {
$.ajax({
type: "post",
url: $("#btnSubscription").data("url"),
data: { fullName: $("#txtFullName").val(), emailAddress: $("#txtEmail").val() },
success: function () {
alert("email sent")
},
error: function () {
alert("An error occurred..")
}
});
}
Once you set up your .validate() all you need to do is call the .valid() method in your .click() handler. This is what submit does automatically, but you can call it manually with the .valid() method.
you should use type submit, and then you can use the submitHandler in order to manage other things you want to do, like this:
$("#formSubscription").validate({
submitHandler: function(form) {
// do other things for a valid form
form.submit();
}
});
Take a loot at the documentation: https://jqueryvalidation.org/validate/
put an if in the SendSubscription function:
if (yourValidationDidntPass) {
//do whatever you want
}
else {
$.ajax({...});
}

React JS - unable to update text after IMG onclick event

I am trying to update the input text field ( Start time ) after the onClick={this.populateDate}. But I get the default value passed to the AJAX call to PHP.
https://jsfiddle.net/adwantgoutam/rg68Lyfk/
<?php header('Access-Control-Allow-Origin: *');
echo "Hello World";
$stime= $_GET['first_name'];
$etime= $_GET['last_name'];
$xyz= $_GET['start_time'];
echo "\n";
echo $stime;
echo "\n";
echo $etime;
echo "\n";
echo $xyz;
?>
Output :
Hello world!
John
Doe
03/11/2016 ( not the updated one after we click date through image onclick ).
var Hello = React.createClass({
render() {
return (
<form onSubmit={this.handleSubmit}>
<input value={this.state.first_name} onChange={this.setFirstName} placeholder="First name"/><br/>
<input value={this.state.last_name} onChange={this.setLastName} placeholder="Last name"/><br/>
<input value={this.state.start_time} onChange={this.setStartTime} placeholder="Start Time" id="demo1" name="stime"/>
<img src="https://rainforestnet.com/datetimepicker/sample/images2/cal.gif" onClick={this.populateDate}/><br/>
<button type="submit">Submit</button>
</form>
)
},
handleSubmit(event) {
event.preventDefault();
var data = this.state;
$.ajax({
type: "GET",
crossDomain: true,
url: "http://localhost:8082/PFT/login.php",
data: data,
success: function(data){
alert(data);
//$('#resultip').html(data);
},
error:function(data)
{
alert("Data sending failed");
}
});
},
populateDate(){
NewCssCal('demo1','yyyyMMdd','dropdown',true,'24',true);
},
getInitialState() {
return {
first_name: "John",
last_name: "Doe",
start_time: "03/11/2016",
};
},
setStartTime(event) {
console.log( event.target.value)
this.setState({start_time: event.target.value});
}
});
ReactDOM.render(
<Hello />,
document.getElementById('container')
);
I have attached my code in jsfiddle and above is the PHP script. I am not sure where exactly or how to process this. Any help is highly appreciated. Thanks.
I have gone through the date picker library you are using. To make this code work you'll have to add componentDidMount as follows.
componentDidMount(){
document.getElementById('demo1').onchange= this.setStartTime;
}
Then you need to modify you setStartTime function as follows
setStartTime() {
this.setState({start_time: document.getElementById('demo1').value});
}
Because the library is triggering change event programatically(as the value is being changed programmatically). Hence you'll not get the event object.
Though doing so will make your code work, my suggestion will be to use any react library for date-time picker(if you don't have the dependency to use this only) which provide proper configuration as per your requirement. Also try to use refs instead of document.getElement.... which is the react way of interacting with dom.

Calling inside a method another method ReactJS

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);
// <--
}
},
// ...
});

form is not refreshing after ajax submit and jquery validate

I have a form which I am submitting to my database, the form includes Jquery Validate plugin and ajax to submit.
The issue I am having is that after I click submit the form does not clear, it updates to database etc but I am just trying to clear the form and css highlight on the input field so someone could add a new record. Any help please?
CODE:
$(document).ready(function () {
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
$("#newform").validate({
//validation
debug: false,
rules: {
Name: {
required: true,
minlength: 3,
},
Surname: {
required: true,
},
},
submitHandler: function (form) {
$.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
$('#newform').reset();
});
}
});
});
HTML:
<form name="newform" id="newform" action="" method="POST">
<p>Name:</p>
<input type="text" id="pName" name="sName" /><br />
<p>Surname:</p>
<input type="date" id="pSName" name="pSName" /><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
You can use the following code to clear your form:
$('#newform').reset();
To focus on a specific <input> then you can use this after the reset() call:
$('input[name="sName"]').focus();
Try the following:
submitHandler: function (form) {
var jqxhr = $.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
});
jqxhr.done(function() {
$('#newform')[0].reset();
});
}
$('#newform').reset();
The above code will do. But reading your comments I see that you will have to make the ajax call synchronous. Because if its asynchronous, you will clear the form before the submit request is actually processed on server side. That's the reason you see a clear form before process.php
In the ajax call pass async also in the object parameter-
{url:'xyz.com',async:false}

Categories