如何在JavaScript条件为真时调用PHP函数

huangapple go评论80阅读模式
英文:

How to call php function if javascript condition true

问题

以下是您的代码的中文翻译:

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( '手机号码', 'woocommerce' ); ?>&nbsp;<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();">发送验证码</button>
</form>
<br/>
<h1>输入验证码</h1>
<form>
<input type="text" id="verificationCode" placeholder="输入验证码" class="woocommerce-Input woocommerce-Input--text input-text">
<button class="woocommerce-Button button woocommerce-form-login__submit" type="button" onclick="codeverify();">验证验证码</button>
</form>

<!-- 必须始终引入核心 Firebase JS SDK,并且必须首先列出 -->
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase.js"></script>

<!-- TODO:添加要使用的 Firebase 产品的 SDK
   https://firebase.google.com/docs/web/setup#config-web-app -->
<script>
   // 您的网页应用的 Firebase 配置
   var firebaseConfig = {
      apiKey: "*****",
      authDomain: "*****",
      databaseURL: "*****",
      projectId: "*****",
      storageBucket: "*****",
      messagingSenderId: "*****",
      appId: "*****"
   };
   // 初始化 Firebase
   firebase.initializeApp(firebaseConfig);
</script>

<script>
window.onload=function () {
   render();
};
function render() {
   window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier('recaptcha-container');
   recaptchaVerifier.render();
}
function phoneAuth() {
   // 获取手机号码
   var number=document.getElementById('number').value;
   // Firebase 的手机号码验证函数,它接受两个参数:第一个是手机号码,第二个是 reCAPTCHA
   firebase.auth().signInWithPhoneNumber(number,window.recaptchaVerifier).then(function (confirmationResult) {
      // s 为小写
      window.confirmationResult=confirmationResult;
      coderesult=confirmationResult;
      console.log(coderesult);
      alert("消息已发送");
   }).catch(function (error) {
      alert(error.message);
   });
}
function codeverify() {
   var code=document.getElementById('verificationCode').value;
   coderesult.confirm(code).then(function (result) {
      alert("验证成功");
      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');

以下是您在 WordPress 主题的 functions.php 文件中的代码:

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');

如果用户成功验证了 OTP,您希望在您的 PHP 文件中调用此函数。这些代码似乎是用于在 WooCommerce 网站中实现电话号码验证和用户身份验证的一部分。如有需要,您可以进一步调试和测试这些功能以确保其正确运行。

英文:

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() { ?&gt;
&lt;form&gt;
&lt;p class=&quot;woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide&quot;&gt;	
&lt;label for=&quot;number&quot;&gt;&lt;?php esc_html_e( &#39;Mobile Number&#39;, &#39;woocommerce&#39; ); ?&gt;&amp;nbsp;&lt;span class=&quot;required&quot;&gt;*&lt;/span&gt;&lt;/label&gt;
&lt;input type=&quot;tel&quot; class=&quot;woocommerce-Input woocommerce-Input--text input-text&quot; name=&quot;number&quot; id=&quot;number&quot;/&gt;
&lt;/p&gt;
&lt;div id=&quot;recaptcha-container&quot;&gt;&lt;/div&gt;
&lt;button class=&quot;woocommerce-Button button woocommerce-form-login__submit&quot; type=&quot;button&quot; onclick=&quot;phoneAuth();&quot;&gt;SendCode&lt;/button&gt;
&lt;/form&gt;
&lt;br/&gt;
&lt;h1&gt;Enter Verification code&lt;/h1&gt;
&lt;form&gt;
&#160; &#160; &lt;input type=&quot;text&quot; id=&quot;verificationCode&quot; placeholder=&quot;Enter verification code&quot; class=&quot;woocommerce-Input woocommerce-Input--text input-text&quot;&gt;
&#160; &#160; &lt;button class=&quot;woocommerce-Button button woocommerce-form-login__submit&quot; type=&quot;button&quot; onclick=&quot;codeverify();&quot;&gt;Verify code&lt;/button&gt;
&lt;/form&gt;
&lt;!-- The core Firebase JS SDK is always required and must be listed first --&gt;
&lt;script src=&quot;https://www.gstatic.com/firebasejs/7.6.1/firebase.js&quot;&gt;&lt;/script&gt;
&lt;!-- TODO: Add SDKs for Firebase products that you want to use
&#160; &#160; &#160;https://firebase.google.com/docs/web/setup#config-web-app --&gt;
&lt;script&gt;
&#160; &#160; // Your web app&#39;s Firebase configuration
&#160; &#160; var firebaseConfig = {
&#160; &#160; apiKey: &quot;*****&quot;,
&#160; &#160; authDomain: &quot;*****&quot;,
&#160; &#160; databaseURL: &quot;*****&quot;,
&#160; &#160; projectId: &quot;*****&quot;,
&#160; &#160; storageBucket: &quot;*****&quot;,
&#160; &#160; messagingSenderId: &quot;*****&quot;,
&#160; &#160; appId: &quot;*****&quot;
&#160; &#160; };
&#160; &#160; // Initialize Firebase
&#160; &#160; firebase.initializeApp(firebaseConfig);
&lt;/script&gt;
&lt;script&gt;
window.onload=function () {
&#160; render();
};
function render() {
&#160; &#160; window.recaptchaVerifier=new firebase.auth.RecaptchaVerifier(&#39;recaptcha-container&#39;);
&#160; &#160; recaptchaVerifier.render();
}
function phoneAuth() {
&#160; &#160; //get the number
&#160; &#160; var number=document.getElementById(&#39;number&#39;).value;
&#160; &#160; //phone number authentication function of firebase
&#160; &#160; //it takes two parameter first one is number,,,second one is recaptcha
&#160; &#160; firebase.auth().signInWithPhoneNumber(number,window.recaptchaVerifier).then(function (confirmationResult) {
&#160; &#160; &#160; &#160; //s is in lowercase
&#160; &#160; &#160; &#160; window.confirmationResult=confirmationResult;
&#160; &#160; &#160; &#160; coderesult=confirmationResult;
&#160; &#160; &#160; &#160; console.log(coderesult);
&#160; &#160; &#160; &#160; alert(&quot;Message sent&quot;);
&#160; &#160; }).catch(function (error) {
&#160; &#160; &#160; &#160; alert(error.message);
&#160; &#160; });
}
function codeverify() {
&#160; &#160; var code=document.getElementById(&#39;verificationCode&#39;).value;
&#160; &#160; coderesult.confirm(code).then(function (result) {
&#160; &#160; &#160; &#160; alert(&quot;Successfully registered&quot;);
&#160; &#160; &#160; &#160; var user=result.user;
&#160; &#160; &#160; &#160; console.log(user);
&#160; &#160; }).catch(function (error) {
&#160; &#160; &#160; &#160; alert(error.message);
&#160; &#160; });
} &#160; &#160;
&lt;/script&gt;
&lt;?php }
add_action(&#39;woocommerce_after_customer_login_form&#39;, &#39;devsol_customer_form&#39;);

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[&#39;number&#39;] );
if ( $user = get_user_by( &#39;login&#39;, $user_phone) ) {
$user_id = $user-&gt;ID;
$user_roles = $user-&gt;roles;
$user_role = array_shift($user_roles);
if ( $user_role === &#39;customer&#39;) {
if ( apply_filters( &#39;woocommerce_registration_auth_new_customer&#39;, true, $user_id ) ) {	
wc_set_customer_auth_cookie( $user_id );
}	
}
}			
}
add_action(&#39;init&#39;, &#39;devsol_customer_auth&#39;);

Someone please help

答案1

得分: 2

你不能直接从JavaScript(JS)中调用PHP函数,因为JS在客户端上运行,比如在浏览器上运行,而你的PHP文件存在于Web服务器上。
为了做类似的事情,你需要向PHP文件发出请求,并在请求中传递参数(可以是GET或POST)。
一个简单的示例可能是

  1. 创建一个单独的PHP文件,比如说actions.php,该文件将被请求访问。

  2. 从JS中对该文件进行请求
    例如:

     function httpGet(theUrl)
    {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // false用于同步请求
    xmlHttp.send(null);
    return xmlHttp.responseText;
    }
    httpGet('www.yourSite.com/actions.php?phone=' + userPhoneNumber);
    

这应该解决了你的问题。

英文:

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

  1. create a separate php file, lets say actions.php, that will be hit by the request.

  2. make a request to the file from JS
    E.g.

     function httpGet(theUrl)
    {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( &quot;GET&quot;, theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
    }
    httpGet(&#39;www.yourSite.com/actions.php?phone=&#39; + userPhoneNumber);
    

This should resolve your problem.

huangapple
  • 本文由 发表于 2020年1月4日 02:00:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583229.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定