javascript combine two with IF - if-statement

I am trying to combine two javascripts to one using IF.
I want IF script1 is True to run only script1.
And IF script1 is False to run script2.
Script1= Check all field with "required" if empty in a contact form.
Script2= Send email using ajax.
Script1
$('document').ready(function () {
$('form#contact-form').submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
});
Script2
$('document').ready(function () {
$('form#contact-form').submit(function () {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});

This script should work for you.
$('document').ready(function() {
$('form#contact-form').submit(function (e) {
var valid = true;
var ref = $(this).find("[required]");
$(ref).each(function(){
if ($(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
valid = false;
return false;
}
});
if (valid){
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
}
});
});
Combined both script and added/ introduced "valid" variable to validate if 'required' fields are valid.

Related

JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?

I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument.
How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ?
The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e, data) {
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
context: 'hello',
data: formData,
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
xhr = null;
}
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
//alert("File is uploaded");
} else {
}
};
xhr.onerror = () => {
};
xhr.setRequestHeader('Content-Type', file.type);
//data.submit();
});
});
},
If the $this = $(this) is defined prior to the $.each loop :
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) { ...
Then the following can be used to access the data in the parent function
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);

Facing error in insertion while using webservices and ajax jquery

WHEN I FILL THE FORM IN HTML,I FACE ERROR OF 500. MY WEBSERVICE IS NOT WORKING. WHEN I COPYPASTE URL AND OPEN IN NEW TABLE THEN IT SHOWS BELOW ERROR.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void addNewUser(string name,string address,string email, string phoneno, string pin)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
string Message = "";
try
{
using (MySqlConnection connection = new MySqlConnection(DBconnect.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO users(name,address,email,phoneno,pin) VALUES(#name,#address,#email,#phoneno,#pin)", connection);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phoneno", phoneno);
cmd.Parameters.AddWithValue("#pin", pin);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
Message = "New User is added Successfully.";
}
catch (Exception ex)
{
Message = "Not Added";
}
var JSonData = new
{
Message = Message
};
HttpContext.Current.Response.Write(ser.Serialize(JSonData));
}
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdduser").on('click', function (e)
{
e.preventDefault();
var All_users = {};
All_users.name = $('#name').val();
All_users.address = $('#address').val();
All_users.email = $('#email').val();
All_users.phoneno = $('#phoneno').val();
All_users.pin = $('#pin').val();
var jsonData = JSON.stringify({
All_users: All_users
});
$.ajax({
type: "POST",
url: "http://localhost/WebApi/WebService.asmx?op=addNewUser",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var result = response.d;
if (result == "success") {
$("#msg").html("New record addded successfully :)").css("color", "green");
}
$("#name").val("");
$("#address").val("");
$("#email").val("");
$("#phoneno").val("");
$("#pin").val("");
}
function OnErrorCall(response) {
$("#msg").html("Error occurs :(").css("color", "red");
}
});
});
</script>
*
System.InvalidOperationException: Missing parameter: name. at
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection
collection) at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
*
I tried reproducing your case.
The problem is UseHttpGet = true, change to UseHttpGet = false and also check that attribute in class [System.Web.Script.Services.ScriptService]
and update your AJAX call by WebService.asmx/addNewUser like this, it worked
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<button id="btnAdduser">Test</button>
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdduser").on('click', function (e)
{
e.preventDefault();
var All_users = {};
All_users.name = "Hien";
All_users.address = "Test";
All_users.email = "Test";
All_users.phoneno = "Test";
All_users.pin = "123";
var jsonData = JSON.stringify({
data: All_users
});
$.ajax({
type: "POST",
url:
"http://localhost/WebApi/WebService.asmx/addNewUser",
data: JSON.stringify(All_users),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var result = response.d;
if (result == "success") {
$("#msg").html("New record addded successfully :)").css("color", "green");
}
$("#name").val("");
$("#address").val("");
$("#email").val("");
$("#phoneno").val("");
$("#pin").val("");
}
function OnErrorCall(response) {
$("#msg").html("Error occurs :(").css("color", "red");
}
});
});
</script>

jsZip - execute generateAsync after Ajax post success

