check duplicate data with javascript - javascript

i am writing web application in asp.net . i have a input form . i want when the client click on save Button before insert, check this data is in data base or not . i have written it with code behind . but i want do this with java script because when i i use code behind the page refresh . this is my .net code for check duplicate data:
SqlCommand commandrepeat1 = new SqlCommand("Select code from CmDet where code = " + txtcode.Text + " and company = " + DataBase.globalcompany.ToString() + " order by code desc");
commandrepeat1.Connection = objconnection;
objconnection.Close();
objconnection.Open();
SqlDataReader drmax1;
drmax1 = commandrepeat1.ExecuteReader();
drmax1.Read();
if (drmax1.HasRows)
{
MessageBox.Show("Duplicate data . try again!!! ");
txtcode.Focus();
objconnection.Close();
return;
}
objconnection.Close();
}
catch
{
objconnection.Close();
}

You should have your ASP.NET button implement both the OnClick event (to execute server-side code once it is determined that there is not duplicate data) and OnClientClick event (to execute your JavaScript that will call to check if there is duplicate data).
I suggest the following:
In JavaScript, add a jQuery click event to your button, like this:
$( "#myButton" ).click(function() {
});
Note: I have assumed the name of your button to be myButton, change it to match the ID of your button in markup.
Now you will need to call server-side to execute your logic to look for duplicate data. I recommend using ASP.NET AJAX Page Methods invoked via the jQuery .ajax() function, like this:
$.ajax({
type: "POST",
url: "YourPage.aspx/DoesDataExist",
data: "{'codeValue': $('#myTextBox').val()}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if(msg.d) {
// This is a duplicate, alert user with message
// Block the server-side click from happening with return false;
return false;
}
}
});
Finally, we need to build the server-side code that will handle the page method called by the jQuery above, like this:
[WebMethod]
public static bool DoesDataExist()
{
SqlCommand commandrepeat1 = new SqlCommand("Select code from CmDet where code = " + txtcode.Text + " and company = " + DataBase.globalcompany.ToString() + " order by code desc");
commandrepeat1.Connection = objconnection;
objconnection.Close();
objconnection.Open();
SqlDataReader drmax1;
drmax1 = commandrepeat1.ExecuteReader();
drmax1.Read();
if (drmax1.HasRows)
{
objconnection.Close();
return true;
}
objconnection.Close();
return false;
}

Related

AJAX query not always updating information consistently

