Home > Mobile >  How to display single items from array using JS/JQuery
How to display single items from array using JS/JQuery

Time:02-10

Its my first Question here, so be kind ^^ Im training myself some JS/Jquery/Ajax. Short: Projekt to filter closest location of a specific company to our current postal zip. So, here is my "work" so far: On index.php im using a simple form like this:

<form id="ajaxForm">
                <input type="number"  id="plzInput" name="plzInput" placeholder="99999"
                       aria-label="Username" aria-describedby="basic-addon1" required>
                <button type="submit" id="plzSubmit" name="plzSubmit" >Search</button>
            </form>

Im passing some data to ajax.php using ajax:

 var request;
     $("#ajaxForm").submit(function (event) {
         event.preventDefault();
         if (request) {
             request.abort();
         }
         var $form = $(this);

         //Caching
         var $inputs = $form.find("input, select, button, textarea");

         var serializedData = $form.serialize();
         $inputs.prop("disabled", true);
         request = $.ajax({
             url: "ajax.php",
             type: "post",
             data: serializedData
         });
         request.done(function (response, textStatus, jqXHR) {
             console.log("in ajax.php geschrieben!");
             console.log(response);
             showResults(response);


         });
         request.fail(function (jqXHR, textStatus, errorThrown) {
             console.error(
                 "The following error occurred: "  
                 textStatus, errorThrown
             );
         });
         request.always(function () {
             $inputs.prop("disabled", false);
         });
     });

     function showResults(data){
         alert(data);

     }
 });

Here the data finally getting handled using php (db queries, calculations, result). Now im struggling on how to send my resuslts from ajax.php back to index. All in all, i want to send back an array from SQLquery, and show those values into existing html inputs using js/jquery on index.php. But i don't know why the response of ajax.php isnt readable by the JS/Jquery. I think there is something wrong with php arrays vs js arrays. Is there a way to send "multiple" responses or even an array of responses?

im glad for every help!

CodePudding user response:

A good way to do this is by using JSON.

On the PHP side, in ajax.php, you use json_encode() to encode your array as a string.

That JSON string is then received in your Javascript AJAX as the response. There you can turn it back into an array with JSON.parse():

let array = JSON.parse(response);

JQuery also has a shorthand for this, see:

https://api.jquery.com/jQuery.getJSON/

  • Related