I have number if files to be added in the zip file. some are optional (user choice). I like to execute the generateAsync once all required files Ajax post is successful.
I tried to place a check but its not working.
SAMPLE CODES:
var requestCSS;
var StyleFileData;
var requestAnimatedJS;
var AnimatedScriptData;
function getAllFiles(complileComplete){
requestCSS = $.ajax({
url: 'css/styles.css',
type: "GET",
contentType: "text/css",
mimeType:'text/plain; charset=x-user-defined',
success: function (data){
StyleFileData = data;
}
});
if(animatedBG){
requestAnimatedJS = $.ajax({
url: 'js/animated.js',
type: "GET",
contentType: "text/javascript",
mimeType:'text/plain; charset=x-user-defined',
//async: false,
success: function (data){
AnimatedScriptData = data;
}
});
} else {
requestAnimatedJS = '';
}
}
$('#saveProject').on('click', function(){
getAllFiles(complileComplete);
if(complileComplete === true) {
var zip = new JSZip();
var jsFiles;
var cssFiles;
zip.file("index.html", fullHTML);
jsFiles = zip.folder("js");
cssFiles = zip.folder("css");
requestCSS.done( function( data ) {
cssFiles.file("styles.css", data, { binary: true });
});
if(animatedBG){
requestAnimatedJS.done( function( data ) {
jsFiles.file("particles.js", data, { binary: true });
});
}
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "Sample.zip");
});
}
});
No server side or node.js is involved.

How to POST data for evaluation in middleware in loopback?

