简体   繁体   中英

Display chart after form submit via AJAX

I need to display a report with some data from the server and this also includes a chart.. im trying to send the json data using $.getJSON once the form is already submitted but for some reason im not even able to echo out $_GET[rep] to make sure im recieving the correct data.. below is the php code and here is the js http://jsfiddle.net/f8rGb/2/

PHP CODE

  if (isset($_POST["search"]) and $_POST["search"] == "go"){

     $name = $_POST['term'];

     $project = new Project();
     $pro = $project->get_project($name);  
     $serv = $project->get_project_service_by_id($pro);

     // DOING this to make sure i recieve the variable 
        // echo $_GET['rep'];

        if(isset($_GET['rep']))
        die(json_encode($serv)); 

     }

JS CODE

   function searchProjectsRep() {

   // TRIGGERING THIS FUNCTION IN THE ONSUBMIT EVENT OF THE FORM

   var datos = $('#formProjectsRepSearch').serialize();
   var uri = $('#formProjectsRepSearch').attr('action');
    $.ajax({
        url: uri,
        data: datos,
        type: 'POST',
        success: function(resp) {
            $('#ajaxProjectsRep').html(resp);
            projectChart();
        }
 });
 }

 // CHART FUNCTION

 function projectChart(){

 $.getJSON('controller.php?rep=1', function(data) { 

    options = {
      chart: {
        renderTo: 'chart_div',
        defaultSeriesType: 'pie'
    },
    title: {
        text: 'Datos de proyecto'
    },

    series: []
    };
       var statusCount = {},
       serie1 = [];

       data.forEach(function(e) {
       statusCount[e.status] = 1 + (statusCount[e.status] || 0);
    });

    $.each(statusCount, function(status, count) {
    serie1.push( [status, count] );
    });
    options.series.push({data: serie1});

    new Highcharts.Chart(options);

    });
  }

You can only do either a POST request, or a GET request, not both at the same time, so don't return the content of the GET variable inside a function that checks if a POST request was done :

if ( isset($_POST["search"]) && trim( $_POST["search"] ) == "go" ){ 
    $name    = $_POST['term'];
    $project = new Project();
    $pro     = $project->get_project($name);  
    $serv    = $project->get_project_service_by_id($pro);
    exit;
}

if(isset($_GET['rep']))
    echo json_encode($serv); 
    exit;
}

On the other hand, what's the point of making two ajax calls, just return the data in the first one where the form is submitted ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM