Finding the element after an ajax event - javascript

I'm working on a site that allows users to love an item (like an item). The event is handled with jQuery and AJAX. The item array holds quite a lot of items and each item has a button to 'love'. I decided to efficiently reduce the number of forms on the page by putting one form at the bottom of the page and just submit it remotely.
So every time a user clicks the love button, the data attribute that holds the item id is put into the form and the form is submitted. Simple stuff.
But I'm finding the data response a bit more complex because I don't know how to find the element id of the item I want to update. I can't just use this or event.target because its inside a different event. I've also tried to carry the event parameter into the submit event, but it didn't work.
$(".love_item").click (event) ->
$(".love_item_item_id").val $(this).data 'id'
$(".love_item_form").submit()
$(this).hide(200)
$("form.love_item_form").submit (evt) ->
evt.preventDefault()
$form = $ #
$form.find(':submit').prop 'disabled', true
$.post($form.attr('action'), $form.serializeArray(), type: 'json').done (data) ->
$(event.target).parent().find(".item_info_box").html data
The last line, where it says event.target is as far as I've got. Its obvious that this variable is not carried, but I don't really know what to place there to achieve my goal. Also, I know that I could pass additional parameters through the form action (in other words send them to the rails controller and back), but I'd rather not. Any ideas?

You don't need an abitrary form at all. Something like this would work:
Example Markup (notice the data attribute):
Item to like
jQuery:
$('a.likeable').on('click', function() {
var $item = $(this);
var id = $item.data('id');
$.post('url/like/' + id, function() {
// success
// do something with $item here.
});
});

If you have an element like this: <div id="foo" data-id="foo1234">Foo</div>
You can select it after your ajax post like this, assuming you still have the ID of foo1234:
$('[data-id="' + id + '"]').doSomething();

Just use jQuery's ajax functionality
$('.love_item').on('click', function(e) {
$.ajax({
type: 'POST',
url: *insert url here*,
data: 'id=' + e.currentTarget.data-id,
success: function(response) {
var element = e.currentTarget;
// do whatever
}
})
});

Related

Struggling to call a Jscript function within jquery

I have a small MVC5/C# Web application. In short, users will select a location from a dropdown ("#UnitList"). This fires the jquery event, to populate the next dropdown ("#CheckItem") with a list of contacts associated to the location selected.
Being very inexperienced in Jscript and Jquery, I am lost.
Additionally, on the same event, I need to populate an element (hidden text box).
In order to fill the hidden elements, I use this code
$(function () {
$("[name='UnitList']").change(function () {
$("#DeliveryUnitID").val($(this).val());
});
});
To run the Jquery that populates the second dropdown:
$(document).ready(function() {
$("#UnitList").change(function() {
var batchId = $(this).val();
var urlForModesl = getURLBase() + "ICS_Requisitions/Details";
urlForModesl = urlForModesl + "/" + batchId;
var modelsHtml = "";
$('#CheckItem')
.find('option')
.remove()
.end()
.append('<option value="Select Contact"></option>')
.val('Contact')
$.ajax({
type: 'get',
url: urlForModesl,
contentType: 'application/json',
dataType: 'json',
success: function(jsonData) {
$.each(jsonData, function(key, value) {
modelsHtml += "<option value='" + value.LoginID + "'>" + value.ContactName + "</option>";
});
$("#CheckItem").html(modelsHtml);
$("#DeliveryUnitID").val($(this).val())
},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
});
});
});
I am aware that I have two functions with the same name "$("#UnitList").change(function ()" and that this is very bad and causing conflicts. This is what I am trying to resolve.
I have tried to simply add the element update within the Jquery code, but that did not work.
I placed the following code
$("#DeliveryUnitID").val($(this).val())
Inside the Jquery, right after:
$("#CheckItem").html(modelsHtml);
But that does not work. The hidden elements are still empty.
I tried creating a function called foo, with the element update, and call that function from at the end of the jquery.
foo();
<script>
function foo() {
$("#DeliveryUnitID").val($(this).val());
}
That also left the element #DeliveryUnitID empty.
I know that I can't have two functions with the same name, but that's the only way I can get it working where the query populates the drop down, and then the hidden element is populated too. BUT . . . that's bad coding AND, for about 5% of the users, it fails.
I can't quite figure out how to make both happen with one onchange event.
It's been a while since I've used jQuery, so here's what I'm seeing:
On change Event:
Get the value of the #UnitList <select> (potential bug: these aren't being stored anywhere)
Clear the options
Re-populate with new ones from AJAX Request
Try to get value of new options (still within initial AJAX request, which might also be a bug? Like I said, it's been a while since I've used jQuery).
It looks like you might have a state-management issue?
Potential fixes:
Store values of first dropdown before you clear them.
Use the stored value to populate #DeliveryUnitID after the AJAX request
Use some if statements or remove the event listener to not constantly be running your code on change event once you get the data you need...unless you need it to be running constantly.
To me, it would seem beneficial (from a code pov and maybe also a UX perspective) to programmatically build a second dropdown to keep things clearer, but that might be overkill for what you're trying to accomplish.

