Search code examples
c#jqueryasp.netajaxwebmethod

Loop the webmethod so 2 ajax calls retrieve 2 different calls


I have mixed a lot of information, but it worked fine, until i discovered i wanted 2 doughnut charts, then i got into problem, that i'm out of bounds i have tried to find a way to loop the webmethod, so it receive the 2 ajax calls, it does receive them, but it doesn't have loop in webmethod like i want to, so it retrieve different, like chart1, should be something about ships and chart2 should be about something else.

Like, it should be a loop, where the querystring is changing, so it will get 2 different Select commands from the query.

Code Behind WebMethod

[WebMethod]
public static string GetChart ( string chart )
{
    string constr1 = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
    using ( SqlConnection con = new SqlConnection ( constr1 ) )
    {
        string query = string.Format("SELECT Value1,Color1,Highlight1,Label1 FROM Tuning WHERE FK_Chart1_ID = '{0}'", chart);
        string query2 = string.Format("SELECT Value2,Color2,Highlight2,Label2 FROM Tuning WHERE FK_Chart2_ID = '{0}'", chart);
        using ( SqlCommand cmd = new SqlCommand ( ) )
        {
            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open ( );
            using ( SqlDataReader sdr = cmd.ExecuteReader ( ) )
            {
                StringBuilder sb1 = new StringBuilder();
                sb1.Append ( "[" );
                while ( sdr.Read ( ) )
                {
                    sb1.Append ( "{" );
                    System.Threading.Thread.Sleep ( 50 );
                    sb1.Append ( string.Format ( "value:{0}, color: '{1}', highlight :'{2}', label :'{3}'" , sdr [ 0 ] , sdr [ 1 ] , sdr [ 2 ] , sdr [ 3 ] ) );
                    sb1.Append ( "}," );
                }
                sb1 = sb1.Remove ( sb1.Length - 1 , 1 );
                sb1.Append ( "]" );
                con.Close ( );            
                return sb1.ToString ( );
            }
        }
    }
}

jQuery

$( function ()
{
    $( '#<%= DropDownList_1.ClientID %>' ).bind( "change", function ()
    {
        LoadChart();
    } );
} );

function LoadChart()
{
    //setup an array of AJAX options, each object is an index that will specify information for a single AJAX request
    var ajaxes = [{ url: 'CS.aspx/GetChart', data: "{chart: '" + $( '#<%= DropDownList_1.ClientID %>' ).val() + "'}", contentType: "application/json; charset=utf-8", dataType: 'json', chart: '#dvChart1' }, { url: 'CS.aspx/GetChart', data: "{motor: '" + $( '#<%= DropDownList_1.ClientID %>' ).val() + "'}", contentType: "application/json; charset=utf-8", dataType: 'json', chart: '#dvChart2' }],
                    current = 0;

        //declare your function to run AJAX requests
        function loadCharts()
        {

            //check to make sure there are more requests to make
            if ( current < ajaxes.length )
            {

                //make the AJAX request with the given data from the `ajaxes` array of objects
                $.ajax( {
                type: "POST",
                url: ajaxes[current].url,
                data: ajaxes[current].data,
                contentType: ajaxes[current].contentType,
                dataType: ajaxes[current].dataType,
                success: function ( r )
                {
                    $( ajaxes[current].chart ).html( "" );
                    var data = eval( r.d );
                    var el = document.createElement( 'canvas' );
                    $( ajaxes[current].chart )[0].appendChild( el );

                    //Fix for IE 8
                    if ( $.browser.msie && $.browser.version === "8.0" )
                    {
                        G_vmlCanvasManager.initElement( el );
                    }
                    var ctx = el.getContext( '2d' );
                    var chartoptions =
                    {
                        animateScale: true,
                        animationEasing: "linear",
                        showTooltips: true,
                        animationSteps: 120
                    }

                    var userStrengthsChart = new Chart( ctx).Doughnut( data, chartoptions );

                    //increment the `current` counter and   recursively call this function again
                    current++;
                    loadCharts();

                    },
                    failure: function ( response )
                    {
                        alert( 'There was an error.' );
                    }
                } );
            }
        }
        //run the AJAX function for the first time once    `document.ready` fires
        loadCharts();
}