I want to use custom API to evaluate data which are posted by applications but remote methods are not accepted in middleware in loopback
module.exports = function () {
const http = require('https');
var request = require('request');
var { Lib } = require('Lib');
var lib = new Lib;
verification.checkID = function (ID, cb) {
cb(null, 'ID is :' + ID);
}
verification.remoteMethod('greet', {
accepts: {
arg: 'ID',
type: 'string'
},
returns: {
arg: 'OK',
type: 'string'
}
});
module.exports = function () {
const http = require('https');
var request = require('request');
var { Lib } = require('Lib');
var lib = new Lib;
verification.checkID = function (ID, cb) {
cb(null, 'ID is :' + ID);
}
verification.remoteMethod('greet', {
'http': { // add the verb here
'path': '/greet',
'verb': 'post'
},
accepts: {
arg: 'ID',
type: 'string'
},
returns: {
arg: 'OK',
type: 'string'
}
});
Update
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
router.get('/ping', function(req, res) { // your middle ware function now you need to call the next() here
res.send('pong');
});
server.use(router);
};
To evaluate is something i am not getting please check this link too Intercepting error handling with loopback
Regarding to fallowing question How to make a simple API for post method?
I find my solution in fallowing way:
module.exports = function(server) {
const https = require('https');
var request = require('request');
return function verification(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
var request;
var response;
var body = '';
// When a chunk of data arrives.
req.on('data', function (chunk) {
// Append it.
body += chunk;
});
// When finished with data.
req.on('end', function () {
// Show what just arrived if POST.
if (req.method === 'POST') {
console.log(body);
}
// Which method?
switch (req.method) {
case 'GET':
Verify url and respond with appropriate data.
handleGet(req, res);
Response has already been sent.
response = '';
break;
case 'POST':
// Verify JSON request and respond with stringified JSON response.
response = handlePost(body);
break;
default:
response = JSON.stringify({ 'error': 'Not A POST' });
break;
}
// Send the response if not empty.
if (response.length !== 0) {
res.write(response);
res.end();
}
// Paranoid clear of the 'body'. Seems to work without
// this, but I don't trust it...
body = '';
});
// If error.
req.on('error', function (err) {
res.write(JSON.stringify({ 'error': err.message }));
res.end();
});
//
};
function handlePost(body) {
var response = '';
var obj = JSON.parse(body);
// Error if no 'fcn' property.
if (obj['fcn'] === 'undefined') {
return JSON.stringify({ 'error': 'Request method missing' });
}
// Which function.
switch (obj['fcn']) {
// Calculate() requres 3 arguments.
case 'verification':
// Error if no arguments.
if ((obj['arg'] === 'undefined') || (obj['arg'].length !== 3)) {
response = JSON.stringify({ 'error': 'Arguments missing' });
break;
}
// Return with response from method.
response = verification(obj['arg']);
break;
default:
response = JSON.stringify({ 'error': 'Unknown function' });
break;
}
return response;
};
function verification(arg) {
var n1 = Number(arg[0]);
var n2 = Number(arg[1]);
var n3 = Number(arg[2]);
var result;
// Addem up.
result = n1 + n2 + n3;
// Return with JSON string.
return JSON.stringify({ 'result': result });
};
};

The changed value is not reflecting on the input field in ReactJS, TestUtils

I am using ReactJs and Mocha and trying few unit tests. I have two mandatory form fields First Name and Last Name. I am trying to test the validation where if only one field is entered, the other field displays the missing value validation error.
Below code simulates the changes to the value and simulates the form submit.
TestUtils.Simulate.change(firstNameElement , {target: {value: 'Joe'}});
TestUtils.Simulate.submit(formElement)
The changed value is reflected in the event handlers on First Name. But, not in the test. So, both the fields display missing value validation failing my test.
What I could be doing wrong here?
Below are code:
//NameForm.jsx
'use strict';
var React=require('react')
var forms = require('newforms')
var NameForm = forms.Form.extend({
firstName: forms.CharField({maxLength: 100, label: "First name(s)"}),
lastName: forms.CharField({maxLength: 100, label: "Last name"}),
cleanFirstName(callback) {
callback(null)
},
render() {
return this.boundFields().map(bf => {
return <div className={'form-group ' + bf.status()}>
<label className="form-label" htmlFor={bf.name}>
<span className="form-label-bold">{bf.label}</span>
</label>
{bf.errors().messages().map(message => <span className="error-message">{message}</span>)}
<input className="form-control" id={bf.name} type="text" name={bf.name} onChange = {this.onChangeHandler}/>
</div>
})
}
, onChangeHandler: function(e){
console.log("onchnage on input is called ----- >> " + e.target.value)
}
})
module.exports = {
NameForm
}
Here is NamePage.jsx:
'use strict';
var React = require('react')
var {ErrorObject} = require('newforms')
var superagent = require('superagent-ls')
var {API_URL} = require('../../constants')
var {NameForm} = require('./NameForm')
var NamePage = React.createClass({
contextTypes: {
router: React.PropTypes.func.isRequired
},
propTypes: {
data: React.PropTypes.object,
errors: React.PropTypes.object
},
statics: {
title: 'Name',
willTransitionTo(transition, params, query, cb, req) {
if (req.method != 'POST') { return cb() }
superagent.post(`${API_URL}/form/NameForm`).send(req.body).withCredentials().end((err, res) => {
if (err || res.serverError) {
return cb(err || new Error(`Server error: ${res.body}`))
}
if (res.clientError) {
transition.redirect('name', {}, {}, {
data: req.body,
errors: res.body
})
}
else {
transition.redirect('summary')
}
cb()
})
}
},
getInitialState() {
return {
client: false,
form: new NameForm({
onChange: this.forceUpdate.bind(this),
data: this.props.data,
errors: this._getErrorObject()
})
}
},
componentDidMount() {
this.setState({client: true})
},
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
var errorObject = this._getErrorObject(nextProps.errors)
this.refs.nameForm.getForm().setErrors(errorObject)
}
},
_getErrorObject(errors) {
if (!errors) { errors = this.props.errors }
return errors ? ErrorObject.fromJSON(errors) : null
},
_onSubmit(e) {
e.preventDefault()
var form = this.state.form
form.validate(this.refs.form, (err, isValid) => {
if (isValid) {
this.context.router.transitionTo('name', {}, {}, {
method: 'POST',
body: form.data
})
}
})
},
render() {
return <div>
<h1 className="heading-large">Your name</h1>
<form action='name' method="POST" onSubmit={this._onSubmit} ref="form" autoComplete="off" noValidate={this.state.client}>
{this.state.form.render()}
<button type="submit" className="button">Next</button>
</form>
</div>
},
})
module.exports = NamePage
Here is NameTest.js :
//NameTest.js
var React = require('react')
var ReactAddons = require('react/addons')
var TestUtils = React.addons.TestUtils
var InputFieldItem = require('../../src/page/name/NamePage')
describe('Name page component', function(){
var renderedComponent;
before('render element', function() {
console.log("*** in before")
renderedComponent = TestUtils.renderIntoDocument(
<InputFieldItem />
);
});
it('Only First Name entered should display one error message', function() {
renderedComponent = TestUtils.renderIntoDocument(
<InputFieldItem />
);
var formElement = TestUtils.findRenderedDOMComponentWithTag(renderedComponent, 'form').getDOMNode()
var firstNameElement = TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input')[0].getDOMNode()
var lastNameElement = TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input')[1].getDOMNode()
var buttonElement = TestUtils.findRenderedDOMComponentWithTag(renderedComponent, 'button').getDOMNode()
TestUtils.Simulate.change(firstNameElement , {target: {value: 'Joe'}});
TestUtils.Simulate.submit(formElement)
var errorSpans = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'error-message')
console.log("First name value is :|"+ firstNameElement.value + "|")
expect (errorSpans.length).to.equal(1)
})
});