submitting a form via ajax upon stop event of jquery

UPDATE
Added this error, just says "Error caught"
<script type="text/javascript">
window.onerror = function() {
alert("Error caught");
};
xxx();
</script>
This is not working, I don't understand why.
My php script inserts data properly if called by itself without an if{method=post} statement
I tried with and without an if method = post argument on the php side to get the ajax below to work but I can't tell if the script is being called at all.
My aim is to submit the data without the user knowing, it's a coordinate / dimension update for a variable design interface.
This is my ajax insert which is supposed to work when a function is invoked after the stop is triggered eg. after an object is done moving which the function is invoked properly as I have set up sequential alerts to pop up after certain lines.
$("#form").submit(function(event){
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, {
id: $('#id').val(),
name: $('#name').val(),
wname: $('#wname').val(),
xcor: $('#xcor').val(xcor),
ycor: $('#ycor').val(ycor),
xwid: $('#xwid').val(xwid),
yhei: $('#yhei').val(yhei),
photo: $('#photo').val(),
targeturl: $('#targeturl').val()
});
posting.done(function( data ){
alert('success');
});
});
This is wrong
xcor: $('#xcor').val(xcor),
ycor: $('#ycor').val(ycor),
xwid: $('#xwid').val(xwid),
yhei: $('#yhei').val(yhei),
Those object are holding jQuery objects, not a value.
Looks like you want to set the value and use the new value. This makes me cringe, but it would do the job
xcor: $('#xcor').val(xcor).val(),
ycor: $('#ycor').val(ycor).val(),
xwid: $('#xwid').val(xwid).val(),
yhei: $('#yhei').val(yhei).val(),
You would be better off updating them before the call and just using the variable when setting the object. Or just use jQuery serialize() and don't deal with grabbing the elements.

Getting all values being sent to the server at once