I am experiecing some issues with AJAX updating the page. The actual data in the database is updated but this is not always reflecting in real time on the web page.
For example, I have the following event:
$("#add_note").click(function(e) {
//e.preventDefault();
$("#add_note_form").validate({
rules: {
contact_note: {
required: true
}
},
submitHandler: function(form) {
contact.modal_update({
'obj' : $('#add_note_form'),
'uri' : '/contact/add_note/'
});
}
});
});
This function when a new note is created calls a callback to validate the form fields first and then if successful calls a callback inside a seperate class to conduct the update. See the modal_update class below:
// Update modal
this.modal_update = function(data)
{//
// Declare a few variables for the data object we've received
obj = data.obj // The form element to serialize
uri = data.uri;
// Get the form ID from the data-target attribute
id = obj.attr('data-target');
// URL to send to
url = this.site_url + uri + id;
// The form object
this.post_data(obj.serialize(),url);
// Hide Modal
obj.closest('.modal').modal('hide');
// Refresh
this.refresh();
}
This then figures out the correct route to ajax and calls a ajax call back inside the same class:
// AJAX post
this.post_data = function(obj,uri)
{
$.ajax({
data: obj,
dataType: 'json',
type: 'post',
url: uri,
headers: { "cache-control": "no-cache" },
cache: false,
success: function (response) {
if (response.success == true)
{
$("#alert_success .msg").html(response.message);
$("#alert_success").fadeIn(200).delay(2000).fadeOut(200);
}
else
{
$("#alert_error .msg").html(response.error);
$("#alert_error").fadeIn(200).delay(2000).fadeOut(200);
console.log(response.error);
}
}
});
}
I am then running another class callback to "refresh" the data in all the elements on the page:
this.refresh = function()
{
// Refresh the ajax requests
this.get_contact_data();
this.get_notes();
this.get_contact_log();
this.get_contact_tasks();
}
This class re loads the functions which run on page load to get the inial data into the tables/fields on the page. See "get_notes" below:
// Get notes
this.get_notes = function()
{
// Get all notes and populate table
var log_uri = this.site_url + "/contact/get_notes/" + this.contact_id;
this.get_data(log_uri,function(data) {
notes = $("#contact_notes ul");
notes.empty("");
// Populate the contact fields, assuming there is a result to play with
if (data != false) {
//alert(JSON.stringify(data));
$("#notes-tab .count").html("(" + data.length + ")");
$.each( data, function( key, value ) {
notes.append("<li class='list-group-item' modal-id='editNoteModal' data-target='" + value.ID + "'><div class='row'><div class='col-lg-3'><i class='fa fa-sticky-note mr-3'></i>" + value.timestamp + "</div><div class='col-lg-7'>" + value.note + "</div><div class='col-lg-2'><a href='#' class='edit mr-3'><i class='fa fa-edit mr-1'></i>Edit</a><a href='#' class='delete'><i class='fa fa-times mr-1'></i>Remove</a></div></div></li>");
});
console.log('Notes loaded');
} else {
notes.append("<li>There are currently no notes for this contact</li>");
}
});
}
Now the problem:
For some reason this does not update consistently in real time. The data is updated fine on the server side but on the client side the update/refresh does not always update. I might add a note and get a correct update response but the refresh method seems to be receiving the old data and always be one note behind. So the next time I add a note, the one I added before then appears and so forth.
Another problem I am experiencing is the methods seem to stack on each event so if I add one note (or one of the other methods) I will see the console say "notes loaded" but on the second note it says "notes loaded" twice, then on the 3rd note added 3 times and so forth.
I am sure there must be something fatal flaw in the design of my code here but I am not experienced enough with javascript/jquery to notice what direction I am going wrong so I can fix it.
I thought that this was an issue with ajax caching and not refreshing the result so I have adjusted the ajax request as cache none and also to send no cache headers. I am running in wamp.
In your case, your refresh code will always run before your data got updated. Because ajax is asynchronous so the code behind and below ajax will always execute nearly the time your ajax running.
At the time you run your post_data function to call the API, the refresh function got run too. So it's done before your data got updated.
You should run refresh function inside ajax callback. For example:
this.post_data = function(obj,uri, callback)
{
$.ajax({
data: obj,
dataType: 'json',
type: 'post',
url: uri,
headers: { "cache-control": "no-cache" },
cache: false,
success: function (response) {
if (response.success == true)
{
$("#alert_success .msg").html(response.message);
$("#alert_success").fadeIn(200).delay(2000).fadeOut(200);
}
else
{
$("#alert_error .msg").html(response.error);
$("#alert_error").fadeIn(200).delay(2000).fadeOut(200);
console.log(response.error);
}
callback();
}
});
}
And in modal_update, you pass refresh function to post_data as a callback:
this.modal_update = function(data)
{//
// Declare a few variables for the data object we've received
obj = data.obj // The form element to serialize
uri = data.uri;
// Get the form ID from the data-target attribute
id = obj.attr('data-target');
// URL to send to
url = this.site_url + uri + id;
// The form object
this.post_data(obj.serialize(),url, this.refresh);
// Hide Modal
obj.closest('.modal').modal('hide');
}
You should read more about asynchronous ajax. You can use other tricky solution is setTimeout to run this.refresh but I do not recommend that because you not sure when the update is done.

Ajax POST working, but php document cannot get data variable

