使用PHP / AJAX将数据插入MySQL数据库,在插入后执行成功选项(回调)

使用PHP / AJAX将数据插入MySQL数据库,在插入后执行成功选项(回调)

问题描述:

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');
    
    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}

Thank you in advanced and if I need include further info don't hesitate to ask.

</div>

我一直在努力创建一个简单的网站,而我无法完全绕过一些网站 这里说的一些东西,其中一些也与我的情况无关。 p>

该网站有一个包含3个输入框,一个按钮和一个列表的表单。 单击提交按钮后,信息将通过单独的PHP文件提交到MySQL数据库。 一旦信息在数据库中成功发送和更新,我应该将列表(它在div中)更新。 到目前为止,我已经使它与异步一起工作:假,但我不应该,因为社会。 p>

如果没有这个(坏)选项,列表在提交信息后就不会加载,因为(我假设)该方法是在它之后执行的,因为它不等待它 完成。 p>

在“成功:”中我应该做些什么才能使其发挥作用? (或者,我在$ .ajax子句中读到了关于.done()的内容,但我不确定如何使其工作。) p>

回调应该是什么样的? 我以前从来没有这样做过,因为每个案例都略有不同,我可能会对这里的结果感到迷失方向。 p>

p>

  function save(){
 
 var name = document.getElementById('name'); 
 
 var email = document.getElementById('email')  ; 
 
 var telephone = document.getElementById('telephone'); 
 
 
 
 $ .ajax({
 
 url:“save.php”,
 
方法:“POST  “,
 
数据:{name:name.value,email:email.value,telephone:telephone.value},
 
成功:$(”List“)。load(”List“)
 \  n}); 
 
}  code>  pre> 
 
  div> 
 
  div> 
 
 
 
 

谢谢你的高级和如果 我需要包含更多信息,请不要犹豫。 p> div>

From this comment

as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam

I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)

I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.

Thanks!

(Won't let me mark as answered until 2 days)

I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:

PHP:

     function doLoadMails(){
       //initialize empty variable 
       $mails;

      $conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
         // Check connection
         if ($conn->connect_error) {
         die("");
             }
          //some select, insert, whatever  
         $sql = "SELECT ... ... ... ";
          $result = $conn->query($sql);

           if ($result->num_rows > 0) {
               // output data of each row, j is counter for rows
                $j =0;
              while($row_a = $result->fetch_assoc()) {    

             //for each row, fill array
            $mails[$j][0] = $row_a["name"] ; 
            $mails[$j][1] = $row_a["mail"] ; 
            $mails[$j][2] = $row_a["language"] ;         


                $j++;

                }
          }


        //if $mails has results (we added something into it)
          if(isset($mails)){
          echo json_encode($mails);/return json*/   }
          else{
//some error message you can handle in JS
echo"[null]";}



    }

and then in JS

function doLoadMails() {



    $.ajax({
        data: { /*pass parameters*/ },
        type: "post",
        url: "dataFunnel.php",
        success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
            console.log(data); //you can check what you get



            if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
        }
    });

Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.

In your solution, you will probably need to echo the return code of the INSERT request.

I would first create an AJAX call inside a function which runs when the page loads to populate the list.

window.onload = populatelist(); 

function populatelist() {
   $.ajax({
      type: "POST",
      url: "list.php",
      data: {function: 'populate'},
      success: function(data) { $("#list").html("data"); }
   });
}

Note: #list refers to <div id="list> and your list should be inside this.

I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.

function save() {
   var name = document.getElementById('name');
   var email = document.getElementById('email');
   var telephone = document.getElementById('telephone');

   $.ajax({
       type: "POST",
       url: "list.php",
       data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
       success: function() { populatelist(); }
   });
}

list.php should look like this:

<?php

if($_POST['function'] == "populate") {
   // your code to get the content from the database and put it in a list
}

if($_POST['function'] == "update") {
   // your code to update the database
}

?>