Avatar of Vincenzo Vecchio
Vincenzo Vecchio

asked on 

Update page content cURL and ajax without page refresh

Hi,

I've a form to send a ajax request which return a json object from a cURL request. I use the form to query the API using the start and and the end date. I've managed to show the datas returned into a table as suggested in this post https://www.experts-exchange.com/questions/29120674/Convert-json-to-html-table.html
Now my problem is every time a make a new request from my form a new table is shown to the form page just after the table I've obtained with the previous request, is there any way to show only one table, so at every form request the previus data is replaced with the new data?

This is my javascript code:
    $(document).ready(function() {

      // Function to create table layout
      function createTable(data) {
        var table = document.createElement('table');
        var header = table.insertRow();

        for(var h in data[0]) {
          var th = document.createElement('th');
          th.innerHTML = h;
          header.appendChild(th);
        }

        table.classList.add('table','table-bordered');
        data.forEach(function(item) {
          var row = table.insertRow();
          for(var v in item) {
            var cell = row.insertCell();
            if (Array.isArray(item[v])) {
              var subtable = createTable(item[v]);
              cell.appendChild(subtable);
            }
            else {
              cell.innerHTML = item[v];
            }
          }
        })

        return table;
      }

      // Initialize air datepicker plugin
      $('.air-datepicker').datepicker();

      // Store form into variable
      var form= $("#requestForm");

      // Actions when form is submitted
      $('#submitForm').click(function(e) {

        // Ajax request
        $.ajax({

          type: "POST",
          url: form.attr("action"),
          data: form.serialize(),
  
          success: function(result){

            // Show the table container
            $('#tableContainer').css('display','block');

            // Convert reponse into JSON
            datas = JSON.parse(result);
            // Get nome condominio and show it
            $('#nome_condominio').html(datas.condomini[0].condominio.nome);
            // Get indirizzo condomino and show it
            $('#indirizzo_condominio').html(datas.condomini[0].condominio.indirizzo);
            // Put datas into table using the function createTable
            var table = createTable(datas.condomini[0].ricevute);
            // Show table 
            $('#table').append(table);

            console.log(result);

          },

          error: function(error, status, xhr) {
            console.log(error, status, xhr);
          
          }

        }); // Fine ajax
       
       e.preventDefault(); // Prevent form to be sent

      }); // fine submit form
      
    }); // fine document ready

Open in new window


This is my html code
<form id="requestForm" action="../km-client-controllers/km-ctrl-client-ricevute.php" method="POST">
              <div class="form-row">
                <div class="form-group col-md-3">
                  <label for="startDate">Data di inizio ricevuta</label>
                  <input type="text" class="form-control air-datepicker" data-date-format="dd/mm/yyyy" data-language='en' placeholder="Data di inizio" id="startDate" name="startDate">
                </div>
                <div class="form-group col-md-3">
                  <label for="endDate">Data di fine ricevuta</label>
                  <input type="text" class="form-control air-datepicker" data-date-format="dd/mm/yyyy" data-language='en' placeholder="Data di fine" id="endDate" name="endDate">
                </div>
              </div>

              <button type="submit" class="btn btn-primary" id="submitForm" >Mostra ricevute</button>
            </form>

          <div class="container-fluid" id="tableContainer" style="display: none" >
            <h2 class="text-center"><div id="nome_condominio"></div></h2>
            <h4 class="text-center"><div id="indirizzo_condominio"></div></h4>
            <br>
           <div id="table"></div>
          </div>

Open in new window


And this is my php code
session_start();

	$startDate = $_POST['startDate'];
	$endDate = $_POST['endDate'];

	$dates= array(

		'd_inizio' => $startDate,
		'd_fine' => $endDate
	);

		$url = "https://www.apiwebsite.com/api/ricevute.jsp?";

		if (!isset($_SESSION['cookiefile'])) {
		    die("no cookie file");
		}

	$cookie = "../../km-controllers/" . $_SESSION['cookiefile'];

	$ch = curl_init ($url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dates));
	curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); 
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
	$output = curl_exec ($ch);

	curl_close($ch);

	echo $output;

Open in new window

JavaScriptPHPAJAXJSON

Avatar of undefined
Last Comment
Julian Hansen
Avatar of David Favor
David Favor
Flag of United States of America image

This will take a massive amount of hacking, as CURL doesn't speak Javascript, so AJAX code... well... will take many hours of work... or...

You can use PhantomJS + be done in a few minutes.

Check the examples page on the site to pull down one of the many example scripts as a starting point.

PhantomJS - headless Chrome, so Javascript + CSS oddities all processed correctly... unlike CURL...
Avatar of Vincenzo Vecchio
Vincenzo Vecchio

ASKER

Hi Thanks for your answer I've sorted it out changing

 $('#table').append(table);

Open in new window


to

 $('#table').html(table);

Open in new window


I will have a look at PhantomJS as well many thanks :)
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Vincenzo Vecchio

ASKER

Many thanks Julian :)
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You are welcome.
JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo