JavaScript libraries are not working inside Ajax - javascript

#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
function notyfy() {
$.notify({
message: "Hello"
}, {
type: 'danger'
});
}
notyfy();//THis works
$("#btnSave").click(function (e) {
savedata();
});
function savedata() {
var items = new Array();
$("#tblGRN TBODY TR").each(function () {
var row = $(this);
var item = {
'PoNo': $("#PoNo").val(),
'FundSource': $("#FundSource").val(),
'Vote': $("#Vote").val(),
'Total': row.find("TD").eq(5).html(),
'InvoiceNo': $("#InvoiceNo").val(),
'ReceivedDate': $("#ReceivedDate").val(),
'Note': $("#Note").val()
}
items.push(item);
});
$.ajax({
type: "POST",
url: "/GRN/Create",
data: JSON.stringify(items),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
notyfy(); //This do not work
alert(r.responseText);
console.log(r);
$("#tbody").empty();
window.location = "/GRN/Create";
}
});
}
</script>
$.notify is not a function
$.notify works outside without any issue. anything I put inside the success function giving me not a function. all libraries are working fine outside the ajax.
The whole script part is above. please help me to solve the issue in this.

Related

Ajax POST don't work after button click

My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.

stopping a function after first click, to prevent more executions

I have this function
function display() {
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
and it serves its purpose, the only problem is, a user can click on for as many times as possible, and it will send just as many requests to new.php.
What I want is to restrict this to just 1 click and maybe till the next page refresh or cache clear.
Simple example would be :
<script>
var exec=true;
function display() {
if(exec){
alert("test");
exec=false;
}
}
</script>
<button onclick="javascript:display();">Click</button>
In your case it would be :
var exec=true;
function display() {
if(exec){
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
exec=false;
}
});
}
}
This should do what you want:
Set a global var, that stores if the function already was called/executed.
onceClicked=false;
function display() {
if(!onceClicked) {
onceClicked=true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function(data) {
$('.daily').html(data);
}
});
}
}
During onclick, set a boolean flag to true to indicate that user clicked the link before invoking the display() function. Inside the display() function, check the boolean flag and continue only if it is true. Reset the flag to false after the AJAX completed processing (successful or failed).
You can use Lock variable like below.
var lock = false;
function display() {
if (lock == true) {
return;
}
lock = true;
$.ajax({
url: "new.php",
type: "POST",
data: {
textval: $("#hil").val(),
},
success: function (data) {
$('.daily').html(data);
lock = false;
}
});
}
you can implement this with that way too
$(function() {
$('#link').one('click', function() {
alert('your execution one occured');
$(this).removeAttr('onclick');
$(this).removeAttr('href');
});
});
function display(){
alert('your execution two occured');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="display();" id='link'>Have you only one chance</a>

How to Hide multiple div on Ajax Success

I am trying to hide 2 div on Ajax Success by following code
$(".editButton").click(function () {
var self = this;
var membershipid = $(this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembershipDetail","User")',
data: { "MembershipID": membershipid },
success: function (data) {
$('#ddlStoreUpdate').val(data["fk_Store_ID"]);
$('#TxtTitleUpdate').val(data["MembershipTitle"]);
$('#TxtDescriptionUpdate').val(data["MembershipDescription"]);
$('#TxtTimeFrameUpdate').val(data["MembershipTimeFrame"]);
$('#TxtMembershipMinUpdate').val(data["MembershipMinVisit"]);
$('#chkUpdate').prop('checked', data["MembershipGroundLevel"]);
$('#HiddenMembershipID').val(membershipid);
if (data["MembershipGroundLevel"] == true)
{
alert("True");
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
}
else
{
alert("false");
$("#RowTimeFrame").show("slow");
$("#RowMinFrame").show("slow");
var storeid = $("#ddlStore").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetTimeFrame","User")',
data: { 'StoreID': storeid },
success: function (data) {
$("#TxtTimeFrame").val(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
},
error: function (data) {
alert(JSON.stringify(data));
}
})
$("#myModalUpdate").modal('show');
});
If condition is working well, but Div(s) doesn't hide
If I remove $(self).closest() from second div, first div hides all well, Issue is with multiple div
You can use class to hide it, like this:
$(".resetValueTo0").val(0);
$(".divToHide").hide();
Therefor, you don't need to do this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
You might want to try this:
Replace this code:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
To this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").each(function(){
$(this).hide();
});
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").each(function(){
$(this).hide();
});