.ASPX Code

<table>
    <tr>
        <td>Choose:
            <asp:DropDownList ID="DropDownList_1" runat="server">
            <asp:ListItem Text="Choose" Value="0" />
            <asp:ListItem Text="TestList" Value="1" />
            </asp:DropDownList>
        </td>
    </tr>
    <tr>
        <td>
            <div id="dvChart1">
            </div>
        </td>
        <td>
            <div id="dvChart2">
            </div>
        </td>
    </tr>
</table>

Like said in the top, the code worked fine, before i wanted to have 2 charts, means.. it's only the webmethod, i need to fix, if it's possible.. to loop it, so it will loop 2 times, and have an arraylist or something like that, so the ajax call is sending an extra number, like "index:0" and then i check if "index" is "0", then do this, or something like, i tried to do that.

I tried to give it index in "data", and then receive it via:

public static string GetChart (string chart, int index) 

Then it stopped working, while i tried, to do it, i'm not sure if i did it right, that's why i mention it, if someone know how to do it that way. I tried to do it, like with the jQuery code, the variable "array", so that i check with if/else, that "index" is 0 or 1, as i have 2 calls. But it couldn't handle it, nothing really happend.

Code Behind WebMethod (incl. index)

[WebMethod]
    public static string GetChart ( string chart, int index )
    {      
        string constr1 = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
        using ( SqlConnection con = new SqlConnection ( constr1 ) )
        {
            string query;
            if (index == 0)
            {
                query = string.Format("SELECT Value1,Color1,Highlight1,Label1 FROM Tuning WHERE FK_Resultat_ID = '{0}'", chart);
            }
            else
            {
                query = string.Format("SELECT Value2,Color2,Highlight2,Label2 FROM Tuning WHERE FK_Resultat_ID = '{0}'", chart);
            }
            //string query = string.Format("SELECT Value1,Color1,Highlight1,Label1 FROM Tuning WHERE FK_Resultat_ID = '{0}'", chart);
            //string query2 = string.Format("SELECT Value2,Color2,Highlight2,Label2 FROM Tuning WHERE FK_Resultat_ID = '{0}'", chart);
            using ( SqlCommand cmd = new SqlCommand ( ) )
            {
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                con.Open ( );
                using ( SqlDataReader sdr = cmd.ExecuteReader ( ) )
                {
                    StringBuilder sb1 = new StringBuilder();
                    sb1.Append ( "[" );
                    while ( sdr.Read ( ) )
                    {
                        sb1.Append ( "{" );
                        System.Threading.Thread.Sleep ( 50 );
                        sb1.Append ( string.Format ( "value:{0}, color: '{1}', highlight :'{2}', label :'{3}'" , sdr [ 0 ] , sdr [ 1 ] , sdr [ 2 ] , sdr [ 3 ] ) );
                        sb1.Append ( "}," );
                    }
                    sb1 = sb1.Remove ( sb1.Length - 1 , 1 );
                    sb1.Append ( "]" );
                    con.Close ( );            
                    return sb1.ToString ( );
                }
            }
        }
    }

jQuery (Incl. Index)

 var ajaxes = [{ url: 'CS.aspx/GetChart', data: "{chart: '" + $( '#<%= DropDownList_Motor.ClientID %>' ).val() + "'},{index:0}", contentType: "application/json; charset=utf-8", dataType: 'json', chart: '#dvChart1' }, { url: 'CS.aspx/GetChart', data: "{motor: '" + $( '#<%= DropDownList_Motor.ClientID %>' ).val() + "'},{index:1}", contentType: "application/json; charset=utf-8", dataType: 'json', chart: '#dvChart2' }],
                    current = 0;

Solution

  • I found out that, i just had to split them into 2 separate methods correctly, i had done it wrong earlier.