When I post something, the network tab of chrome shows that the post is going through with the correct variables, but on the php end, the POST global is empty, and the method on the page is GET for some reason. I hope I am not just missing something obvious, I spent like 4-5 hours troubleshooting. What is occuring, or is suppose to, is that when you type anything in the searchbox, an event listener in the js file triggers and POSTs the value of the search box to the php of the storepage.php. The search bar itself is actually on a seperate php file which makes a header for every html page, but the php that queries the database is in the storepage.php
Picture of network results from entering items into search (notice variable searchInput at bottom of image)
This is where the Ajax POST happens: searchItUp.js
$(document).ready(function() {
console.log("Document Ready. Listening for search bar key presses...");
$('.SearchBar').keyup(function() {
console.log("Key pressed.");
var searchBoxValue = document.getElementById('superSearcher').value;
console.log("Current searchbox value: " + searchBoxValue);
jQuery.ajax({
method: "post",
url: "storepage.php",
data: {searchInput: searchBoxValue},
datatype: "text",
success: function () {
console.log("Ajax functioning properly...");
$('.content').load(document.URL + ' .content>*');
},
error: function() {
console.log("Ajax NOT functioning properly...");
}
});
});
});
Next is the section of the php document (storepage.php) where the javascript file is included, and the POST is directed to.
if (isset($_POST["searchInput"]) && !empty($_POST["searchInput"])) {
echo "searchInput is set... ";
} else {
echo "searchInput is not set... ";
}
echo $_SERVER['REQUEST_METHOD'];
$searchInput = $_POST['searchInput'];
if ($searchInput=="") {
// query all game information based on text in the search bar
$query = "SELECT ProductID,ImgID,Image,GameName,ESRB_ID,ESRB_Img,Rating,ReleaseDate,Description,Tags,Price,PlatformID,PlatformName
FROM PRODUCTS
JOIN PRODUCT_IMAGES USING (ImgID)
JOIN GAME_INFO USING (GameID)
JOIN PLATFORMS USING (PlatformID)
JOIN ESRB USING (ESRB_ID)";
$statement = $db->prepare($query);
$statement->execute();
$GameList = $statement->fetchAll();
$statement->closeCursor();
echo "<script>console.log( 'Game database queried WITHOUT search' );</script>";
}
else {
// query all game information if search is empty
$query = "SELECT ProductID,ImgID,Image,GameName,ESRB_ID,ESRB_Img,Rating,ReleaseDate,Description,Tags,Price,PlatformID,PlatformName
FROM PRODUCTS
JOIN PRODUCT_IMAGES USING (ImgID)
JOIN GAME_INFO USING (GameID)
JOIN PLATFORMS USING (PlatformID)
JOIN ESRB USING (ESRB_ID)
WHERE GameName LIKE '%$searchInput%'";
$statement = $db->prepare($query);
$statement->execute();
$GameList = $statement->fetchAll();
$statement->closeCursor();
echo "<script>console.log( 'Game database queried WITH search' );</script>";
}
I have tried everything I could find online, and I have probably looked at all relevant stackoverflow, and other, posts, but I can't figure it out for the life of me.
You're invoking the script twice. First with $.ajax, where you're sending the search parameter.
Then in the success: function, you invoke it again using $('.content').load. This sends a GET request without the search parameter. So it doesn't show the result of the search in .content.
The AJAX request should return whatever you want to show. Then you can do:
success: function(response) {
$(".content").html(response);
}
Another option is to pass the parameter when calling .load. That changes it to a POST request:
$(document).ready(function() {
console.log("Document Ready. Listening for search bar key presses...");
$('.SearchBar').keyup(function() {
console.log("Key pressed.");
var searchBoxValue = document.getElementById('superSearcher').value;
console.log("Current searchbox value: " + searchBoxValue);
$('.content').load(document.URL + ' .content>*', {
searchInput: searchBoxValue
});
});
});

How to call a non-static method from aspx

I've a Method in the code behind of my aspx page, I need to call Two methods from Javascript, the problem that I'm Having is that I was trying to do it with a Json request and a WebMethod, but this method has to be static and the page components and other methods cannot be accessed from this method.
I was trying something Like:
javascript Function
function Func(Value) {
var conf=confirm('Sure? '+valor)
if (conf==true)
{
BlockAction();
}
}
function BlockAction() {
$.ajax({
type: "POST",
url: 'frmVentaTelefonica.aspx/BlockAction',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
})};
Code-behind code:
[WebMethod]
public static void BlockAcction()
{
try
{
frmVentaTelefonica venta = new frmVentaTelefonica();
venta.ConsultarVentaTelefonica();
venta.ImprimirTiquetes();
}
catch (Exception e)
{
throw;
}
}
I want to call those two methods when the confirm is true.
Update:
In need to accesses to two methods like this:
public void ConsultarVentaTelefonica()
{
DatosImpresion = new List<Impresion>();
IServicioVentas servicioVentas;
servicioVentas = SATWebServiceLocator<IServicioVentas>.ObtenerServicio();
string Tiquetes = string.Empty;
foreach (GridDataItem dataItem in gridInfoVentaTelefonica.MasterTableView.Items)
{
if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked)
{
Tiquetes = Tiquetes + (dataItem["Tiquete"]).Text + ",";
}
}
Tiquetes = Tiquetes.TrimEnd(Tiquetes[Tiquetes.Length - 1]);
Tiquetes = " " + Tiquetes + " ";
DataSet dsResultado = servicioVentas.EntregaTelefonica(sessionR8A.Turno.IdTurno, Tiquetes);
if (dsResultado.Tables.Count > 0 && dsResultado.Tables[0].Rows.Count > 0)
Just run it when is true, those methods update in the database and print a ticket(first reading a grid checked items)
If you are trying to update the UI controls, or read their values, then what you are describing is the UpdatePanel control. A page webmethod cannot update any control and refresh the UI (unless through JavaScript). If you want to update the state of the page async, UpdatePanel is what you are looking for.
If you are trying javascript just because you dont want to refresh the page, then go for Update Panel . The answer for your question is 'No' you cant access non-static methods like how you want to do.
The reason it supports only static methods is that page instantiation is not done, if you want to use non static web methods then go for web service(.asmx).

