Update page content cURL and ajax without page refresh


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;

        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]);
            else {
              cell.innerHTML = item[v];

        return table;

      // Initialize air datepicker plugin

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

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

        // Ajax request

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

            // Show the table container

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



          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 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">

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

          <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>
           <div id="table"></div>

Open in new window

And this is my php code

	$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);


	echo $output;

Open in new window

Vincenzo VecchioAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David FavorLinux/LXD/WordPress/Hosting SavantCommented:
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...
Vincenzo VecchioAuthor Commented:
Hi Thanks for your answer I've sorted it out changing


Open in new window



Open in new window

I will have a look at PhantomJS as well many thanks :)
Julian HansenCommented:
First up this line is not necessary
datas = JSON.parse(result);

Open in new window

jQuery will convert to JSON for you if you specify the following option in your AJAX call

Open in new window

Secondly your code should already cater for this

Open in new window

Each table you create if you run the append code above it will append the new table after the last one.

Other than that I am not understanding the question.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ensure Business Longevity with As-A-Service

Using the as-a-service approach for your business model allows you to grow your revenue stream with new practice areas, without forcing you to part ways with existing clients just because they don’t fit the mold of your new service offerings.

Julian HansenCommented:
Missunderstood your question.

Firstly PhantomJS is not relevant to this Question - I don't think Dave understood what the issue was.

Secondly, yes your solution will work - I thought you wanted to add a new table each request.

Another option would be


Open in new window

Vincenzo VecchioAuthor Commented:
Many thanks Julian :)
Julian HansenCommented:
You are welcome.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.