Autocomplete textbox in asp.net mvc4 using ajax and jQuery

I am trying to fetch company name in textbox as autocomplete. When I run my project, Ajax will call the success function, and the record is also fetched correctly, but there are no autocomplete suggestions in the textbox.
My view is:
$("#idcompanyname").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Companymap", "admin")',
data: "{'term':'" + document.getElementById('idcompanyname').value + "'}",
dataType: "json",
success: function (data) {
alert(data)
response($.map(data, function (v, i) {
var text = v.vcCompanyName;
alet(text)
if (text && (!request.term || matcher.test(text))) {
return {
label: v.vcCompanyName,
value: v.kCompanyId
};
}
}));
},
error: function(result) {
alert("No Match");
}
});
}
});
}
Here is Method on controller:
var query = db.tbaccounts.Where(t => t.vcCompanyName.ToLower()
.StartsWith(term)).ToList();
List<string> lst = new List<string>();
foreach (var item in query)
{
lst.Add(item.vcCompanyName);
}
return Json(lst, JsonRequestBehavior.AllowGet);
Here is the referred Javascript:
<script src="~/script/jquery-2.0.3.js"></script>
<script src="~/script/jquery-ui.js"></script>
<script src="~/js/jquery-1.10.2.js"></script>
<script src="~/js/jquery-ui.js"></script>
Please try removing
~/script/jquery-2.0.3.js
from the script references in your application, and that should work for you....

AJAX reloads the page without inserting into database

I am new to Ajax and confused. The problem is the ajax reloads the page. The function mentioned in the url inserts the data into database. but the page reloads. I guess the URL is not working but i am not sure on this.
Here is my Controller Function
public function insert_student_fee_payment()
{
$std_code=$this->input->post('std_code');
$total_fee=$this->input->post('total_fee');
$payable_fee=$this->input->post('payable_fee');
$date=date('Y m d');
$class_detail=$this->db->select('class.class_year,class.class_semester')
->join('class','class_student.class_id=class.class_id','LEFT')
->where('class_student.student_id',$std_code)
->where('class_student.class_student_status',2)
->limit(1)
->get('class_student')
->result();
if(count($class_detail)>0)
{
foreach($class_detail as $cd)
{
$year=$cd->class_year;
$semester=$cd->class_semester;
}
}
$data=array(
'std_code'=>$std_code,
'year'=>$year,
'semester'=>$semester,
'total_fee'=>$total_fee,
'payable_fee'=>$payable_fee,
'date'=>$date,
'status'=>2
);
if($this->db->insert('student_fees',$data))
{
echo '1';
}
}
and here is my Ajax code in form
<script type="text/javascript">
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '<?php echo base_url()."index.php/finance/insert_student_fee_payment;?>',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
});
});
any help guys
We don't see the HTML so it's hard to say what's wrong but my guess is that $('#insert_fee_payment') is a submit button so you have to cancel the action by default which is submitting the form.
$('#insert_fee_payment').click(function(e){
e.preventDefault();
};
or
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
});
return false;
});
Add return false after the error function.
$(document).ready(function(){
$('#insert_fee_payment').click(function(){
var std_code=$('#std_code').text();
var total_fee=$('#total_fee').text().split(' ');
var payable_fee=$('#payable_fee').text().split(' ');
total_fee=total_fee[0];
payable_fee=payable_fee[0];
var data='std_code='+std_code+'&total_fee='+total_fee+'&payable_fee='+payable_fee;
$.ajax({
url: '/index.php/finance/insert_student_fee_payment',
type: 'POST',
data: data,
success: function(response)
{
alert(response);
},
error: function(response,status,err)
{
alert(err.message);
}
return false;
});
});
});

Categories

Resources