0

I am sending some form data via ajax to a php script in the same page. PHP must process the data and show results in the same page.

I am using this syntax for ajax:

$.ajax
({
    type: "POST",
    url: "",
    data: $("form").serialize(),
    success: function(result)
    {
        updatechart();
       console.log(result);
    }
});  

I am basically trying to update some values in a chart based on data entered in the form and after processed by a php script. I get the whole source of the page when I do console.log(result); and the values are updated in my console after doing this but the chart is not updated. When I view-source the page, the values remain the same. What should I do?

    function updatechart() {
        var json=<?php echo json_encode($GLOBALS['json']); ?>;
        var direct=json['direct'];
        var total=json['total'];
        var referred=total-direct;
        var aid=new Array();
        var count=new Array();
        for(var i=0;i<json['aid'].length;i++) {
            aid[i]=json['aid'][i];
            count[i]=json['count'][i];
        }
    var series = [{
                name : "Referred",
                data: [referred]
            }, {
                name: "Direct",
                data: [direct]
            }];
       for(var i=0; i<aid.length;i++) {
            series.push({
                name: 'AID-'+[aid[i]],
                data: [count[i]]
            })
        }
    var options = {
        chart: {
            renderTo: 'container',
            type: 'column'
        },
        title: {
            text: 'User Source Chart'
        },
        xAxis: {
            categories: ['Users']
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Total users'
            }
        },
        tooltip: {
            pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.percentage:.0f}%)<br/>',
            shared: true
        },
        plotOptions: {
            column: {
                stacking: 'percent'
            }
        },
            series: series
    };
    chart = new Highcharts.Chart(options); 
}

This is my updatechart() code. The problem is, json value is not updated.

user2510555
  • 967
  • 2
  • 8
  • 15
  • 3
    whats `updatechart()` do? – tymeJV Jul 08 '13 at 14:43
  • What is the body of `updatechart()`? – ElmoVanKielmo Jul 08 '13 at 14:44
  • Your `url` parameter is empty; is that true in your code or is that just a typo in the question? – cfs Jul 08 '13 at 14:46
  • I want the url to be the same page. That is why. – user2510555 Jul 08 '13 at 14:47
  • Added updatechart() code. I basically want json varaible's value to be updated. Which is done in php. – user2510555 Jul 08 '13 at 14:52
  • 1
    JavaScript runs on the client (in this case), changing a global in PHP won't change where you output that global in javascript unless you completely reload the page or re-include the javascript again. Instead, return the json from the request and pass said json into updatechart(), as suggested by user1671639 – Kevin B Jul 08 '13 at 14:52
  • I don't understand what am I supposed to do? I have to use $GLOBALS['json'] because json is stored as a global variable in a function in php. What is the alternative? And I am getting the full page as response. So passing it to updatechart() won't really help no? – user2510555 Jul 08 '13 at 14:59
  • Why must you post to the same page? if you want to do that, you'll either have to do a full page refresh every time, or completely change the output of the page depending on whether it's ajax or not. If it's ajax, you'll have to make it return ONLY the json. Changing a global var in php won't help you solve this problem, javascript can't see said global. – Kevin B Jul 08 '13 at 15:02

2 Answers2

3

Pass the result as parameter to updatechart()

$.ajax
({
    type: "POST",
    url: "",
    data: $("form").serialize(),
    success: function(result)
    {
        updatechart(result);      
    }
}); 

then access the results via parameter.

function updatechart(result) {
//.......
//.......
console.log(result);
}

Hope you're trying something like this.

Praveen
  • 55,303
  • 33
  • 133
  • 164
  • Yes, this is the correct way, but it looks like OP is getting the entire page in response... – ElmoVanKielmo Jul 08 '13 at 14:51
  • 1
    @user2510555 That's probably because your PHP is still setting a global rather than returning the json. (via echo) – Kevin B Jul 08 '13 at 14:54
  • @user2510555 what is your ajax returning? `result = undefined`, then what is the use of ajax call? – Praveen Jul 08 '13 at 14:56
  • @user1671639 it is returning the whole page with updated values when I do `console.log(result);` inside the success function. – user2510555 Jul 08 '13 at 15:00
1

That is expected behavior. Move your PHP processing to a different page.

$.ajax
({
    type: "POST",
    url: "anotherphppage.php",
    data: $("form").serialize(),
    success: function(result)
    {
        updatechart(result);      
    }
}); 

Try this and you'll see what I mean:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

        <script type="text/javascript">
            $(document).ready(function() {

                $('#mybutt').click(function() {
                    $.ajax({
                        type: "POST",
                        url: "",
                        data: 'myVar=Hello',
                        success: function(data) {
                            alert(data);
                        }
                    });
                });
            }); //END $(document).ready()

        </script>
    </head>
<body>

    Try this:<br />
    <input type="button" id="mybutt" value="Click Me">

</body>
</html>
cssyphus
  • 37,875
  • 18
  • 96
  • 111