0

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.

devonj
  • 1,198
  • 1
  • 13
  • 24
Zero Ziat
  • 11
  • 4
  • Are you saying that there are three things in a list, and each one is from what is entered in an input field? – The Codesee Dec 08 '17 at 21:39
  • The list outputs what's in the database, which is inserted through the form. The three things are in the form (name, email, telephone), and they are inserted through the PHP script to the database. I am looking for the list to update once it's finished sending the info to the database. – Zero Ziat Dec 08 '17 at 21:41
  • When the user loads onto the page, is the list already there? – The Codesee Dec 08 '17 at 21:42
  • Yes. I didn't think it'd be necessary but I can include the whole page code if needed. The list works fine... for now. – Zero Ziat Dec 08 '17 at 21:43
  • Just to be clear the form is in one half of the page and the list is in the other half of the page, so yes, the form and the list are within the same page and the list is supposed to update once info is submitted through the form. – Zero Ziat Dec 08 '17 at 21:45
  • What I would do is have an AJAX request inside a function which gets the information from the database and put it into a list. I would call this function when the page loads. And then when the user updates the list, clear (empty the contents) of the list and inside the success function, run the function which populates the list (what you used at the start). Let me know if you want further clarification... – The Codesee Dec 08 '17 at 21:45
  • The list does load when the page loads, and displays info already in the database. I'm seeking to have the list update once info is submitted. I do so by reloading the div where the PHP that loads the list is stored. (That is what my "success:" currently does) I'm just lacking that something to make it wait for the PHP to finish to have it load without having to use async: false. – Zero Ziat Dec 08 '17 at 21:49
  • is the statement `$("List").load(" List")` just for a reference ? I don't get why it doesn't work and it should I just used your code to run locally and it works fine and async :false is not a good option for this it will make other sections wait which are called after the ajax call –  Dec 08 '17 at 21:53
  • if you could add a bit more code related to your list that you say needs to be updated , is that a simple select drop down or div based , or select2 dropdown there are lots of options to update the list after you submit via ajax –  Dec 08 '17 at 21:55
  • That statement has worked for me, but only with async off. It's not for a reference though, my div with the list is literally called "List". – Zero Ziat Dec 08 '17 at 21:56
  • The list is fine, what I need to know is what /howto asynchronous call to make for the script wait enough to run the list reload clause (which is in success:) (I'm sorry if it seems unclear!) – Zero Ziat Dec 08 '17 at 21:59
  • And the div that holds the list is that using `html` to show the list , is it `ul` and `li` based list ? if you can add the `HTML` related to the div it would be easier to fix it –  Dec 08 '17 at 21:59
  • The list is just a PHP script that populates a ``. As I've said before the problem resided within the AJAX because I don't know how to make it wait for the PHP that inserts the data to finish it's processing so that the data is already in the database once the list reloads. In other words, the PHP should say something like "Data inserted, done" and the AJAX should say something like "Okay you're done? Then I'll load the list" and then it loads it. There are no `ul`s and `li`s.
    – Zero Ziat Dec 08 '17 at 22:07
  • 1
    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 Dec 08 '17 at 22:07
  • I'll try that, might just be the slight change I need. **EDIT**: It worked. I'll have to look more into how I'll handle errors later though. Wish I could credit you with the answer! @MuhammadOmerAslam – Zero Ziat Dec 08 '17 at 22:34
  • :) that is ok , the main thing is you get it working , can just edit your own post and add the solution that worked. – Muhammad Omer Aslam Dec 08 '17 at 22:39

3 Answers3

1

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)

Zero Ziat
  • 11
  • 4
  • yes they are called optons you should read more about it [here](http://api.jquery.com/jquery.ajax/) , yes it will make you wait for 2 days and if you want to know about [async](https://stackoverflow.com/questions/1457690/jquery-ajax-success-anonymous-function-scope) – Muhammad Omer Aslam Dec 08 '17 at 22:45
  • by the way @The Codesee also used the same approach below –  Dec 08 '17 at 22:47
  • well, i think I can suggest a complete answer along with the error handling if you say so? – Muhammad Omer Aslam Dec 08 '17 at 22:52
  • That'd be swell. I don't know how it'd respond if say, the email wasn't unique (email in database is configured with a UNIQUE key) or maybe the telephone number goes over the varchar limit or maybe there's numbers in the name (though i've set no validation for that either), etc... I mean, as of the moment, obviously nothing happens when you submit something wrong but returning specific errors would be neat. – Zero Ziat Dec 08 '17 at 23:08
  • Turns out I also have to make the last submitted row show up at the top of the form too. – Zero Ziat Dec 09 '17 at 00:46
0

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.

Zorak
  • 709
  • 7
  • 24
  • 1
    this does not provide what the OP wants he wants you should either delete or update the code according to therequirements –  Dec 08 '17 at 21:56
  • It actually does if I got it correctly. He wants to perform some data handling inside DOM after data were successsfuly inserted. And as mysql has return codes, he can pass the return code from php - sql request into JS and he knows, he can perform other actions - get another data, handle existing data, or whatever – Zorak Dec 08 '17 at 21:59
  • 1
    and you still use `async:false` is that what the OP wanted? –  Dec 08 '17 at 22:00
  • Should I make a JS function() function to run this? I would input the `$("List").load(" List")` below the if, I assume? – Zero Ziat Dec 08 '17 at 22:01
  • I have copied it from my solution, the truth is it is not needed, but I believe, async parameter is not the core/point of the problem and the requester will get it ... – Zorak Dec 08 '17 at 22:02
  • Oh yeah, I can't use async:false. It hangs the JS engine if there's bad connectivity. – Zero Ziat Dec 08 '17 at 22:02
  • so dont use it .. the async does not have anything with it ... you care about the success: function(data) part – Zorak Dec 08 '17 at 22:03
  • `async:false` does have to to do with other events on the page that are executed after the call @Zorak it wont move forward until it finishes – Muhammad Omer Aslam Dec 08 '17 at 22:04
  • I am not arguing about that and I have already deleted it from my solution. @AliAslam was definitely right. But interesting is, how everyone shouts about this, completely ignoring the origin of this problem, which is - I believe - working. – Zorak Dec 08 '17 at 22:07
  • @Zorak could be right guys, I just haven't finished trying stuff yet but I'll report back, don't downvote please. – Zero Ziat Dec 08 '17 at 22:09
  • I cant down vote @Zorak , wasn't me I just pointed out the problem in the script and the requirements of the OP just to eventually help out :( –  Dec 08 '17 at 22:10
  • guys i downvoted because it wasnt what the requirements are and as soon it fixes i always take my downvote bak, i dont like discouraging others chill out – Muhammad Omer Aslam Dec 08 '17 at 22:12
0

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
}

?>
The Codesee
  • 3,714
  • 5
  • 38
  • 78
  • I thank you for your valuable code, friend, but I am not seeking to change how the list is handled/populated, only how AJAX handles the submission of the info, waits for a response that says it's done from the PHP script, then reloads the div. – Zero Ziat Dec 08 '17 at 22:14