demonLaMagra
demonLaMagra

Reputation: 409

Passing Javascript variable to PHP and then reloading page without refresh

How do you reload a page without re-fresh after sending a javascript variable to PHP via Ajax.

Below is an image of a webpage I'm creating which analyses asset performance.

What I'm trying to do is the following.

When a user selects a test block with in the graph, the selcection box is updated with all subtests within that specific test block. However, I do not want to refresh the page. I have managed to send the the selected tested block to the PHP code via ajax, but can not get ajax to reload the page without a refresh.

Currently, when a test block is selected, the label is return to PHP and is stored in the $_SESSION['label'] variable. This is then used in the panel header #subtest-chart-select. However the label will not update without a page refresh which is what I want to avoid.

example webpage

Ajax:

$("#test_block_chart").click(
    function(evt){
        var activePoints = myNewChart.getElementsAtEvent(evt);
        if (activePoints[0]) {
            var chartData = activePoints[0]['_chart'].config.data;
            var idx = activePoints[0]['_index'];
            var label = chartData.labels[idx];
            //alert(label);

            $.ajax(
                {
                    url:'test_performance.php',
                    type: 'POST',
                    datatype: 'json',
                    data: {'label':label},   // post to location.php
                    success: function(label) {
                    // success
                 },

                 error: function(label) {
                     alert("There may an error on uploading. Try again later");
                 }

             });

         }
     });
 });`

PHP:

session_start();

if(isset($_POST['label']))
{
    $_SESSION['label'] = $_POST['label'];
}

PHP echo HTML

<?php
    echo '<div class="row">
              <div class="col-lg-12 subtest-select">
                  <div class="panel panel-default">
                      <div class="panel-heading">
                          <h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i>' . $_SESSION['label'] . ' Subtest Select </h3>
                      </div>
                      <select class="form-control">
                          <option>1</option>
                      </select>
                  </div>
              </div>
         </div>'
     ?>

I'm still to write the PHP code to update the options of subtests within the selected test block.

Any help will be greatly appreciated as I've been trying to get this working for what seems like forever.

Upvotes: 0

Views: 1320

Answers (2)

Rauli Rajande
Rauli Rajande

Reputation: 2020

In $.ajax() set

dataType: 'text',

In your $.ajax() success function say:

success: function(data) {
    $('.inside_whereever_you_want_to_show_this').html(data);
}

Edit:

To update only one value on page you can:

a) in PHP print out only this value (so that whole page would be only this value).

<?php echo $_SESSION['label']

and in HTML put a span around the bit you want to update (avoid constructing longer strings in javascript, all constant parts should be in HTML)

<h3 class="panel-title" id="subtest-chart-select"><i class="fa fa-bar-chart-o fa-fw"></i><span class="subtest-updateable">' . $_SESSION['label'] . '</span> Subtest Select </h3>

then you can update only your needed bit with whole response

success: function(data) {
    $('.subtest-updateable').html(data);
}

b) better (in systematic approach means) would be use json response, where you can return more isolated variables as well:

  • Set dataType to json.
  • Success function would use $('.subtest-updateable').html(data.label)
  • In PHP print json_encode(array('label' => $_SESSION['label'], 'someelse' => $someother_variable ))
  • You still should put span (or some other html element) around updateable bits of your page (to avoid writing constants into your javascript)

Upvotes: 2

WombatPM
WombatPM

Reputation: 2619

In your success function you need to update the part of the DOM that you want to change. On the PHP side just return your blade partial or whatever HTML you want to display.

$(document).on('submit', 'form#form-grad', function (e) {
    e.preventDefault();
    var context = $(this);
    var thisForm = context.closest('form');

    $.ajax({
        url: thisForm.attr('action'),
        method: 'PUT',
        data: thisForm.serialize(),
        success: function (response) {
            $('#updatearea').html(response.pt_html);
             // Close grading form
        }
    });

    return false;
}); 

Upvotes: 1

Related Questions