I have create some personal project with wordpress + php + google firebase.
I want to execute function if Google firebase OTP verification is success.
Here is the code
function devsol_customer_form() { ?>
<form>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="number"><?php esc_html_e( 'Mobile Number', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="tel" class="woocommerce-Input woocommerce-Input--text input-text" name="number" id="number"/>
</p>
<div id="recaptcha-container"></div>
<button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="phoneAuth();">SendCode</button>
</form>
<br/>
<h1>Enter Verification code</h1>
<form>
<input type="text" id="verificationCode" placeholder="Enter verification code" class="woocommerce-Input woocommerce-Input--text input-text">
<button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="codeverify();">Verify code</button>
</form>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "*****",
authDomain: "*****",
databaseURL: "*****",
projectId: "*****",
storageBucket: "*****",
messagingSenderId: "*****",
appId: "*****"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script>
window.onload=function () {
render();
};
function render() {
window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier('recaptcha-container');
recaptchaVerifier.render();
}
function phoneAuth() {
//get the number
var number=document.getElementById('number').value;
//phone number authentication function of firebase
//it takes two parameter first one is number,,,second one is recaptcha
firebase.auth().signInWithPhoneNumber(number,window.recaptchaVerifier).then(function (confirmationResult) {
//s is in lowercase
window.confirmationResult=confirmationResult;
coderesult=confirmationResult;
console.log(coderesult);
alert("Message sent");
}).catch(function (error) {
alert(error.message);
});
}
function codeverify() {
var code=document.getElementById('verificationCode').value;
coderesult.confirm(code).then(function (result) {
alert("Successfully registered");
var user=result.user;
console.log(user);
}).catch(function (error) {
alert(error.message);
});
}
</script>
<?php }
add_action('woocommerce_after_customer_login_form', 'devsol_customer_form');
I want if user successfully verify the OTP then this function call in my php file. I am using function.php file in my wordpress theme.
function devsol_customer_auth() {
$user_phone = sanitize_text_field( $_POST['number'] );
if ( $user = get_user_by( 'login', $user_phone) ) {
$user_id = $user->ID;
$user_roles = $user->roles;
$user_role = array_shift($user_roles);
if ( $user_role === 'customer') {
if ( apply_filters( 'woocommerce_registration_auth_new_customer', true, $user_id ) ) {
wc_set_customer_auth_cookie( $user_id );
}
}
}
}
add_action('init', 'devsol_customer_auth');
Someone please help
You cannot directly call php function from javascript(JS) as JS runs on the client side like on the browser and your php file exists on the webserver.
In order to do something like that, you'll need to make request to the php file and pass parameter in the request(could be GET or POST).
A simple example of such could be
create a separate php file, lets say actions.php, that will be hit by the request.
make a request to the file from JS
E.g.
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
httpGet('www.yourSite.com/actions.php?phone=' + userPhoneNumber);
This should resolve your problem.
Related
This question already has answers here:
Are javascript's async functions actually synchronous?
(2 answers)
When does async function actually return a pending promise?
(1 answer)
Closed 18 days ago.
What's happening here?? the order of execution is commented.
dad() is async and returns a promise. shouldn't it be executed after console.log('faster')?
two() is async w/o await and still it's executes before console.log(5)
g() is awaited and executes as the last one?!
async function dad(){
async function g(){
return new Promise((a,b)=>{
setTimeout(() => {
console.log('im waiting') //4th
}, 2000)
a(6)
})
}
async function two(){
console.log(2) //1st
}
two()
await g()
console.log(5) //3rd
}
dad()
console.log('faster') //2nd
i'm trying to make an autocomplete form in django but when i run the page locally don´t run because don't find the url of the json, the idea of the autocomplete is that take information from x table and then the form post the information in y table
views.py
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'def
get_employee(request):
if is_ajax(request=request):
q = request.GET.get('term', '')
places = InfoTrabajadores.objects.filter(documento__icontains=q)
results = []
for pl in places:
place_json = {}
place_json['label'] = pl.state
results.append(place_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
and the jquery
$(document).ready(function() {
async function getCities(event, ui) {
//let url = '{% url ' / api / get_employees / ' %}';
let url = 'http://127.0.0.1:8000/api/get_employees/';
let results = await fetch(url);
let data = await results.json();
return data;
};
async function AutoCompleteSelectHandler(event, ui) {
let zipCode = await getCities();
$('#nombre').val(nombre[ui.item.value]);
$('#num_emergencia').val(num_emergencia[ui.item.value]);
$('#prov_salud').val(prov_salud[ui.item.value]);
$('#prov_salud_trabj').val(prov_salud_trabj[ui.item.value]);
$('#rh').val(rh[ui.item.value]);
};
$("#autoSuggest").autocomplete({
source: "{% url 'invitados' %}",
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
minLength: 2,
});
});
My test fails. The test is executed immediately, and the automation test doesn't wait to finish some of the actions.
I saw an issue with cucumber and nodejs, but I am unsure how to handle it.
Here is my step js class:
const { Given, When, Then } = require('#cucumber/cucumber');
Given("I visit the automation-practice-form page", async () => {
await page.goto("https://demoqa.com/automation-practice-form/");
});
When("I fill the form with correct data", async () => {
await page.fill('#firstName', 'Tester');
await page.fill('#lastName', 'Testerov');
await page.fill('#userEmail', 'testingemail#testemail.com');
await page.check('//*[#id="gender-radio-1"]/following-sibling::label');
await page.fill('#userNumber', '1232131231');
await page.click("#dateOfBirthInput");
await page.click('(//div[#role="option"])[1]');
await page.fill('#subjectsInput', 'Computer Science');
await page.keyboard.press("Enter");
await page.click('//*[#id="hobbies-checkbox-1"]/following-sibling::label');
await page.setInputFiles("#uploadPicture", "uploads/test-image.jpg");
await page.fill('#currentAddress', 'Test Address');
await page.click("#state");
await page.click('//*[#id="react-select-3-option-1"]', { force: true });
await page.click("#city");
await page.click('//*[#id="react-select-4-option-0"]');
});
When("click over the Submit button", async () => {
await page.click("#submit");
});
Then("I will verify that the data ware filled in correctly", async () => {
let name_actualResultElement = page.locator(
'//*[contains(text(),"Student Name")]/following-sibling::td'
);
});
and feature class:
Feature: Fill the form
As a user
I want to be able to fill the form
Scenario: Fill the form with valid data
Given I visit the automation-practice-form page
When I fill the form with correct data
When click over the Submit button
Then I will verify that the data ware filled in correctly
So, basically I am trying to send a request from my ajax post to my node js backend. Then I am trying to get the response back from the node js and update my view. Now, this is something that happens. Instead of just updating the resulttoken in the view, I can see in the console that whole html is loaded like a page. I am really confused. Please kindly point my error. This is what I tried so far.
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: <%=resulttoken%>;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
server
app.post("/home", function (req, res) {
var s = -1;
var t = -1;
var m = -1;
var phonenumber = req.body.phonenumber;
var review = req.body.review;
console.log(phonenumber);
fd.insertreview(phonenumber,review).then(function(v) {
if(v=="1") {
console.log("Your review has been inserted successfully");
s = md.getRand();
console.log("Unique number is",s);
fd.checkifuniquenumberexists(s).then(function(u){
if(u!="1"){
console.log("Unique number doesnt exist");
fd.inserttoken(s,phonenumber).then(function (p) {
if(p=="1"){
console.log("Token has been inserted successfully");
res.render('trial',{"resulttoken":s});
}
})
}
});
}
});
});
This is what loads on the console log
info <!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: 35055;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
The issue is this line
res.render('trial',{"resulttoken":s});
You're returning the entire page as your response, if you just need the token you can return this as part of a JSON response e.g.
res.status(200).json({ token: s });
then at the client
$.post('/home', { phonenumber, review }, res => {
// use res.token
console.log(`Token: ${res.token}`);
})
.fail(console.error);
I have a page with multiple elements and some jQuery code to send when one of the forms are clicked.
form:
<form method="post" action="">
{% csrf_token %}
<input id="vote" name="vote" type="hidden" value="up">
<input id="post_id" name="post_id" type="hidden" value="{{submission.id}}"/>
<input type="submit" class="arrowup" value=""/>
</form>
jQuery javascript:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/button_form/",
dataType: "json",
data : {
post_id : encodeURIComponent(document.getElementById('post_id').value),
vote : encodeURIComponent(document.getElementById('vote').value),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#result').html( 'post id: ' + json.post_id + ' voted: ' + json.up_or_down);
},
error: function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
The first button works as expected and gets the server's json response, however all the other buttons don't work.
I'm led to think this might be because there are multiple vote and post_id form inputs, but can't figure out an alternative strategy, or if that's really the issue.
Any help is greatly appreciated.
Thanks
I think you can iterate through all your forms and submit each one separetely on their submit event:
$("#formID").submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
// All other ajax code for submitting form data
});
});