How to get account code to display in error message - javascript

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.

Related

ASP.Net MVC - Jquery Returning undefined

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);
}
}

How to pass the data from controller to view in mvc4

I am working on MVC4 application in that this is Actionresult returns json result but i want to pass variable objservice.callid on view but i am returning json can it is possible to get value on view with the help of json result or having any method to pass the value of variable to view but return type shoould be json result.
Here is code in controller:
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
ViewBag.id = objservice.callID;
return Json("Service Call = " + objservice.callID + " is Created successfully!");
} else {
return Json("This record is not added because of this error:=>" + result);
}
}
Here is code in view:
if (str.indexOf("successfully") != -1)
{
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", '#ViewBag.id');
} else {
if (str.search("added") != -1)
{
window.location.href = '#Url.Action("service_call", "service_call")';
} else {
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", callID);
}
}
I have try that objservice.callid variable store in viewbag and access on view it is not work.because view is not return controller.
can it is possible to store that variable in session variable then access on view.
Please give some suggestion ....
return as a json object with multiple values
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
return Json(new { message = "Service Call = " + objservice.callID + " is Created successfully!", id = objservice.callID);
}
else
{
return Json(new {message = "This record is not added because of this error:=>" + result, id = 0});
}
}
and use this in the post success to redirect ...

Get return value from Controller to javascript

What I want is, I want to check whether there is a file in the database or not. To do this I have a method in the controller which checks this and returns a boolean for the corresponding case. It looks like this:
public bool fileInDb(int empId)
{
using (SLADbContext db = new SLADbContext())
{
bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
if (file)
{
return true;
}
else
{
return false;
}
}
}
I simply just check if there is any file assigned to the given employee.
Now I would like to call this method from my javascript in the view, and get the return value, so that I can let the user know, if there is a file assigned to the selected employee or not. It may look like this:
$("#get-file").click(function() {
empId: $("#EmployeeSelect").val();
var fileInDb = // Get the return value from the method 'fileInDb'
if(fileInDb) {
// Let the user download the file he/she requested
var url = "#Url.Action("GetUploadedFile", "Competence")";
this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
} else {
alert("There is no file assigned to this employee.");
}
});
So my question now is, how do I get the get the return value from the method in the controller?
I would suggest few changes here:
Change your controller method to have return type ActionResult or JsonResult and I prefer JsonResult would be enough here and retrun Json response from controller and manipulate this method with $.get. You also need to change parameter to string because the parameter will be received as Json string.
public JsonResult fileInDb(string eId) //change signature to string and then convert to int
{
int empId=Convert.ToInt32(eId);
using (SLADbContext db = new SLADbContext())
{
bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
if (file)
{
return Json(new { result = true },JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { result = false},JsonRequestBehavior.AllowGet);
}
}
}
Now your ajax-get call would be as below:
$("#get-file").click(function() {
var eId= $("#EmployeeSelect").val();
$.get('/YourControllerName/fileInDb',{'eId':eId},function(response){
//you just need to get the response so $.get is enough to manipulate
//this will be called once you get the response from controller, typically a callback
if(response.result) //same result variable we are returning from controller.
{
// Let the user download the file he/she requested
var url = "#Url.Action("GetUploadedFile", "Competence")";
this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
} else {
alert("There is no file assigned to this employee.");
}
})
});
You need to set-up a single page script using your ASP fileInDb function and then communicate with that page using AJAX from the browser. If you're unfamiliar with AJAX I'd recommend using the jQuery implementation to get you started.
You can use jquery and ajax to achieve this. Call your method using an ajax call from your client code. Here is an example as a reference :Calling controller method from view
In the backend create a method to call, returning a JsonResult
public JsonResult fileInDb(int empId)
{
// your code - set fileExists to true/false
JsonResult returnObj = new JsonResult
{
Data = new
{
FileExists = fileExists ;
}
};
return Json(returnObj);
}
in your javascript code use $.ajax
$.ajax({
cache: false,
url: '#Url.Action("fileInDb")',
data: { 'empId': someVar },
type: 'POST',
success: function (response) {
if (response.Data.FileExists === true) {
// do something
} else {
// it was false
}
},
error: function (er) {
alert('Error!' + er);
}
});

Access string stored in a ViewBag on ajax success

I'm pretty new to ASP.NET MVC, I been searching for a solution for this problem but I couldn't find any proper solution. I found some solutions here on stachoverflow but nothing has worked with me. Here are some links:
Possible to access MVC ViewBag object from Javascript file?
MVC 3 - Assign ViewBag Contents to Javascript string
Here is my ajax call to the server:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Prize/UploadPassport');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText)
if (data.nationality != "") {
$('#PassportData tbody').append('<tr><td data-title="#Web.Resources.MyResources.PassportNationality">' + data.nationality + '</td><td data-title="#Web.Resources.MyResources.PassportName">' + data.passportName + '</td><td><a><i id="viewApp_' + data.passportID + '" class="fa fa-search fa-lg" onclick="ViewPassport(' + data.passportID + ');"> <iframe id="img_' + data.passportID + '" class="costumeiframe"></iframe></i></a></td></tr>');
}
else {
//var errorMsg = data.errorMsg;
ShowDataValidationMessage("#ViewBag.FileError"); //here i'm getting an empty string
}
}
}
In my server side action I set ViewBag.FileError based on some conditions here it is:
public ActionResult UploadPassport(HttpPostedFileBase FileUpload, string PassportCopyNationality)
{
if (Condition)
{
//Database access
}
else
{
if (isFileAlreadyExist)
{
ViewBag.FileError = Web.Resources.MyResources.PassportAttachmentValidationForFile;
}
else if (file.ContentLength > 3145728 || !isFileTypeLegal)
{
ViewBag.FileError = Web.Resources.MyResources.FileError;
}
return Json(new { nationality = "", passportName = "", passportID = "" });
}
}
catch (IOException io)
{
return Json("File not uploaded");
}
}
The problem that I'm getting an empty string
Firstly, #ViewBag.FileError (inside your script) is razor code which is parsed on the server before your view is sent to the client, so unless you include ViewBag.FileError = someValue in the GET method that generates this view, then it will always equate to null.
Secondly, your UploadPassport() method is returning a JsonResult not a view, so ViewBag does not even exist. You can resolve this by adding the value to the JsonResult, for example
return Json(new { fileError = someValue, nationality = "", passportName = "", passportID = "" });
and then access it in the script
ShowDataValidationMessage("data.fileError");

Passing array of arbitrary length to php through java and handling it within php

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..

Categories