Binding Repeater with entity framework and Jquery/Ajax

I want to bind repeater with entity framework, that call a procedure in database(Speed purposes), i create an ajax web method to be called from jquery code to sent parameters. so it will decide what data to display.
Below is the ajax call that will sent the parameter to showResult web method, i use the ajax code to handle all data within one page, because i have drop down lists to handle user selections(every selection reflect a query in database).
$.ajax({
url: "WebService.asmx/showResult",
type: "post",
data: JSON.stringify({
"dateFrom": $('#txtDateFrom').val(),
"dateTo": $('#txtDateTo').val(),
"ddlType": $("#ddlType").children("option").filter(":selected").val(),
"ddlTer": $("#ddlTer").children("option").filter(":selected").val()
}), // parameters
beforeSend: function () {
$('#loader').html('<img src="Images/loading.gif" />');
},
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#loader').html('');
//To delete the whole tr except the first one.
$("#tblUsers").find("tr:gt(0)").remove();
$('#tblUsers').append(JSON.stringify(result));
},
error: function () {
alert('error');
}
});
also, below is the web method showResult code that will call the proc with parameters:
public string showResult(DateTime dateFrom, DateTime dateTo)
{
string result = " ";
var sp = db.select_alltypes(dateFrom, dateTo).ToList();
foreach (var u in sp)
{
result += "<tr>";
result += "<td>"+u.depno+"</td>";
result += "</tr>";
result += "</table>";
}
return result;
}
I used to return a table and to append it to the table in .aspx page but i stop, because I want to show 3 tables in the page every table data will present an execution of procedure so, I don't know how to handle this, instead of tables i use 3 repeaters.
so i want to a way to change the DataSource of the repeater immediately whenever the user press a button.
Note: If any one have an idea to present three tables instead of using
repeaters, please provide it here.

Ajax driven content using CodeIgniter

I'm making an web that is a single-page website interacting with the server through Ajax in CodeIgniter. The general coding is of the following type:
controller (user.php):
public function get_user_content() {
$id = $this->input->post('id');
$hits = $this->user_model->user_data($id);
$s = '';
foreach ($hits as $hit) {
$s .= $hit->name;
$s .= $hit->age;
}
echo $s;
}
model(user_model.php):
function user_data($id) {
//do sql operation
return $query->result();
}
view:
...
...
Click here for user details
...
...
javascript:
('.user-data').click(get_user_data);
....
....
function get_user_data(response) {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/get_user_content",
data: { id: this.id },
success: function(response) {
$("#somediv").append(response);
$(".someclass").click(another_function);
},
error: function(error) {
alert("Error");
}
});
}
So, looking at the above javascript, there are separate functions for all actions that send some data to the server and the particular html content is updated via Ajax.
I had the following questions (I'm just new to this stuff):
1. Is there any better way of doing ajax in javascript than my implementation.
2. I'm not using the concept of views in CodeIgniter. I just `echo` results through my controller functions that gets embedded in javascript. This is because I want dynamic update in my app. It is a single page and there is no concept of new-page/new-tab. Is there any better way?
I'm not aware of any open-source projects that might make it easier/more optimized.
For making code more simplified, readable & with great coding standard answer will be yes for both to improve your javascript code & way you are getting a response from the Ajax call.
Improve Javascript :
You might have one common js included in you header portion, if not create & include one. This common jar contains only common functions throughout the application. Create one function with the name may be like sendAjaxRequest() in that common.js. This function will have some parameters like divId (refresh div id), url(post url), options(array of options) & function will look like this:
function sendAjaxRequest(strDivId, strRequestUrl, options) {
options = options || {};
var defaultOptions = {url: strRequestUrl, type: 'POST', beforeSend: function(request,options){showLoadingImage(strDivId);}, success: function(html){$('#'+strDivId).html(html); removeLoadingImage(strDivId); }};
options = $.extend({},defaultOptions,options);
$.ajax(options);
}
Call this function from where ever required on application.
like
('.user-data').click( function() { sendAjaxRequest('somediv', url,{data: { id: this.id }}) });
Benefit : This method is very useful in the future when you want to keep google analytics on ajax call also or want to track your ajax calls. It is always good to have common functions.
Resposnse from ajax call: You can load views in Controller->function in case of ajax call also, nothing need to change or configure for this. Use of this way is always good practice to maintain standardness & readablity in the code.
Note : Here in this case you might worry about using a second action on load of your first Ajax call, for this standard way is to write second action on load of view of that particular Ajax call view (Write second click code in that particular view only) like
('.someclass').click( function() { sendAjaxRequest('someOtherDiv', otherUrl,{data: { id: this.id }}) });
In short at the end user divide & conquer rule (Divide an html page into blocks & create the huge page) to create good applications. Its really fantastic way, as I am using this way in my codings overall.
1- There is other ways to do ajax calls , being better or not is based on your needs, This post clears this point
2- your way is good, still you could use some enhancements to your functions to be a complete web-services same as handling errors - in case - and to return the output data as json allowing you to control it from your JavaScript function for a better handling & representation.
3- from what i understood you're getting data for single user each time ,in this case using $query->row() would be make your life easier extracting the data than using $query->result() , but in case you are getting multiple records you could loop it withing your JavaScript function.
here's another approach to your example with little enhancements that might be helpful :
controller (user.php):
public function get_user_content($id) {
$output -> hit = $this -> user_model -> user_data($id);
if (!$output -> hit) {
$output -> msg = "NORECORDS";
} else {
$output -> msg = "SUCCESS";
}
echo json_encode($output);
}
model(user_model.php):
function user_data($id) {
//do sql operation
return $query -> row();
}
JavaScript :
function get_user_data(response) {
$.get("<?php echo base_url();?>index.php/user/get_user_content/" + this.id, function(data) {
if (data.msg != 'SUCCESS') {
alert(data.msg);
return;
}
var hit = data.hit;
$("#somediv").append("Name: " + hit.name + "Age: " + hit.age);
$(".someclass").click(another_function);
}, "json");
}
First Answer:
The ajax request seems fine, you can add dataType option also to expect particular type of response,
As you are using post you can use jquery.post as an alternative
Example
$.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
You can also use done callback instead of success
Second answer:
Controller
public function get_user_content() {
$id = $this->input->post('id');
$hits = $this->user_model->user_data($id);
$user_array = array();
foreach ($hits as $hit) {
$temp_array = array();
$temp_array = array('name' => $hit->name);
$temp_array = array('age' => $hit->age);
$user_array = array($temp_array);
}
$this->load->view('user', $user_array);
}
Modal
Remains the same
View (user.php)
example say user.php
<?php
echo "<div class='somediv'>";
if (sizeof($user_array)) {
for ($row = 0; $row < sizeof($user_array); $row++ ) {
echo "User Details: Name - " . $user_array[$row]['name'] . ", Age - " . $user_array[$row]['age'];
echo "<br/>";
}
} else {
Click here for user details
}
echo "</div>";
?>
Javascript
$('.user-data').on('click' function () { // better to use event delegation as content is loaded dynamically
get_user_data();
});
function get_user_data() {
$.post( "<?php echo base_url();?>index.php/user/get_user_content", function(data) {
alert( "success" );
$("#somediv").append(data);
$(".someclass").click(another_function);
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
});
}
Reference
stackoverflow.com/questions/18471627/codeigniter-load-a-view-using-post-and-ajax

Categories

Resources