I made a Web service in which I have a function to count some data in my SQL data base. Here the code of my WebService.asmx :
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public int SalesNumberMonth(int i)
{
int total = 0;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);
try
{
string request = "SELECT * FROM sales_Ventes V INNER JOIN sys_AnneesFiscales A ON V.AnneeFiscale = A.Code INNER JOIN sys_Mois M ON V.Mois = M.Code WHERE M.Code='" + i + "'" + " AND Active = 'true'";
connection.Open();
SqlCommand Req = new SqlCommand(request, connection);
SqlDataReader Reader = Req.ExecuteReader();
while (Reader.Read())
{
total++;
}
Reader.Close();
}
catch
{
}
connection.Close();
return total;
}
}
and here my script.js :
var sin = [], cos = [];
for (var i = 1; i < 13; i += 1) {
GestionPro.WebService1.SalesNumberMonth(i, function (e) { sin.push([i, e]); } ,function (response) { alert(response); } );
cos.push([i, 2]);
}
var plot = $.plot($("#mws-test-chart"),
[{ data: sin, label: "Sin(x)²", color: "#eeeeee" }, { data: cos, label: "Cos(x)", color: "#c5d52b"}], {
series: {
lines: { show: true },
points: { show: true }
},
grid: { hoverable: true, clickable: true }
});
My probleme is on this line :
GestionPro.WebService1.SalesNumberMonth(i, function (e) { sin.push([i, e]); } ,function (response) { alert(response); } );
When I swap the two functions, the alerts are displayed well but in this order I can’t add the value of my function in sin[]. I should miss something but don’t know what …
There are enormously lots of issues with your code:
SELECT *and then counting on the client code in a loop instead of using theCOUNTSQL aggregate functionThe issues being mentioned, let’s start by fixing them.
Let’s first fix the server side code:
OK, you will notice now the new method that I added and which allows to calculate totals for a number of months and returning them as an array of integers to avoid wasting bandwidth in meaningless AJAX requests.
Now let’s fix your client side code: