使用jQuery .ajax()有效地输出查询结果? [关闭]

Sorry in advance if what I am going to ask is silly, I am having trouble understanding the asynchronous HTTP responses. I am trying to use jQuery .ajax() with PHP and MySQL in the following context:

  • when page loads I will query and return all the applications for a particular id, and then I will use a while loop to output them;
  • also there is a button that allows the user to add new application for that particular id -> on click it:
    • shows a hidden form and gets the values in the inputs;
    • sends the data to PHP using the .ajax() method;
    • performs the insert.
  • and I am stuck at this point

I need to output the newly added application above the existing ones, but the query and while will do it only when an synchronous HTTP request is sent.

I tried to use the .success() but the HTML I need to output inside is really long and I am afraid it will be hard to maintain having outputs from both PHP while loop and jQuery.

Can you please help me understand an efficient way to do this? I have never dealt with asynchronous HTTP request before. Also, I am can't use any JavaScript templating libraries.

I would really appreciate your help!

An ajax postback typically implies some sort of JSON-based web api behind it. Examples of this on the internet abound.

https://www.lennu.net/jquery-ajax-example-with-json-response/ http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html

Your REST endpoint should return the minimal amount of JSON data you need. At which point you can use that data to update/bind to elements in your DOM inside your "done" or "success" callback.