I have the following the code on aap.js with a route to '/bio_post'. I'm trying to post some text based on my website using jquery ajax. The problem I'm having is that jquery picks up the objects that come from '/bio_post' as undefined. I was wondering if you guys can point me in the right direction. Thank you for your time and effort.
app.post('/bio_post', function (req, res) {
// Get user input value
let update_bio = req.body.user_bio;
// Check if the input isn't empty
if(update_bio !== "") {
// Connect to mysql database
mysql_connection.query("UPDATE users SET user_bio = ? WHERE id = ?", [update_bio, session_id], function (err, rows) {
if (err) {
let obj_error = {err: err};
res.send(obj_error.err);
} else {
// Check if the post was successfully inserted into the database
if (rows.changedRows === 1) {
let id = {id: session_id};
res.redirect("/profile/" + JSON.stringify(id.id));
console.log("bio post id is: " + JSON.stringify(id.id));
/*let msg_success = {id: session_id, success_msg: 'Bio successfully inserted!'};
res.send(msg_success);*/
} else {
let id = {id: session_id};
let msg_error = {msg_err: 'No changes were made to your bio.'};
res.send(JSON.stringify(msg_error.msg_err));
console.log("bio post id is: " + JSON.stringify(id.id));
}
}
});
}else{
//res.render("settings", {u_id: session_id, logged_in_user: session_username, bio: '', bio_msg: "Bio field cannot be empty."});
res.send("Bio field is empty");
}
});
Below is the code for jquery.
/**Set up URL route variable**/
let url = '/bio_post';
/**Set up Ajax callback**/
$.ajax({
url: url,
type: 'POST',
data: {user_bio: user_bio.val()},
success: function (data) {
if(data.msg_err){
success_bio_handler.hide();
error_bio_handler.fadeIn().text(data.msg_err).delay(5000).fadeOut();
} else {
error_bio_handler.hide();
//success_bio_handler.fadeIn().text(data.success_msg).delay(5000).fadeOut();
//window.location.href = '/profile/' + data.id;
console.log(data.id); /***COMES OUT AS UNDEFINED****/
}
}
});
Then lastly, is the html file.
<!--ADD OR UPDATE BIO-->
<div id="add_update_bio_title"><strong>Add or Update Bio</strong></div>
<div id="add_update_bio_panel">
<form id="frm_add_update_bio" action="/bio_post" method="post"><br />
<div class="py-5 w-100">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<p id="error_bio_handler" class="alert-danger collapse">Error</p><!--jQuery error handler-->
<p id="success_bio_handler" class="collapse" style="background-color: #00AA88; color: white;"></p><!--jQuery success handler-->
<form class="">
<div class="form-group">
<!--Check if user has entered a bio-->
<div class="alert-danger"><%= typeof bio_msg !== 'undefined' ? bio_msg : '' %></div><br />
<% if (bio){%>
<textarea class="form-control" rows="5" id="user_bio" name="user_bio" placeholder="Write a little something about yourself"><%- bio%></textarea>
<%} else{%>
<textarea class="form-control" rows="5" id="user_bio" name="user_bio" placeholder="Write a little something about yourself"></textarea>
<%}%>
</div>
<div class="form-group"></div>
<div class="form-group"></div>
<button id="btnSubmitBio" type="button" class="btn btn-primary">Add or Update Bio</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
</div>
</form>
</div>
<!--END ADD OR UPDATE BIO-->
Related
I have a php (Laravel 7) website that uses Stripe.js to accept credit card payments. The integration usually works nicely, but from time to time, I have some customers, who are not able to make a payment. There is no error message, all I know from the customers is something like this:
"I entered the card details, clicked "Pay" and then a white field and nothing..."
On the stripe backend, I see the payment with status payment "Incomplete" and the "Customer has not entered its payment method". I believe this means that the customer came to the payment page, but has not (could not?) finished the payment for some reason.
Please see some code excerpts below. The first code shows how I create a payment intent when the payment page is loaded. The second one shows the payment form and js code to make the payment. My suspicion is that somehow the js code breaks down for some customers...
Any ideas why this is not working for some customers or how I could debug the root-cause?
Thanks,
W.
GNGBookingController.php:
function show_step4($id){
// Create and send payment intent
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$idstr = '[T#' . sprintf('%04d', $tour->id) . ']';
try{
$intent = \Stripe\PaymentIntent::create([
'amount' => round($tour->fees->plat_fee * 100),
'currency' => 'eur',
'payment_method_types' => ['card'],
'description' => $idstr,
]);
}
catch(\Exception $e) {
GNGLogger::qlog('Failed to create payment intent. ' . $e->getFile() . ' ' . $e->getLine() . $e->getMessage(), GNGLogType::Error);
redirect(route('office.' . app::getLocale() . '.crash.show'));
}
return view('backoffice.booking.ver2.show-step4', [
'tour' => $tour,
'clientSecret' => $intent->client_secret,
'date' => $date,
'time' => $time,
]);
}
show-step4.blade.php:
#extends('backoffice.layouts.guest')
#section('content')
<script src="https://js.stripe.com/v3/"></script>
<div class="row">
<div class="col-sm-1 col-md-2 col-lg-3 col-xl-4">
</div>
<div class="col">
<h3>{{__('Advance Payment')}}</h3>
<form id="payment-form" method="post" data-secret="{{$clientSecret}}">
<input type="hidden" name="token" />
<div id="payment-form-holder" class="my-4 p-3 border rounded shadow" style="background-color: lightgrey">
#csrf
<div class="form-group">
<input type="hidden" class="form-control" name="ID" id="ID" value="{{$tour->id}}">
</div>
<div class="form-group">
<label>{{__('Card Number')}}</label><br>
<div id="card-number">
</div>
</div>
<div class="form-row">
<div class='col'>
<div class="form-group">
<label>{{__('Expiry Date')}}</label><br>
<div id="card-expiry">
</div>
</div>
</div>
<div class='col'>
<label>{{__('Security Code')}}</label><br>
<div class="form-group">
<div id="card-cvc">
</div>
</div>
</div>
</div>
<!-- We'll put the error messages in this element -->
<div id="card-errors" role="alert"></div>
<div class="form-row my-3" style="flex-wrap: nowrap">
<div class="spinner-border text-danger" id="spinner" role="status" style="display: none;">
</div>
<div id="spinner-text" class="mx-2" style="display: none;">
{{__('Please wait. This can take up to a minute...')}}
</div>
</div>
<p id="card-error" role="alert"></p>
<p id="result-message" class="result-message" style="display: none;">
{{__('Payment succeeded!')}}
</p>
<div class="form-row">
<input type="submit" id="pay" name="pay" class="btn btn-primary gng-action-button mr-3 mb-3" style="min-width: 100%" value="{{__('Pay :platFee €', ['platFee' => $tour->fees->plat_fee])}}" >
</div>
</div>
<input type="submit" id="back" name="back" class="btn btn-secondary gng-action-button mr-3 mb-3" value="{{__('Back')}}" >
</form>
</div>
<div class="col-sm-1 col-md-2 col-lg-3 col-xl-4">
</div>
</div>
#endsection
#section('scripts')
<script>
// Create a Stripe client
var stripe = Stripe('{{env('STRIPE_KEY')}}');
// Set up Stripe.js and Elements to use in checkout form
var elements = stripe.elements();
var style = {
base: {
color: "#32325d",
fontSize: "18px",
}
};
var classes = {
base: 'form-control',
};
var cardNumberElement = elements.create('cardNumber', {
style: style,
classes: classes,
});
cardNumberElement.mount('#card-number');
var cardExpiryElement = elements.create('cardExpiry', {
style: style,
classes: classes,
});
cardExpiryElement.mount('#card-expiry');
var cardCvcElement = elements.create('cardCvc', {
style: style,
classes: classes,
});
cardCvcElement.mount('#card-cvc');
document.querySelector('#payment-form').addEventListener('submit', function(e) {
if (e.submitter.name == 'pay') {
e.preventDefault();
loading(true);
stripe
.confirmCardPayment('{{$clientSecret}}', {
payment_method: {
card: cardNumberElement,
billing_details: {
name: '{{$tour->guest->name}}'
}
}
})
.then(function(result) {
if (result.error) {
// Show error to your customer
showError(result.error.message);
} else {
// The payment succeeded!
orderComplete(result.paymentIntent.id);
stripe.createToken(cardNumberElement, options).then(submitToken);
}
});
var options = {
//address_zip: document.getElementById('postal-code').value,
};
}
});
function submitToken(result) {
var form = document.querySelector('#payment-form');
form.querySelector('input[name="token"]').setAttribute('value', result.token.id);
form.submit();
}
/* ------- UI helpers ------- */
// Shows a success message when the payment is complete
var orderComplete = function(paymentIntentId) {
loading(false);
document.querySelector(".result-message").style.display = 'flex';
document.querySelector("#pay").disabled = true;
document.querySelector("#back").disabled = true;
};
// Show the customer the error from Stripe if their card fails to charge
var showError = function(errorMsgText) {
loading(false);
var errorMsg = document.querySelector("#card-error");
errorMsg.textContent = errorMsgText;
setTimeout(function() {
errorMsg.textContent = "";
}, 4000);
};
// Show a spinner on payment submission
var loading = function(isLoading) {
if (isLoading) {
// Disable the button and show a spinner
document.querySelector("#pay").disabled = true;
document.querySelector("#back").disabled = true;
document.querySelector("#spinner").style.display = 'flex';
document.querySelector("#spinner-text").style.display = 'flex';
document.querySelector("#pay").style.display = 'none';
document.querySelector("#back").style.display = 'none';
} else {
document.querySelector("#pay").disabled = false;
document.querySelector("#back").disabled = false;
document.querySelector("#spinner").style.display = 'none';
document.querySelector("#spinner-text").style.display = 'none';
document.querySelector("#pay").style.display = 'inline-block';
document.querySelector("#back").style.display = 'inline-block';
}
};
</script>
#endsection
If it is only breaking for some customers, I suspect this is a device/browser compatibility issue. Whenever this happens, be sure to ask what device and browser they are using when submitting payment. Then, you can verify if they are using a stripe.js compatible browser. If they are using a stripe.js compatible browser, my recommendation is to install whatever browser they are using and test your flow (while inspecting the developer console for errors).
I'm using an input box, when the search button is pressed I want to see if the searched term is an existing directory within the directory that the index.html file is stored within. Here's the code so far:
function searchWebs () {
var searchedTermRaw = document.getElementById('searchBox').value;
var searchedTerm = searchedTermRaw.toUpperCase();
if (searchedTerm == "") {
return;
} else {
if (searchedTerm == "NUMI" || searchedTerm == "ELMDON PM") {
document.getElementById('searchFor').innerHTML = "Search results for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "";
} else {
document.getElementById('searchFor').innerHTML = "No search results were found for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "Please use the ID provided within the email Netwal sent you, if you have not been sent an email with the ID, your website isn't ready for viewing/testing yet.";
}
}
}
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-sm-12">
<input type="text" class="form-control input-lg" id="searchBox" placeholder="Website ID">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br>
<a class="btn btn-lg btn-primary col-lg-12" onclick="searchWebs();">Search</a>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 id="searchFor"></h1>
<p id="searchForDetails"></p>
</div>
</div>
</div>
</div>
I want to replace the if statement for checking if the search term is NUMI or ELMDON PM with checking if the directory exists.
Use this method isAvailable(url) and pass the path or searchedTerm
Make sure to maintain the cross-origin policy.
I have added baseUrl as https://stacksnippets.net/ for that issue.
var baseUrl = "https://stacksnippets.net/";
function isAvailable(url) {
url = baseUrl + url;
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
try {
http.send();
} catch (err) {
return false;
}
return http.status != 404;
}
EXAMPLE:
I tried term js which will produce url https://stacksnippets.net/js
I am afraid the example will not work due to cross-origin and mixed-content errors but this approach should work in your case.
You can check for your resource in your domain by changing the baseUrl
SNIPPET
function searchWebs() {
var searchedTermRaw = document.getElementById('searchBox').value;
var searchedTerm = searchedTermRaw.toUpperCase();
if (searchedTerm == "") {
return;
} else {
if (isAvailable(searchedTerm)) {
document.getElementById('searchFor').innerHTML = "Search results for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "";
} else {
document.getElementById('searchFor').innerHTML = "No search results were found for '" + searchedTermRaw + "'.";
document.getElementById('searchForDetails').innerHTML = "Please use the ID provided within the email Netwal sent you, if you have not been sent an email with the ID, your website isn't ready for viewing/testing yet.";
}
}
}
var baseUrl = "https://stacksnippets.net/";
function isAvailable(url) {
url = baseUrl + url;
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
try {
http.send();
} catch (err) {
return false;
}
return http.status != 404;
}
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-sm-12">
<input type="text" class="form-control input-lg" id="searchBox" placeholder="Website ID">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<br>
<a class="btn btn-lg btn-primary col-lg-12" onclick="searchWebs();">Search</a>
</div>
</div>
</div>
</div>
<div class="section">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 id="searchFor"></h1>
<p id="searchForDetails"></p>
</div>
</div>
</div>
</div>
I have my database with Firebase and now I'm trying to do a newsletter subscription, but I want to save the subscribers in Mailchimp and Firebase.
Mailchimp connection works perfectly, but I don't know how to integrate the Firebase connection in the same js.
This is what I have in the <head> tag
<script type="text/javascript">
angular.module("productLaunch", ["mailchimp"])
</script>
This in the <body> tag
<body ng-app="productLaunch"><section class="container-fluid subscribe" ng-controller="MailchimpSubscriptionCtrl">
<div class="wrapper">
<!-- Let us your email -->
<div class="">
<h2 class="text-center">Subscribe to our news</h2>
<div class="col-lg-4 col-lg-offset-4 mt centered">
<h4 ng-hide="mailchimp.result ==='success'">LET ME KNOW WHEN YOU LAUNCH</h4>
<h4 ng-show="mailchimp.result ==='success'">THANKS FOR SIGNING UP!</h4>
</div>
<form class="form-inline" role="form" ng-hide="mailchimp.result === 'success'">
<input class="hidden" type="hidden" ng-model="mailchimp.username" ng-init="mailchimp.username='stopappweb'">
<input class="hidden" type="hidden" ng-model="mailchimp.dc" ng-init="mailchimp.dc='us12'">
<input class="hidden" type="hidden" ng-model="mailchimp.u" ng-init="mailchimp.u='3eb39be3ad857e60b357fdb5e'">
<input class="hidden" type="hidden" ng-model="mailchimp.id" ng-init="mailchimp.id='520ddfd981'">
<div class="form-group">
<label class="sr-only" for="mailchimp.email">Email address</label>
<input type="email" class="form-control" id="mailchimp.email" placeholder="Enter email" ng-model="mailchimp.email">
</div>
<button type="submit" class="btn btn-info" ng-disabled="MailchimpSubscriptionForm.$invalid" ng-click="addSubscription(mailchimp)" type="submit" value="SIGN UP" disabled="disabled">Submit</button>
<div ng-show="mailchimp.result === 'error'">
<p ng-bind-html="mailchimp.errorMessage" class="error"></p>
</div>
</form>
</div>
</div>
</section>
And this is my JS:
'use strict';
angular.module('mailchimp', ['ng', 'ngResource', 'ngSanitize'])
.controller('MailchimpSubscriptionCtrl', ['$log', '$resource', '$scope',
function ($log, $resource, $scope) {
$scope.myData = new Firebase("https://stopappwebpre.firebaseio.com/subscriptors");
// Handle clicks on the form submission.
$scope.addSubscription = function (mailchimp) {
var actions,
MailChimpSubscription,
params,
url;
$scope.myData.push({mailchimp.email:$scope.mailchimp.email});
// Create a resource for interacting with the MailChimp API
url = 'http://' + mailchimp.username + '.' + mailchimp.dc + '.list-manage.com/subscribe/post-json';
params = {
'EMAIL': mailchimp.email,
'FNAME': mailchimp.fname,
'LNAME': mailchimp.lname,
'c': 'JSON_CALLBACK',
'u': mailchimp.u,
'id': mailchimp.id
};
actions = {
'save': {
method: 'jsonp'
}
};
MailChimpSubscription = $resource(url, params, actions);
// Send subscriber data to MailChimp
MailChimpSubscription.save(
// Successfully sent data to MailChimp.
function (response) {
// Define message containers.
mailchimp.errorMessage = '';
mailchimp.successMessage = '';
// Store the result from MailChimp
mailchimp.result = response.result;
// Mailchimp returned an error.
if (response.result === 'error') {
if (response.msg) {
// Remove error numbers, if any.
var errorMessageParts = response.msg.split(' - ');
if (errorMessageParts.length > 1)
errorMessageParts.shift(); // Remove the error number
mailchimp.errorMessage = errorMessageParts.join(' ');
} else {
mailchimp.errorMessage = 'Sorry! An unknown error occured.';
}
}
// MailChimp returns a success.
else if (response.result === 'success') {
mailchimp.successMessage = response.msg;
}
},
// Error sending data to MailChimp
function (error) {
$log.error('MailChimp Error: %o', error);
}
);
}; }]);
Thank you so much for your help.
<form name="LPform" novalidate>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">Email ID</label>
<input class="mob-adj-inpbx " type="email" name="uemail" ng-model="useremail" placeholder=" me#example.com" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.uemail.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.uemail.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.uemail.$dirty && allow_Invalid">
</div>
</div>
<div class="form-row clearfix">
<label class="lbl-fld" style="margin-left: 12%;width:20%;">PASSWORD</label>
<input class="mob-adj-inpbx" type="password" name="upassword" ng-model="userpassword" placeholder=" password" ng-required="true"/>
<div class="valid-chk validation-loginpopup" ng-show="LPform.upassword.$dirty && allow_Invalid">
<i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[LPform.upassword.$valid]" class="icon-correct"></i>
</div>
<div class="error-prompt" ng-show="LPform.upassword.$dirty && allow_Invalid">
</div>
</div>
<div id="server_message" class="form-row clearfix basic-error-msg-loginpopup" ng-show="server_message">
{{server_message}}
</div>
<div class="btn-container clearfix mobile-adj" style="margin-left:17.2%;">
<div class="btn-wrap btn-loginpopup">
<input style="max-height:40px;width:121%;" type="submit" name="commit" value="LOGIN" ng-click="login_request()"/>
</div>
</div>
</form>
This part is displayed to the user and the inputs are validated using angular validations. All validations are working fine.
$scope.login_request = function(){
if(LPform.useremail.$valid && LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$http({
method: 'POST',
url: '/users/home_login',
data: {email: $scope.useremail, password: $scope.userpassword}
}).success(function (response) {
console.log(response);
window.location = response.location;
}).error(function (response) {
console.log(response);
$scope.server_message = response.server_message;
});
}
else if(!LPform.useremail.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid email.";
}
else if(!LPform.userpassword.$valid) {
$scope.allow_Invalid = "true";
$scope.server_message = "Please enter valid password.";
}
else{
$scope.allow_Invalid = "true";
$scope.server_message = "Request Failed.";
}
};
This part is in javascript file where I want to use the validations to decide whether to send a request to the server or not. The conditions I have used in the if else clause is not working, which I randomly tried btw. I am aware that I can disable Login button, however, I don't want to implement this that way.
I believe your problem is that the form name is bound to $scope and isn't a global variable.
In controller change
LPform
To
$scope.LPform
I have created a Ajax form to handle the errors in my login form, but instead of showing errors in the form area, it directs me to another page with the json error response
<div class="container-fluid bg-primary" id="login">
<div class="row">
<div class="col-lg-3 text-center">
</div>
<div class="col-lg-6 text-center">
<h1> </h1><h3> </h3>
<h2 class="section-heading">Login to your profile</h2>
<hr>
</div>
<div class="col-lg-3 text-center">
</div>
<h2> </h2>
<h2> </h2>
<h2> </h2>
</div>
<div class="col-md-4 col-md-offset-4 ">
<form id='loginform' action='/users/login/' method='post' accept-charset='UTF-8'>
{% csrf_token %}
<fieldset >
<div class="form-group">
<input type="text" name="mobile_number" id="mobile_number" tabindex="1" class="form-control" placeholder="Mobile Number" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Enter Password">
</div>
</fieldset>
<button type="submit" class="btn btn-primary btn-xl btn-block">LOG IN</button><br><br>
<span class="login-error"></span>
<h1> </h1><h1> </h1>
</form>
</div>
My ajax code
$("#loginform").on('submit', function(event) {
event.preventDefault();
alert("Was preventDefault() called: " + event.isDefaultPrevented());
console.log("form submitted!");
var url = "/users/login-ajax/";
$.ajax({
type: "POST",
url:url,
data: $("#loginform").serialize(),
success: function(data)
{
console.log(data);
var result = JSON.stringify(data);
if(result.indexOf('errors')!=-1 ){
console.log(data);
if(data.errors[0] == "Mobile number and password don't match")
{
$('.login-error').text("Mobile number and password don't match");
}
else if(data.errors[0] == "Entered mobile number is not registered")
{
$('.login-error').text("Entered mobile number is not registered");
}
}
else
{
window.open("/users/profile/");
}
//var result = JSON.stringify(data);
// console.log(result);
}
})
});
My code for the action in views.py
def login(request):
if request.method == 'POST':
mobile_number = request.POST.get('mobile_number', '')
password = request.POST.get('password', '')
data = {}
user_queryset = User.objects.filter(mobile_number=mobile_number)
if len(user_queryset) == 0:
data['error'] = []
data['error'].append("Entered mobile number is not registered")
# return JsonResponse(data)
elif len(user_queryset) == 1:
email = user_queryset[0].email
user = auth.authenticate(email=email, password=password)
if user is not None:
auth.login(request, user)
else:
data['error'] = []
data['error'].append("Mobile number and password don't match")
return JsonResponse(data)