autocomplete form in django - javascript

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

Related

Shouldn't async functions always execute as the last ones? [duplicate]

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

NodeJS Cucumber test are executed with not wait

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

How to call php function if javascript condition true

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.

search box result == Json result

I have a Node.js server that reads a JSON file and there are a lot of information in it. One of them is ID of a person, I have a search box in my HTML page I wanna right a jquery method(ajax required) for the client side to find if the ID that the user put in the search box is the same as the ID in JSON, if it is I wanna return some information about that person, let's say name and username of the user.
Note: I am 100% sure that my server.js file works.
Please help me, I am kind of a newbie in Jquery.
I have so far;
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
url: '/url_of_the_related_server_side',
dataType: 'json'
})
.done(function(data){
console.log(data);
alert(JSON.stringify(data));
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.search_box_ID == any_function_variable_name.name_in_the_JSON_file_for_one_of_the_searched_ID){
$userElement = $("<li>").html("<strong>ID: </strong>" + any_function_variable_name.id); //id is defined in JSON and I was able to use in another part of the jquery
$userBlock = $("<ul>")
.append(
$("<li>").html("<strong>Name: </strong>" + any_function_variable_name.name) //name of the user
)
.append(
$userElement
)
.append(
$("<li>").html("<strong>User User Name: </strong>" + any_function_variable_name.userName)
);
$any_function_variable_nameBlock.insertAfter("#search");
}
});
});})})
Note: I don't know if I could close the brackets right.
Thanks in advance!
I guess you are looking for something like as shown below ...
Instead of making an ajax call, I wrote with static data as below ...
HTML
<input id="searchBox" type="text" />
<button id="id_of_the_search_box_button">
Search
</button>
<ul>
</ul>
JS
var data = [
{
"id": 37595960858,
"in_reply_to_screen_name": null,
"user": {
"id": 2384451,
"id_str": "238678",
"name": "Doga I",
"screen_name": "IDoga"
}
},
{
"id": 65739068412,
"in_reply_to_screen_name": null,
"user": {
"id": 2878009,
"id_str": "235678",
"name": "Jon Doe",
"user_name": "JD"
}
}
];
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
var searchText = parseInt($('#searchBox').val());
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.id === searchText){
$("ul")
.append('<li> <strong>ID: </strong>' + any_function_variable_name.user.id)
.append('<li> <strong>User Name: </strong>' + any_function_variable_name.user.user_name)
.append('<li> <strong>Name: </strong>' + any_function_variable_name.user.name)
.append('<li> <strong>Screen Name: </strong>' + any_function_variable_name.user.screen_name);
} //End if
}); //End forEach
});
});
which makes your ajax call like this ...
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
url: '/url_of_the_related_server_side',
dataType: 'json'
})
.done(function(data){
var searchText = parseInt($('#searchBox').val());
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.id === searchText){
$("ul")
.append('<li> <strong>ID: </strong>' + any_function_variable_name.user.id)
.append('<li> <strong>User Name: </strong>' + any_function_variable_name.user.user_name)
.append('<li> <strong>Name: </strong>' + any_function_variable_name.user.name)
.append('<li> <strong>Screen Name: </strong>' + any_function_variable_name.user.screen_name);
} //End if
}); //End forEach
});
});
});
Following is the fiddler
https://jsfiddle.net/rrtbz4bo/7/
Enter 37595960858 in search box and hit search.
UPDATE: call the /find/id?id=... api directly if it returns data like
{
"id": 37595960858,
"in_reply_to_screen_name": null,
"user": {
"id": 2384451,
"id_str": "238678",
"name": "Doga I",
"screen_name": "IDoga"
}
}
Then following should work.
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
//Or whatever your URL structure is
url: 'http://127.0.0.1:5230/find/id?Id=' + $('#searchBox').val(),
dataType: 'json'
})
.done(function(data){
$("ul")
.append('<li> <strong>ID: </strong>' + data.user.id)
.append('<li> <strong>User Name: </strong>' + data.user.user_name)
.append('<li> <strong>Name: </strong>' + data.user.name)
.append('<li> <strong>Screen Name: </strong>' + data.user.screen_name);
});
});
});
If this doesn't work, post a fiddler and i'll try and make it work.
Hope this helps ...

Google prediction api javascript "message": "Login Required"

I was trying to implement a simple JavaScript client that will allow me to exploit the google prediction; I tried to mimic the authentication (Oauth 2.0) in this tutorial with google prediction.
This my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var _DATA = {
"input": {
"csvInstance": [
"je m'appelle dali"
]
}
}
var API_KEY =
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/prediction';
var CLIENTID =
var REDIRECT = 'http://localhost:6666/GoogleOauth/GoogleOauth.html'
var TYPE = 'token';
var TOKEN = '';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getPrediction;
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getPrediction() {
$.ajax({
url: 'https://www.googleapis.com/prediction/v1.6/projects/coderscloud-1/trainedmodels/CC-1/predict?key=' + API_KEY,
data: _DATA,
success: function(resp) {
alert(JSON.stringify(resp));
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
}
</script>
</head>
<body>
Click here to login
Click here to logout
</body>
</html>
The ajax call did return
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
Your missing a step. Until you have a user authenticated you cant request anything.
Step 3: Authentication and Authorization in popup
Lets show the actual authentication dialog now in a ‘popup’. Redefine
the login function as follows:

Categories