Net MVC controller with this SQL query to return a value, in which I have a field that has Email.
The email is being passed and read by the query but the value isn't being transfered over the View with Json.
This is my controller code:
[HttpGet]
public JsonResult hhhhhh(string email)
{
SqlConnection cn = new SqlConnection(#"Data Source=Example;Initial Catalog=Example;User ID=example;Password=example;");
SqlCommand cmd = new SqlCommand("SELECT anr.Name FROM AspNetUsers anu " +
"LEFT JOIN AspNetUserRoles anur ON (anur.UserId = anu.Id) " +
"LEFT JOIN AspNetRoles anr ON (anr.Id = anur.RoleId) " +
"WHERE anu.Email = '" + email + "'", cn);
cn.Open();
cmd.ExecuteNonQuery();
return Json(cmd, JsonRequestBehavior.AllowGet);
}
This is my View:
<script>
$(document).ready(function() {
var str = '#User.Identity.GetUserName()'; //returns the current email
$.getJSON("/Student/hhhhhh", {
email: str
}, function(data) {
alert(data.cmd)
if (data == "Admin") {
alert("asddsadas");
} else {
alert("n deu");
}
/* if (data = "Admin") {
alert("DEUEUEUEUEU");
}
else {
alert("ndeu");
}*/
});
</script>
This is returning me an undefined value.
Can you guys identify the error ?
Use
$getjson(
// Send data from here
).done(
// On success whatever you want to do
).fail(
// On fail whatever you want to do
)
Your request might be getting failed. Using getjson this way you can exactly check where request is going is failing or getting success than we can debug further.
ExecuteNonQuery is supposed to be used for queries that does not return any data like update, insert, delete... If you want to execute a select query you have to use ExecuteReader and get your results as a DataReader object, Also you can't pass directly an SqlCommand Object to JsonResult You need a Dictionary Or a List of objects, try this code:
[HttpGet]
public JsonResult hhhhhh(string email)
{
string connectionString = #"Data Source=Example;Initial Catalog=Example;User ID=example;Password=example;";
// note the 'using' statement
using( SqlConnection connection = new SqlConnection(connectionString) ) {
string query = "SELECT anr.Name FROM AspNetUsers anu " +
"LEFT JOIN AspNetUserRoles anur ON (anur.UserId = anu.Id) " +
"LEFT JOIN AspNetRoles anr ON (anr.Id = anur.RoleId) " +
"WHERE anu.Email = #email";
SqlCommand command = new SqlCommand(query, connection);
// note how to pass parameter to SqlCommand object
command.Parameters.Add("#email", SqlDbType.NVarChar, 50);
command.Parameters["#email"].Value = email;
connection.Open();
// We can use a Dictionary for example to produce json result
var dict = new Dictionary<string, object>();
using( SqlDataReader reader = command.ExecuteReader() ) {
while (reader.Read()) {
for (i = 0; i < reader.FieldCount; i++) {
dict.Add(reader.GetName(i), reader.GetValue(i));
}
}
}
return Json(dict, JsonRequestBehavior.AllowGet);
}
}
Related
I have problem with create grid (without kendo)
I try to make a dictionary. I have a list of word and pass this to ajax JavaScript and show it to grid in view. but I don't know how to work with this :(.
thanks all
this is my controller
public ActionResult ChekingInBank(string username, string password, string datasource, string bnkname, string SqlQuery)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Server"] = datasource;
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
builder["Integrated Security"] = false;
builder.InitialCatalog = bnkname;
builder.Password = password;
builder.UserID = username;
List<TranslateViewModel> translateViewList = new List< TranslateViewModel>();
WebGrid TranslateGrid = new WebGrid();
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(SqlQuery, con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
TranslateViewModel translateView = new TranslateViewModel();
translateView.id = dr[0].ToString();
translateView.word = dr[1].ToString();
translateView.translate = dr[2].ToString();
translateViewList.Add(translateView);
}
if (translateViewList.Count>0)
{
return Json( new {translateViewList = translateViewList, JsonRequestBehavior.AllowGet);
}
else
{
return Json("No Record Found");
}
}
}
}
}
JavaScript
function chekingInBank() {
var translate = $("#eWord").val();
var bnkname = $("#combo").val();
var username = $("#Username").val().trim();
var password = $("#password").val();
var datasource = $("#Datasource").val();
var SqlQuery = "select * from lego.LocalizationView where Word =N'" + translate + "'";
if (bnkname) {
$.ajax({
url: 'Home/chekingInBank?' + "Username=" + username + "&Password=" + password + "&databaseConString=" + datasource + "&bnkname=" + bnkname,
data: {
bnkname: bnkname,
username: username,
password: password,
datasource: datasource,
SqlQuery: SqlQuery
},
//dataType: "json",
type: "get",
datatype: "json",
traditional: true,
success: function (data)
{
`I have problem with this `
debugger;
if (data != "No Record Found") {
$('#gridContent').html(data);
}
else {
alert('No Record Found')
}
},
});
}
else
{
//do nothing
}
}
and my view
and this :(((
#{
var grid = new WebGrid(VeiwModeList, canPage: true, rowsPerPage: 5,
selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent");
grid.Pager(WebGridPagerModes.All);
}
#grid.GetHtml(
tableStyle: "webGrid",
columns: new[]
{
grid.Column("id"),
grid.Column("Word"),
grid.Column("Translate")
});
First of all, you should never send such data like database's username, password, database name and SQL query from javascript to server. This is dangerous because anyone gain access to your database. For example one can change your query to something like
var SqlQuery = "TRUNCATE TABLE lego.LocalizationView"
and your server code will execute this destructive query.
Next, I think you have some misunderstanding with using WebGrid. For example, your controller's method returns JSON, but in js code you put this JSON as html into HTML element:
$('#gridContent').html(data);
Also you didn't mention whether your controller action is decorated with HttpGet attribute.
I advise you to find and implement (reproduce) a working example of using WebGrid with AJAX requests, for example what I've googled: link
In this example Entity Framework is used to connect to data, but you can begin with returning static JSON in your controller method, to verify this all works altogether:
[HttpPost]
public JsonResult AjaxMethod(int pageIndex)
{
CustomerModel model = new CustomerModel();
model.PageIndex = pageIndex;
model.PageSize = 10;
model.RecordCount = 2; //number of records - for pager
int startIndex = (pageIndex - 1) * model.PageSize;
model.Customers = new List<Customer> //some random static data
{
new Customer
{
CustomerID = "AAAA",
City = "City 1",
ContactName = "Contact Name 1",
Country = "Country 1"
},
new Customer
{
CustomerID = "BBBB",
City = "City 2",
ContactName = "Contact Name 2",
Country = "Country 2"
}//, add some more dummy customer's info
};
return Json(model);
}
And when you'll reproduce it you can change the CustomerModel to your class, change POST to GET, connect to your database, modify grid columns and so on.
I have made requests to a Java web service using AJAX:
<script>
function loadcaptcha() {
$("#spmsg").html("");
$("#txtCaptcha").val("");
var inputValObj = {};
inputValObj.flag = "LD";
inputValObj.captcha = "NA";
inputValObj.hash = "NA";
inputValObj.servicename = "Rural";
var inputVal = JSON.stringify(inputValObj);
$("#target").show();
$.ajax({
url : local_url+'/captchavalue?jsoncallback=?',
data:encodeURIComponent(inputVal.toString()),
type : 'POST',
dataType : 'jsonp',
contentType : "application/json",
success : function(data) {
setTimeout(myFunction, 100);
if (data.statusCode == "INPUT_ERR") {
alert("Data Error");
}else if(data.statusCode == "CAPTCHA_ERR"){
alert("Authenticate Problem");
}
else{
var captcha=data.captcha;
if(getparameter==="8"){
$("#captchaImg1").attr("src","data:image/gif;base64," + captcha);
$("#hashval1").val(data.hash);
}else if(getparameter==="3"){
$("#captchaImg_fmb").attr("src","data:image/gif;base64," + captcha);
$("#hashval_fmb").val(data.hash);
}
else if(getparameter==="4"){
$("#captchaImg_rev").attr("src","data:image/gif;base64," + captcha);
$("#hashval_rev").val(data.hash);
}
else if(getparameter==="7"){
$("#captchaImg_is").attr("src","data:image/gif;base64," + captcha);
$("#hashval_is").val(data.hash);
}
else if(getparameter==="11"){
$("#captchaImg_ec").attr("src","data:image/gif;base64," + captcha);
$("#hashval_ec").val(data.hash);
}
else if(getparameter==="17"){
$("#captchaImg_crt").attr("src","data:image/gif;base64," + captcha);
$("#hashval_crt").val(data.hash);
}
else{
$("#captchaImg").attr("src","data:image/gif;base64," + captcha);
$("#hashval").val(data.hash);
}
}
},
error : function(jqXHR, exception) {
alert("Error Occured not connected");
}
});
}
</script>
Calls to the Java service works well until a few extra lines of Java code is added:
#POST
#Path("/captchavalue")
public Response captchavalue(
#QueryParam("jsoncallback") String jsonvalue, #Context HttpServletResponse serverResponse,
#Context HttpHeaders headers, #Context HttpServletRequest request,
String inputVal) throws ParseException,
URISyntaxException, SQLException,IOException {
String inputVal1 = URLDecoder.decode(inputVal, "UTF-8");
System.out.println("inputVal ---->"+inputVal1);
serverResponse.addHeader("Access-Control-Allow-Credentials", "true");
serverResponse.addHeader("Allow-Control-Allow-Methods","POST");
serverResponse.addHeader("Access-Control-Allow-Headers",
"X-Requested-With,Content-Type,Origin");
serverResponse.addHeader("Access-Control-Max-Age", "3600");
serverResponse.addHeader("X-Frame-Options", "DENY");
serverResponse.addHeader("Content-Security-Policy", "frame-ancestors 'none'");
serverResponse.addHeader("Content-Type", "application/json");
serverResponse.setHeader("cache-Control","no-cache,no-store,must-revalidate");
serverResponse.setHeader("Pragma","no-cache");
serverResponse.setHeader("Expires","0");
String responsee = "";
String resp = "";
boolean respflag=getUrlPath(serverResponse, request);
JSONObject obj1 = new JSONObject();
if(respflag){
String refererURI = new URI(request.getHeader("referer")).getPath();
serverResponse.addHeader("Access-Control-Allow-Origin", refererURI);
JSONParser parser = new JSONParser();
Object obj = parser.parse(inputVal1);
JSONObject json = (JSONObject) obj;
String flag = json.get("flag").toString();
String captchaval=json.get("captcha").toString(); //changed on 13/7/2022 .toUpperCase()
System.out.println("capitalized ---->"+captchaval);
String hashval = json.get("hash").toString();
String servicename = json.get("servicename").toString();
System.out.println("flag ---->"+flag);
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String fmb_url=rb.getString("fmburl");
List<String> hashvalue = memcached_data(flag,captchaval,hashval,request);
if(flag.equals("SB")){
System.out.println("hashval -new--->"+hashvalue.get(0));
System.out.println("servicename--->"+servicename);
if( hashvalue.get(0).equals("VAL")){
String outvalue="";
if(servicename.equals("Rural")) {
outvalue=getAllServiceRural(inputVal);
}else if(servicename.equals("Urban")) {
String code =json.get("code").toString();
if(code.equals("sursearch") || code.equals("oldsursearch") || code.equals("Urban_Applstatus")){
outvalue=getUrbanService(inputVal);
}
}
else if(servicename.equals("Fmb")) {
JSONParser dist_parse = new JSONParser();
Object inp_obj = dist_parse.parse(inputVal);
JSONObject json1 = (JSONObject) inp_obj;
String req = (String) json1.get("req");
String district = (String) json1.get("districtCode");
String taluk = (String) json1.get("talukCode");
String village = (String) json1.get("villageCode");
if (req.equals("survey")) {
String survey_no = (String) json1.get("surveyno");
outvalue = fmb_url+"/pdf/"+ district+taluk+village+survey_no;
System.out.println("Outvalue1");
String remoteadd = request.getRemoteHost();
String s=createtoken(outvalue,survey_no,remoteadd);
outvalue =outvalue+"&token="+s;
}
if (req.equals("subdiv")) {
String survey_no = (String) json1.get("surveyno");
String subdiv_no = (String) json1.get("subdivno");
outvalue = fmb_url+"/pdf/"+ district+taluk+village+survey_no+"/"+subdiv_no;
System.out.println("Outvalue2");
String plotNo = survey_no + "/" + subdiv_no;
String remoteadd = request.getRemoteHost();
String s=createtoken(outvalue,plotNo,remoteadd);
outvalue =outvalue+"&token="+s;
}
}
else if(servicename.equals("Revenue")) {
JSONParser dist_parse = new JSONParser();
Object inp_obj = dist_parse.parse(inputVal);
JSONObject json1 = (JSONObject) inp_obj;
String district = (String) json1.get("districtCode");
String taluk = (String) json1.get("talukCode");
String village = (String) json1.get("villageCode");
String surveyNo = (String) json1.get("surveyNo");
String subdivision = (String) json1.get("subdivision");
String survey_no = (String) json1.get("surveyno");
outvalue = get_revenue_details(district,taluk,village,surveyNo,subdivision);
}else if(servicename.equals("Court")) {
outvalue=getCourtService(inputVal);
}
else if(servicename.equals("eadangal")) {
outvalue=geteadangalService(inputVal);
}else if(servicename.equals("EC")) {
outvalue=IgrsEcservice(inputVal);
}else if(servicename.equals("town_prop")) {
outvalue=tndtp_get_assessment(inputVal);
}
else if(servicename.equals("gcc_prop")) {
outvalue=get_gcc(inputVal);
}
else if(servicename.equals("ulb_prop")) {
outvalue=get_dcb(inputVal);
}
else if(servicename.equals("metrowater")) {
outvalue=get_chennaimetrowater(inputVal);
}
else if(servicename.equals("cma_water")) {
outvalue=get_cmawater(inputVal);
}
else if(servicename.equals("water_dtp")) {
outvalue=get_dtpwatertax(inputVal);
}
else if(servicename.equals("eb")) {
JSONParser dist_parse = new JSONParser();
Object inp_obj = dist_parse.parse(inputVal);
JSONObject json1 = (JSONObject) inp_obj;
String service_type = (String) json1.get("service_type");
if(service_type.equalsIgnoreCase("H")){
outvalue=get_eb_htbill(inputVal);
}else{
outvalue=get_eb_billdetails(inputVal);
}
}
//System.out.println("outvalue ---->"+outvalue);
obj1.put("outputvalue", outvalue);
}
obj1.put("statusCode", hashvalue.get(0));
obj1.put("result", hashvalue.get(1));
}else if(flag.equals("LD") || flag.equals("RF")){
obj1.put("statusCode", hashvalue.get(0));
obj1.put("captcha", hashvalue.get(1));
obj1.put("hash",hashvalue.get(2));
}
else
{
obj1.put("statusCode", "ER");
obj1.put("captcha", "Error");
obj1.put("hash","Error");
}
resp = jsonvalue + "(" + obj1.toString() + ")";
}else
{
responsee = "Unauthorized Access!!!";
return Response.ok(responsee, MediaType.TEXT_PLAIN).build();
}
return Response.ok(resp, MediaType.TEXT_PLAIN).build();
}
The code works well until the following lines are added to the else-if blocks of the Java code given above:
1.
String remoteadd = request.getRemoteHost();
String s=createtoken(outvalue,plotNo,remoteadd);
outvalue =outvalue+"&token="+s;
String plotNo = survey_no + "/" + subdiv_no;
String remoteadd = request.getRemoteHost();
String s=createtoken(outvalue,plotNo,remoteadd);
outvalue =outvalue+"&token="+s;
As soon as the above code is added, the AJAX call from the application throws a 404 error for the same URL which was showing 200 status before the code addition.
Additionally, the 404 error is thrown only for the AJAX call from the web app whereas the same URL shows 200 status code when called from Postman or Talend API.
Tried adding headers using "serverResponse.addHeader()" in Java but only to get the 404 error again.
Got the solution to this problem long ago.
The solution was to add the relevant JAR files to the WEB-INF/lib folder in addition to adding the same JAR files to the project build path.
Note: It is insufficient that the JAR files is added to the project build path alone. That's what triggered the error. Adding the JAR files to the WEB-INF/lib folder solved the error.
I am trying to create some validation for a form.
The user can enter in account code, name, address, etc for companies. I need to create the validation for the name text box. If they enter a name that already exists then display the message "This name already exists on account code: " then display the account code.
The problem is I don't know how to get the account code of the company.
<asp:TextBox runat="server" ID="txtName" onblur="CheckIfNameExists(this.value)"></asp:TextBox>
function CheckIfNameExists(Name) {
PageMethods.CheckIfNameExists(Name,
OnCheckIfNameExists,
null
);
}
function OnCheckIfNameExists(result){
if(result){
alert("This Name already exists!");
}
else{
}
}
Web method for checking bool:
[WebMethod]
public static bool CheckIfNameExists(string Name)
{
try
{
if(Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return true;
}
}
Right now the code just checks if the name already exists in the database. But I want to get the account code of the name in the database.
This is the code that searches the database:
public static bool CheckIfNameCreditorExists(int CompanyID, string Name)
{
DataSet ds = new DataSet();
string sql = "proc_CheckIfACCreditorExists";
string query = "SELECT c.* " +
" FROM Creditor c " +
" WHERE c.Company_ID = " + CompanyID + " AND c.Name LIKE '" + Name + "' ";
DataTable dt = new DataTable();
using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, DataUtils.ConnectionStrings["TAT"]))
{
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = query;
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
return true;
}
return false;
}
}
Change the return type of your method to string from bool
bool is replaced with string in below code snippet
public static string CheckIfNameCreditorExists(...
Now, change your return type. I am just rewriting your return lines only.
if (dt.Rows.Count > 0)
{
//Make sure to use right column name here
return string.format("{Exist: true, AccountNo: {0}}", dt.Rows["AccNo"]);
}
return return "{Exist: false, AccountNo: null}";
Finally, modify javascript method as below.
function OnCheckIfNameExists(result){
if(result.Exist){
alert("This Name already exists!");
alert("Associated Account Number is: " + result.AccountNo);
}
else{
}
}
Only possible issue is: Sometimes, returned json string will not be parsed automatically. In that case rather than directly referring result, you can parse Json to object and use its properties in javascript method.
I would call the method using jquery.
jquery ajax
function CheckIfNameExists(Name) {
$.ajax("CheckIfNameCreditorExists?companyID=[value]&name=[value]").done(
function(result) {
if(result){
alert("This Name already exists!");
}
else {
}
});
}
You can do it in POST or GET as you wish.
I have a HashMap of event-outcome pairs stored as two strings, where the first string can be any positive integer, this represents the id, and the second string is the possible outcome. This can be '1' 'X' or '2'. So for example this would be a valid HashMap:
32
9X
81
12X
I'm trying to check every one of these Id's with my database using php to check if the outcome in the hashmap is the same as the outcome in the database for that event. The outcomes in the database stored as 'Result' can be either '1' 'X' or '2' or 'null' if the event didn't occur yet. At the moment I'm using a for loop as shown below and creating a new Httpconnection for every ID. This works, however it is incredibly inefficient and I receive "connection refused, TIMEOUT" errors if I try to check a lot of data. I'm sure this can be done by passing an array of ID strings to the php and checking each ID within the php and returning an array of event-outcome pairs back to the android app. However, although I found ways on how to fo pass arrays to php, I have no idea how to incorporate the varying length of the array as in each case the HashMap may be of different length, and I don't know how to work through the array of arbitrary length in php itself. Below is my java class and two php files. Thanks for the help in advance. :)
CheckBet.java
public String checkbetoutcome() {
for (String x : bet.keySet()) {
Log.d("X", x);
currentitem = x;
new LoadAllGamet().execute();
}
for (String x : statuses) {
Log.d("testaaaaa",x);
if (x.equals("open")) {
finalstatus = "open";
}
if (x.equals("lost")) {
finalstatus = "lost";
break;
}
}
return finalstatus;
}
class LoadAllGamet extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_check_bet);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 2000000);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", currentitem));
Log.d("CURRENTITEM",currentitem);
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Responsecxxx:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sbsssssssssss", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
game = jObj.toString().substring((jObj.toString().indexOf(':')+1),(jObj.toString().length()-1));
Log.d("GAME",game);
Log.d("jsonsssssssssss", jObj.toString());
if (game.contains("null")) {
String asa = game.substring(game.indexOf("\"") + 1, game.length());
game = asa;
}
else {
String asa = game.substring(game.indexOf("\"")+1,game.length()-1);
game = asa;
}
Log.d("CURRENTITEMSTATUS",game);
Log.d("CURRENTITEAMREAL", bet.get(currentitem));
if (game.equals("null")) {
status = "open";
}
else if (game.equals(bet.get(currentitem))) {
status = "won";
}
else {
status = "lost";
}
Log.d("Status", status);
statuses.add(status);
status = "open";
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
}
// CHANGE THIS AT THE END
}
}
Check_Bets_Handler.php
<?php
if (isset($_POST['param'])) {
// get tag
$array = array();
$array= $_POST['param'];
// include db handler
require_once 'include/Check_Bets.php';
$db = new Check_Bets();
foreach($array as $id) {
// response Array
$result = $db->checkuserbets($id);
$response["bet"] = array();
array_push($response["bet"], $result);
}
echo json_encode($response);
}
else {
$response["error"] = TRUE;
$response["error_msg"] = "the response is null!";
echo json_encode($response);
}
?>
Check_Bets.php
<?php
class Check_Bets {
function __construct() {
require_once 'DB_Connect.php';
$this->db = new DB_Connect();
$this->db->connect();
}
function __destruct() {
}
public function checkuserbets($id) {
$conn=mysqli_connect("****", "****", "**","******");
$result = mysqli_query($conn,"SELECT Result FROM gamelist WHERE gid = '$id'");
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
return mysqli_fetch_array($result,MYSQLI_ASSOC);
}
}
}
?>
I'm not 100% sure if this solves your purpose, but I have passed an array of uncertain length, and also associative arrays to php using a simple technique.
Assume param to be the key to be the hashmap. You can access it in the PHP code as param [ index ] to obtain value.
Here's a snippet for you:
//Assuming you've created a HashMap mHashMap
for (String id : mHashMap.keySet()) {
nameValuePair.add(new BasicNameValuePair("param" + "[" + id + "]" , mHashMap.get(id)));
You can retrieve this associative array in your PHP script as $_POST["param"]. Store this in a variable array and access using array["id"].
Hope it helps. Please let me know if you face any trouble with this..
Like for a single value i easily work, or also true false condition.
like getting a single value from database
string i = "";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SelectPass";
cmd.Parameters.AddWithValue("#userID", context.Request.QueryString["id"]);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
i = reader["Password"].ToString();
}
reader.Close();
conn.Close();
if (i == "")
{ context.Response.Write("False"); }
else
{
context.Response.Write(i);
}
and in client side easily showing the value in one variable.
function abc()
{
$.get('\HandlerResetPass.ashx?id=' + $('#txtUserId').val()+'&lbl='+ $('#lblPasswo').val(), callback);
function callback(data)
{
if (data == "False")
{
alert('ID doesn\'t exist try again..!')
return false;
}
else
{
$('#tblPassWord').show();
$('#tblprofile').hide();
role = data;
}
}
}
But how working with A dataset.
Your question is not clear. What exactly your HandlerResetPass is returning? if is a list of object you should define a class with the structure of your data, serialize json for example, the in your client side, jquery can go through your list ,and process your data.
You can return JSON and then parse it to an object using jQuery's $.parseJSON.
For instance,
// data = '{"field1": "value1", "field2": false}'
function callback(data) {
dataObj = $.parseJSON(data)
if(dataObj["field2"] == false) {
// do something
}
else {
// do something else
}
}
Here is my having some bit of code for getting dataset values.
For that first you have to create class object for that require table data.
Like below
Class MyData
Public ID As Integer
Public Name As String
Public ContactNo As String
End Class
Now you need to define Structure for BasicOuputObject. object of this BasicOuputObject
is sent over from server side to client.
Public Structure BasicOuputObject
Dim status As String
Dim errorMessage As String
Dim strMessage As String
Dim obj As Object
End Structure
Now you have to use below function for getting datatable.
Public Sub GetMyData()
Dim objOutput As New BasicOuputObject
Dim objCommand As New SqlCommand
Dim lstMyData As New List(Of MyData)
Dim objMyData As MyData
Dim objConn As New SqlConnection("Pass Connection String")
objCommand.CommandText = "select ID ,Name ,ContactNo from Customers"
objCommand.Connection = objConn
objConn.Open()
Dim m_rdrReader As SqlDataReader = objCommand.ExecuteReader()
If m_rdrReader.HasRows Then
While m_rdrReader.Read()
objMyData = New MyData
objMyData.ID = m_rdrReader(0)
objMyData.Name = m_rdrReader(1)
objMyData.ContactNo = m_rdrReader(2)
lstMyData.Add(objMyData)
End While
End If
m_rdrReader.Close()
m_objConn.Close()
objOutput.errorMessage = ""
objOutput.obj = lstMyData
objOutput.strMessage = "success"
Dim objSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
HttpContext.Current.Response.Write(objSerialiser.Serialize(objOutput))
HttpContext.Current.Response.End()
End Sub
End Class
Now modify javascript as below. use can use any machnism for calling above function
from the handler.
function abc() {
$.get('\HandlerResetPass.ashx?id=' + $('#txtUserId').val() + '&lbl=' + $('#lblPasswo').val(), callback);
function callback(data) {
if (data.status == "success") {
for (var row, i = 0; row = data.obj[i]; i++) {
//Create the row strings using the CreateAddModelRowString function
// Process row var for as per usage.
}
}
else {
alert('ID doesn\'t exist try again..!')
return false;
}
}
}
Hope this will help you. happy coding....
we can return data set from handler by useing that king of work.
public void ProcessRequest(HttpContext context)
{
string connect = (#"Connection string");
using (SqlConnection conn = new SqlConnection(connect))
{
using (SqlCommand cmd = new SqlCommand("", conn))
{
string i = "";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Selecttest";
cmd.Parameters.AddWithValue("#_ID", context.Request.QueryString["id"]);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
string ans = "";
ans = Convert.ToString(ds.Tables[0].Rows[0]["name"])+",";
ans += Convert.ToString(ds.Tables[0].Rows[0]["age"]);
context.Response.Write(ans);
}
}
}
Or in client side we get these two values by this method.
function abc()
{
$.get('\Handler1.ashx?id=' + $('#txtID').val(), callback);
function callback(data)
{
var arr = data.split(',');
$("#name").html(arr[0]);
$("#age").html(arr[1]);
}
}