简体   繁体   English

访问数据库时的 AJAX & JQUERY

[英]AJAX & JQUERY when accessing database

Good day!再会!

I have a problem when using AJAX & JQUERY when accessing my database.在访问我的数据库时使用 AJAX 和 JQUERY 时遇到问题。 After searching from the internet this script (I think) fit on my problem.从互联网上搜索后,这个脚本(我认为)适合我的问题。 I tried to mimic it but failed.我试图模仿它但失败了。 Using JQuery AJAX and php to fetch data from a mysql database使用 JQuery AJAX 和 php 从 mysql 数据库中获取数据

my code: userValidation.php我的代码:userValidation.php

include '..\assets\database\connect.php';
$userLN = $_GET['userLN'];
$userFN = $_GET['userFN'];
// $userMN = $_GET['userMN'];
$regStatus='';

$i=0;
$getInfo = array();
$valLN=$valFN=$valMN='';
$query = "SELECT studLastname, studFirstname, studMiddlename FROM tblstudentinfo ";
$query .= "WHERE studLastname=? AND studFirstname=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss',$userLN,$userFN);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
    $stmt->close();
    $conn->close();
    $regStatus='exist';
}else{
    $regStatus='not exist';
}
echo json_encode($regStatus);

index.php索引.php

$('#btnNext').click(function() {
    var regStatus='';
    var urlParam='';
    var LN = document.getElementById('studRegLN').value;
    var FN = document.getElementById('studRegFN').value;
    urlParam="userLN="+LN+"&userFN="+FN;
    $.ajax({
      url: 'ajax/userValidation.php',
      data: urlParam,
      type: 'GET',
      dataType: 'json',
      success: function(data)
      {
        regStatus=data;
        alert(regStatus);
      }
    });
  });

My Scenario: When an admin user register a Student Assistant it will input the last name and first name.我的场景:当管理员用户注册学生助手时,它将输入姓氏和名字。 when the next button clicked before accessing the next part of the page it will validate first if the SA(student Assistant) is already exist.当在访问页面的下一部分之前单击下一步按钮时,它将首先验证 SA(学生助手)是否已经存在。

so there are $regStatus & var regStatus variable... i want to use alert();所以有$regStatus & var regStatus变量...我想使用 alert(); just to test if the variable was passed from $regStatus to regStatus(java variable).只是为了测试变量是否从 $regStatus 传递到 regStatus(java 变量)。

BUT if you have better way to do this, then feel free to post your recommendations + code.但是,如果您有更好的方法来做到这一点,那么请随时发布您的建议 + 代码。 Thank you谢谢

UPDATE these are my screenshot that proves the codes is not working更新这些是我的截图,证明代码不起作用在此处输入图片说明 在此处输入图片说明

notice the next button... I just clicked that but no alert(getStatus) pop-up注意下一个按钮...我只是点击了它,但没有alert(getStatus)弹出窗口

Change your ajax with this one.用这个改变你的ajax。

$('#btnNext').click(function() {
        var regStatus='';
        var urlParam='';
        var LN = document.getElementById('studRegLN').value;
        var FN = document.getElementById('studRegFN').value;
        urlParam="userLN="+LN+"&userFN="+FN;
        $.ajax({
            url: 'ajax/userValidation.php',
            data: urlParam,
            type: 'GET',
            dataType: 'json',
            success: function(data){
              regStatus=data;
            }
        });
    });

A handful of problems:几个问题:

1) not URL-encoding your querystring parameter values, especially since they're names and might easily contain characters not permitted on a querystring. 1) 不对您的查询字符串参数值进行 URL 编码,尤其是因为它们是名称并且可能很容易包含查询字符串中不允许的字符。 Let jQuery handle this for you by passing an object as the "data".通过将对象作为“数据”传递,让 jQuery 为您处理此问题。 NB You could also consider sending this request as POST, then the values will be in the request body, and cannot cause problems on your querystring.注意您也可以考虑将此请求作为 POST 发送,然后值将在请求正文中,并且不会导致您的查询字符串出现问题。

2) It's not clear whether you wait until the document is fully loaded before you declare your "click" event handler. 2) 不清楚是否要等到文档完全加载后再声明“单击”事件处理程序。 In an earlier revision of the question you had a document.ready block inside the click handler, which made no sense.在这个问题的一个早期版本,你不得不点击处理程序,它没有任何意义的document.ready块。 If you haven't already, wrap your button click code inside a document.ready handler, to ensure that your button already exists in the DOM by the time you try to bind to it.如果您还没有,请将您的按钮单击代码包装在一个 document.ready 处理程序中,以确保您的按钮在您尝试绑定到它时已经存在于 DOM 中。 Also ensure you used the correct ID selector - I can't see your HTML so can't check that for you.还要确保您使用了正确的 ID 选择器 - 我看不到您的 HTML,因此无法为您检查。

3) Ajax calls are asynchronous, so put your alert inside the "success" function as Priyank suggested, if you want to see the updated value of regStatus. 3) Ajax 调用是异步的,因此如果您想查看 regStatus 的更新值,请按照 Priyank 的建议将警报放入“成功”函数中。 Otherwise the alert runs before the ajax call is complete, so you won't see the updated value否则警报会在 ajax 调用完成之前运行,因此您将看不到更新的值

4) It's not clear what type of button you've used (again, the HTML is missing from your question), but if it's a submit type, then it will post back the page simultaneously unless you explicitly prevent that in your JS code. 4) 不清楚您使用了哪种类型的按钮(同样,您的问题中缺少 HTML),但如果它是提交类型,那么它会同时回发页面,除非您在 JS 代码中明确阻止。 If it posts back, then the page is destroyed and your ajax request will either not run, or the response from it will be be lost because the page it ran from is destroyed.如果它回发,那么页面将被销毁,您的 ajax 请求将不会运行,或者它的响应将丢失,因为它运行的页面已被销毁。

Putting these all together should result in something like this:将所有这些放在一起应该会导致如下结果:

$(function() { //don't declare click handler until document is fully ready and all HTML elements are loaded.
  $('#btnNext').click(function(event) {
    event.preventDefault(); //prevent default button postback behaviour, if any
    var regStatus='';
    var LN = document.getElementById('studRegLN').value;
    var FN = document.getElementById('studRegFN').value;

    $.ajax({
      url: 'ajax/userValidation.php',
      data: { //let jQuery do the URL-encoding for you
            "userLN": LN,
            "userFN": FN
      },
      type: 'GET',
      dataType: 'json',
      success: function(data)
      {
        regStatus = data;
        alert(regStatus); //alert must be in here to definitely delay executing the alert until the variable is populated from the asynchronous server response
      },
      error: function(jqXHR) { //handle ajax errors
        alert("Error: " + jqXHR.responseText);
      }
    });
  });
});

Ajax Call Should be like. Ajax Call 应该是这样的。

    var lanme=document.getElementById('studRegLN').value;
    var fname=document.getElementById('studRegFN').value;
    $.ajax({
     url: 'ajax/userValidation.php',
     type:'GET', /* GET or POST */     
     data: {
            userLn:lname,
            userFn:fname
            },
     dataType: 'json',
     success: function(data)
     {
       regStatus=data;
     }
    });

Hey, i'm new to Stack overflow Sorry for bad English.嘿,我是 Stack Overflow 的新手 抱歉英语不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM