jQuery on 'keyup' no longer working after AJAX request - ajax

I have a shopping cart application that will change the cart prices on the page 'on-the-fly' using an AJAX request using the following updateCart() function - it calls the render_cart() function to display each item in the basket using an 'keyup' event.
For some reason it all works fine on the initial keyup press - but if I attempt to do this again it doesnt' work, even though I can see the .cart-qty class on the input field, can anyone suggest why this is happening?
// on keyup event call the update cart function
$(".cart-qty").on('keyup',function( e ) {
var qty = $(this).val(); // e.g '2'
var rowid = $(this).data("rowid"); // e.g 740fdjhirtj3swnjf463
$( ".basket-item" ).remove();
updateCart( qty, rowid );
} );
function updateCart( qty, rowid ){
$.ajax({
type: "POST",
url: "/cart/ajax_add_item",
data: { rowid: rowid, qty: qty },
dataType: 'json',
success: function(data){
render_cart(data);
}
});
}
function render_cart(json) {
total = json.total;
cart = json.contents;
var html = '';
if (cart) {
$.each(cart, function (i, item) {
html += '<div class="basket-item"><div class="col-sm-6 col-no-pad"><p><img class="img-responsive" src="'+ item.custom.image +'" alt="'+ item.name +'" /></p><div class="remove-item"><p><a class="btn btn-sm btn-yellow" href="#">Remove</a></p></div></div><div class="col-sm-6 col-no-pad"><p class="model"><span class="heading">Model:</span><br />'+ item.name +'<br />'+ item.options.attributes +'</p><p class="buyer"><span class="heading">Buyer:</span>'+ item.options.merchant +'</p><p class="price"><span class="heading">Price:</span>$'+ item.subtotal.toFixed(2) +'</p><p class="condition"><span class="heading">Condition:</span>'+ item.options.condition +'</p><p class="quantity"><span class="heading">Quantity:</span><input type="text" class="form-control cart-qty" value="'+ item.qty +'" data-rowid="'+ item.rowid +'" /></p></div></div>';
})
}
$('#basket_start').after( html );
$('#total-value').text( total );
}

You need to use event delegation .on() for dynamically added elements like this
$(document).on('keyup','.cart-qty',function( e ) {
Bind it to document or the closest static parent

$('.cart-qty').on('keyup', (function(event) {
//do code
}));

Related

Send Table cell value to Servlet Through ajax

I need to post values from a table cell to a servet through Ajax but the response is returning a null. My Javascript is not that strong and I am certainly doing something wrong and need some direction. Below are my JSP and Ajax script:
**My JSP code**
<td><button type="button" class="btn btn-default btn-md" class="itemData" tableData="${item}" onclick="saveData()"><span class="glyphicon glyphicon-save"></span></button> </td>
**My Ajax code**
function saveData(){
$(document).ready(function(){
var dataID = $(this).attr('tableData');
$.ajax({
url : 'DataCtrlServlet',
type: 'Post',
data : dataID,
success : function(responseText) {
$('#submissionSuccessContainer').text(responseText);
}
});
return false;
});
}
Romve return false; and $(document).ready ,also you need to change the data format to pass the parameter correctly
function saveData(){
var dataID = $(this).attr('tableData');
$.ajax({
url : 'DataCtrlServlet',
type: 'Post',
data : {
dataID:dataID
},
success : function(responseText) {
$('#submissionSuccessContainer').text(responseText);
}
});
}

Laravel getting value of checkbox in ajax Error :Cannot read property 'checked' of null

I am showing the checkbox value checked or unchecked based on the db value.but when user try to change it like unchecked it and update the value. i call the ajax i getting this error.
Thanx for help
Code
<div class="{{count($employees) !=0 ? 'sidebar-hide': 'sidebar-customize'}}">
<a>
{{ Form::checkbox('Employee','1',$user->employee) }}
<i class="fa fa-id-card"></i>
<span>Employee</span>
</a>
</div>
Below is the Ajax Function
$(document).ready(function(){
$('#customize').click(function(e){
e.preventDefault();
var customers=document.getElementById('customers').checked ? '1' :'0' ;
var accounts=document.getElementById('accounts').checked ? '1' :'0';
var Inventory=document.getElementById('InventoryItems').checked ? '1' :'0';
var Employee=document.getElementsByName('Employee').checked ? '1' :'0';
console.log(Employee);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url :"{{ url('user')}}",
type :'POST',
data :{
customer : customers,
accounts : accounts,
inventory: Inventory,
employee : Employee
},
dataType: 'JSON'
// ,
// success: function( data ) {
// $("#ajaxResponse").append(data.msg);
// console.log(data);
//}
});
});
});
Is the HTML created dynamically?
If so, then you need to bind the event to a parent element and use the jQuery.on() method instead of click()
$('#parentelement').on('click', 'div.sidebar-customize', function(e) {
//code
});
The second parameter of the method needs to target the element you're trying to use. From you HTML, I can't tell what that will end up being. Maybe implement an additional class or ID so the HTML can be targeted better.
its like i have to include the Id from the checkbox
{{ Form::checkbox('Employee', 'Employee', $user->employee, ['id' => 'employee']) }}
Ajax Code :
$(document).ready(function(){
$('#customize').click(function(e){
e.preventDefault();
var employee=document.getElementById('employee').checked ? '1' :'0' ;
console.log(employee);
});
});
Works prefectly fine as aspected