I have a form, bunch of inputs and submit button. Some of the inputs are added and deleted dynamically. And some of them may be (or may not) disabled but I still need to get their values of the server.
So I have to add a handler to the button and collect the values of the disabled inputs manually and add them up to other, enabled. inputs. But I'd like not to go that way as it seems too complex (since some of the inputs are added / removed dynamically).
I can also add hidden inputs for each inputs which can be disabled but still it's a bit complex.
What I want is similar to 1. But instead of manually enumerating the enabled inputs by jquery selectors, I want to just get all values are being sent to the server at once by some jquery function maybe or by any other way. And then manually (by selectors) add up the values from the disabled inputs to them. Is this possible?
You could use the jQuery .serialize() for that.
The general structure of the function would look something like this
var mydata = $("#myform").serialize();
$.ajax({
type: "POST",
url: "ajaxurl",
data: mydata,
dataType: "json",
success: function(data) {
...
}
});
So I just figured you had a problem of how to get the disabled fields as well. You could use the function suggested in this thread:
Disabled fields not picked up by serializeArray
Just to make the answer complete, I will copy the plugin from there.
The usage is like this:
var data = $('form').serializeAllArray();
And here's the plugin itself:
(function ($) {
$.fn.serializeAllArray = function () {
var obj = {};
$('input',this).each(function () {
obj[this.name] = $(this).val();
});
return $.param(obj);
}
})(jQuery);
You could use a strategy like the following in your submit handler:
Select all disabled elements .. (don't lose the reference to these)
Enable all disabled elements
Serialize the form .. to get all the data
Disable the elements back
Submit your form.

ajax conditional var before posting

I have a like button. It shows on each item of an activity feed. I recently added the ability to like comments as well. Need some help adjusting the ajax to work with this. I currently grab the closest .feeditem and get the id, which is formatted to have the ID of the item.
The comments are showing in the same .feeditem div, so clicking like executes the same code, but does not save the right information. Is there a way to make it first check if one of the parent divs id starts with activity-comment- and if it does, have it select different divs, and if its not within that parent id, select the default (below)?
Or if you have a better way to implement this altogether please suggest. Newer to AJAX so this may not be the most effective way.
$likeButton.click(function (event) {
event.preventDefault();
var $itemClicked = $(this)
**//START SELECT**
var liking_user_id = $itemClicked.closest('.feeditem').attr('data-member').match(/\d+/);
var activity_id = $itemClicked.closest('.feeditem').attr('id').match(/\d+/);
**//END SELECT**
var data = {
'action': 'save_like',
'activity_id': activity_id,
'liking_user_id': liking_user_id
}
$.ajax({
type: 'post',
url: ms_user_actions.ajaxurl,
data: data,
success: function (response) {
if (!response.success) {
}
if (response.data.like == true) {
$itemClicked.siblings('.feedBox_Likes').text('You Like This!');
$itemClicked.html('Unlike').attr("like", "unlike");
}
if (response.data.unlike == true) {
$itemClicked.html('Like').attr("unlike", "like");
}
}
});
});
Having to make some assumptions here as there's no HTML in the question. In particular, I'm assuming that you want liking_user_id and activity_id in both cases, and that these two values are read from the relevant container nodes (divs) in the same way.
If those assumptions are valid, then the easiest approach is probably to devise another class name (eg. 'likeContainer') and apply it to the outer (feeditem) container and each of the inner comment containers. This class name will be additional to any existing class names, eg <div class="feeditem likeContainer">
The jQuery would then be as follows :
var liking_user_id = $itemClicked.closest('.likeContainer').attr('data-member').match(/\d+/);
var activity_id = $itemClicked.closest('.likeContainer').attr('id').match(/\d+/);
Thus,
when a comment's 'like' is clicked, .closest() will find an inner, comment container
when a non-comment's 'like' is clicked, .closest() will find an outer, feeditem container.
If the assumptions are not valid, then you might consider building the outer and inner divs differently. This might be the line of least resistance.

How do I get my jquery post request to work with the variable stored from a function on a click?

I have been banging my head against the wall trying to pass a game's name through to my php function as soon as a user clicks a button. The idea is the user clicks a button, which has a value of its videogame name, then the php script checks that game's ranking and returns that ranking to the html. I have made post requests work before, and even here when I manually set the variable name to one of the Games to test it, it works. Please help!
<script>
$(document).ready(function(){
//global n variable
n = $();
$('#target').click(function(){
//set value of n to the game's name
n = $(this).val();
});
//then send the name as term to my php function to deal with it and return
//the ranking
$.post('getTotal.php', {term: n}, function(data){
//been trying to see if anything comes through for debugging purposes
alert(data);
//commented this out for now, just puts it in the div I left open
//$('#total').html(data);
});
});
</script>
simply when the user clicks the button. inside the click handler, obtain the value and perform an http post
$ajax or $POST
eg -
$(document).ready(function() {
$('#target').click(function()
$.ajax({
type: "POST",
url: "url...",
data: "n="+nVal+",
success: function(html){
alert( "Submitted");
}
});
});
});
You should put the $.post into your click handler... so it will only run when you actually click the button... now your code sets up an n variable, its value is an empty jQuery object (why?). Then it attaches a click handler on the button. Then it runs a $.post request - n is still an empty jQuery object. Clicking the button happens much later...
Also, using globals should be avoided. The var keyword should be used when declaring variables.

Categories