Rendering a partial view with ajax

Currently I have a main view called getRolesByYear.cshtml. In this view I have three buttons, each for an year. When I click a button(or on page load) I invoke a method, which takes an int 'year' for a parameter and calls an ajax with the year parameter. This ajax calls an action method (getRolesByYear, the one for the main view). The Action method makes a query to a database, a result of which is a list of ViewModel objects. In the return statement I return a PartialView like this : return PartialView("_yearlyRoles",list);. Sadly, after all this, instead of getting a list of the desired objects in my frontend, all i get is an error from the error part of the ajax call. I am generally a novice and I am very stuck with this.
Here is the main view getRolesByYear.cshtml:
#{
ViewBag.Title = "getRolesByYear";
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
getRolesForYear(parseInt(#DateTime.Now.Year));
$(function () {
$('#years a').click(function () {
var year = $(this).text();
console.log(year);
getRolesForYear(parseInt(year));
});
})
//console.log(year);
function getRolesForYear(year) {
console.log(year);
$.ajax({
type: "POST",
url: '#Url.Action("getRolesByYear", "WorkRoles")',
dataType: "json",
data: {
year: year
},
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
$("#partial").html(data);
}
function errorFunc() {
alert('error');
}
}
</script>
<div id = "years" class="btn-group btn-group-justified timeline">
#DateTime.Now.Year
#DateTime.Now.AddYears(-1).Year
#DateTime.Now.AddYears(-2).Year
</div>
<div id = "partial"></div>
The partial view :
#model IEnumerable<eksp.Models.RoleViewModel>
#foreach (var item in Model)
{
<div class="jumbotron">
<h2>item.Role.RoleName</h2>
<h1> item.Role.RoleDescription</h1>
<p class="lead">Focus start : item.Role.FocusStart</p>
<p>Focus end : item.Role.FocusStart </p>
</div>
}
The Action Method :
[HttpPost]
public ActionResult getRolesByYear(int year)
{
string currentUserId = User.Identity.GetUserId();
var list = db.WorkRoles.
Join(db.WorkRolesUsersDetails,
o => o.WorkRoleId, od => od.WorkRoleId,
(o, od) => new
{
WorkRoleId = o.WorkRoleId,
RoleName = o.RoleName,
RoleDescription = o.RoleDescription,
CompanyId = o.CompanyId,
WRUDId = od.WRUDId,
UserDetailsId = od.UserDetailsId,
FocusStart = od.FocusStart,
FocusEnd = od.FocusEnd
}).ToList()
.Select(item => new RoleViewModel(
item.WorkRoleId,
item.RoleName,
item.RoleDescription,
item.CompanyId,
item.WRUDId,
item.UserDetailsId,
item.FocusStart,
item.FocusEnd)).ToList();
//RoleViewModel rv = list;
if (Request.IsAjaxRequest())
{
return PartialView("_yearlyRoles", list);
}
else
{
return View(list);
}
}
Given the reported error message, you need to alter your ajax call. By setting "data" parameter to "json" you're telling ajax to expect JSON-formatted data back in the response, but a partial view is HTML, so change your ajax call to reflect this:
$.ajax({
type: "POST",
url: '#Url.Action("getRolesByYear", "WorkRoles")/' + year,
dataType: "html", //set the correct data type for the response
success: successFunc,
error: errorFunc
});
As an aside, you can improve your error handling on the client side quite straightforwardly by changing errorFunc to something like this, using the parameters that are provided to the callback by $.ajax:
function errorFunc(jQXHR, textStatus, errorThrown) {
alert("An error occurred while trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
For less instrusive reporting and/or easier debugging, you could change the alert to console.log. To get more detail you could also log the entire jQXHR object:
console.log(JSON.stringify(jQXHR));

Django Ajax-jQuery

Since I am relatively new to Ajax and jQuery, and having hard time doing this, I am posting this over here.
Views.py
if request.is_ajax():
if request.method == "POST":
chatroom_id = request.POST['chatroom_id']
else:
chatroom_id =''
print chatroom_id
When I remove if request.is_ajax() condition , then it shows the error saying Key 'chatroom_id' not found in <QueryDict: {u'reply': [u''], u'csrfmiddlewaretoken': [u'yIJct9O7WfyPnWmDosW9N5TEklRwoIHP']}>
Template.html
{% for key, values in chat_data.items %}
<div class="container-fluid" alt = {{key}}>
<div class="row-fluid">
<div class="span2">
{{values.from}} <br/> {{values.init_query}}
</div>
<div class="span10 well">
{% for k in values.chat %}
<label> Text : {{k.text}} </label>
<label> {{k.date_time}} </label>
{% endfor %}
<form action = "#" method = "POST" id = {{key}} class="chatroom">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value = "Sent" class="btn btn-primary">
</form>
</div>
</div>
</div>
{% endfor %}
Since, there will be many chats and correspondingly reply submit button and its key, I want that when I reply to a specific chat, it carries the key with itself and process the chat accordingly.
How can I achieve this using Django, jQuery and Ajax? Replies to be being sent should give via Ajax using jquery
I have written these jQuery lines of code, but they seem not to work. Where I am going wrog
<script type="text/javascript">
var form = $('#'+'{{key}}');
form.submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/dashboard",
data : form.serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});
I believe that the best free resource on the matter is Mike Hibbert's video on using django with jquery to implement ajax.
For the jQuery, you have a few mistakes, the post should look like this:
var form = $('#'+'{{key}}');
form.submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/dashboard",
data : form.serialize(),
success: function( response ) {
console.log( response );
}
});
return false;
});
Try that and tell me how it goes.
When you make an Ajax request with jQuery and Django with csrf you need to pass the token, this uses the jQuery cookie plugin from Django's docs https://raw.github.com/carhartl/jquery-cookie/v1.3.1/jquery.cookie.js :
/** Django's csrftoken ajax security & server failures */
App.ajax = (function () {
var csrftoken = $.cookie('csrftoken'),
host = document.location.host,
protocol = document.location.protocol,
sr_origin = '//' + host,
origin = protocol + sr_origin;
return {
'csrfSafeMethod': function (method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
},
'sameOrigin': function (url) {
return (url === origin || url.slice(0, origin.length + 1) === origin + '/') || (url === sr_origin || url.slice(0, sr_origin.length + 1) === sr_origin + '/') || !(/^(\/\/|http:|https:).*/.test(url));
},
'$setup': function () {
var scope = this;
// TODO: create server failure pages and alert mechanism
$.ajaxSetup({
statusCode: {
401: function () {
},
403: function () {
}
},
beforeSend: function (xhr, settings) {
if (!(scope.csrfSafeMethod(settings.type) && scope.sameOrigin(settings.url))) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
return this;
}
}());
$(document).ready(function(){
App.ajax.$setup()
var $form = $('form');
$form.on('submit' function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/dashboard',
data: $form.serialize(),
success: function (response) {
window.alert(response);
}
});
});
});
Personally I would prefer to pass JSON, also what browser are you testing in? Look into these libraries:
https://raw.github.com/marioizquierdo/jquery.serializeJSON/1.0.0/jquery.serializeJSON.js
https://raw.github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/master/jQuery.XDomainRequest.js

knockout sammy.js navigation issue

I have a scenario like this.
Initially loaded when page is navigated to #Action.
Once the select action is performed data-bind="with tag is loaded"
User click on "Do Something" action is performed. Which replaces the whole "parentNode"
Now When the user clicks back, and the sammy.js notices the hash tag #Action/:id, I need to load the #Action to get back the main View and then select the id to load the data-bind="with" tag again.
How can I do this?
Currently the page does go back to "Action/:id" but since main view is not loaded it doesn't do anything. I have used "this.redirect("#Action") then selected the node, but the doesn't work.
<div id="parentNode">
<ul data-bind="foreach: items">
<li data-bind="click: $root.selectItem">
<h2><span data-bind="text: Sometext"></span></h2>
</li>
</ul>
<div data-bind="with: selectedItem">
<a data-bind="click: loadSomething">Do Something</a>
</div>
</div>
In my viewmodel i have this:
viewModel.selectItem= function (item) {
location.hash = "Action/" + item.id();
}
viewModel.loadSomething = function () {
location.hash = "Action/" + viewModel.someSelectedItem().id() +"/SubAction";
}
$.sammy(function () {
this.get('#Action', function () {
$.ajax({
url: '#Url.Action("GetMainView")',
type: "GET",
data: self.someId(),
dataType: "json",
success: function (result) {
$("#parentNode").html(result.message);
}
});
this.get('#Action/:id', function () {
var id = this.params["id"];
var matchItem = ko.utils.arrayFirst(viewModel.MainItems(), function (item) {
return item.id() == id;
});
viewModel.someSelectedItem(matchItem);
});
this.get('#Action/:id/SubAction', function () {
var id = this.params['id'];
$.ajax({
url: '#Url.Action("ViewSomething")',
type: "GET",
data: { id: id },
success: function (result) {
$('#parentNode').html(result.message);
}
});
});
});
Sample Code: https://skydrive.live.com/redir?resid=33048714B5BF3B4B!913
Steps to Reproduce:
Select "SubItems" under any of the items listed (Item 1, Item 2, Item 3)
Select any of the Sub Items that Label (Sub Item 1, Sub Item 2)
Partial View will be shown with "Sub Item {x}" with "Next View" link
Click "Next View" link.
"Next Partial View" will be shown.
Press the back button.
The thing I am trying to do is to load the SubItems and Select "Sub Item 1" view.
List item
I'm not sure this will work, but could you create a separate helper function to load the main view. Then it would be the case of the following:
this.get('#Action', function () {
LoadMainView();
}
this.get('#Action/:id', function () {
if($('#parentNode').length == 0) {
LoadMainView(function() {
var id = this.params["id"];
var matchItem = ko.utils.arrayFirst(viewModel.MainItems(), function (item) {
return item.id() == id;
});
viewModel.someSelectedItem(matchItem);
})
}
}
Your LoadMainView function would then accept a callback and be something like this:
function LoadMainView(callback) {
$.ajax({
url: '#Url.Action("GetMainView")',
type: "GET",
data: self.someId(),
dataType: "json",
success: function (result) {
$("#parentNode").html(result.message);
if(typeof callback == "function") {
callback();
}
}
});
}
I haven't been able to test this in your solution (I get an error opening it), but I believe that's the general structure to do what you are asking.

Resources