Call a Custom Class Method from jQuery/JavaScript - javascript

I am creating an eCommerce website for school in Visual Studio 15. I am using jQuery and a handler to display the products retrieved from my database. Doing it this way I am unsure how to call methods from my shopping cart class that I wrote within the <script> tag. Each product has this button:
<button type=\"button\" data-itemID=\"" + dt.Rows[i]["itemID"] +
"\" class=\"btnAddItem\">Add To Cart</button>
I'm trying to bind a click event to each button to call my method Add(itemID), I understand I could do it a lot easier just using C# but I already wrote my jQuery and handler.

You could do something like this:
$("button.btnAddItem").on('click', function(){
Add($(this).attr('data-itemID');
});
The jquery selector ( the thing in $() ) matches all buttons with the class "btnAddItem", and then once clicked, fires an anonymous function that calls Add() with the data-itemID attribute form the button that was clicked. This can also be achieved without an anonymous function:
function buttonClickHandler(event){
Add($(this).attr('data-itemID'));
};
$("button.newAddItem").on('click', buttonClickHandler);
Hope this answers your question.

I assume thet method Add(itemId) is written in C#, in Controller named Home.
class Home : Controller {
public ActionResult Add(string itemId) //...
}
Every item in controller is by default mapped to GET and POST http request. So what you can do is call your method from jQuery with GET like so:
$.get( "/Home/Add" , {itemId: "test"} ,function( data ) {
$( ".result" ).html( data );
alert( "Add was performed." );
});
or with POST:
var responce = $.post("/Home/Add",
{
itemId: "test",
},
function () {
console.log(responce);
...
});
And now for connecting to the button event, you can use jquery method in your script:
$("button.addItemButton").on('click', function()
{
var responce = $.post("/Home/Add", ///rest of the code...
});

Related

Jquery ajax post only works once

I have a jquery script that posts a value:
// //Delete a product from the shopping cart
tpj('.remove').on('click', function() {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
console.log('test');
var $remove = tpj(this).attr('id');
url = 'includes/shoppingcart.php';
// Send the data using post
var posting = tpj.post( url, { remove: $remove} );
// Put the results in a div
posting.done(function( data ) {
var content = tpj( data );
tpj( "#result" ).empty().append( content );
});
});
This works the first time, but when I click a second time I redirect to my homepage, which makes sense since the anchor tag the .remove class is in has nothing in its href. However this means the preventdefault() is not working, the entire on click is not working.
Why is that? I googled and found out I should use .on instead of .click but this didn't change anything for me.
The following html line (which fires the jquery):
×
is in my header.php and shoppingcart.php, when the ajax post is made and the result of shoppingcart.php is loaded in my shopping cart, the link stops working like it should.
What do I need to do?
function(EVENT) foggoten in
tpj('.remove').on('click', function() {
//...
}
must be:
tpj('.remove').on('click', function(event) {
//...
}

Send a JSON object to AJAX of jQuery Tabs using WordPress

I am using jQuery Tabs to program a messaging system using WordPress. The point is that when the user clicks one tab, which represents one conversation, an AJAX call is performed automatically with the functionality of jQuery Tabs.
I programmed the jQuery Tab to call an action (that I programmed as well). The action is programmed in PHP using WordPress and I can call it through localhost/mywebpage/wp-admin/admin-ajax.php?action=my_action.
The problem is the following: The default functionality of the jQuery tabs expects the raw output of the PHP file (the ajax action). This means I have to code HTML on the PHP file so I just put the response on the tabs panel (ui.panel.html). However I think this is inefficient and I would like to create a JSON object using WordPres function wp_send_json_success( jsonObject ) which is received on the ui.ajaxSettings.dataFilter function.
When I send HTML to the ui.ajaxSettings.dataFilter function, everything is correctly displayed on the jQuery tabs panel. But when I send a json success, I can see it on the console but I can't display it on the jQuery tabs panel. It appears for a millisecond and then disappears. So the JSON object is being received but for some reason can't be displayed. The only way something is displayed at the jQuery tabs panel is by sending raw HTML by my PHP function. Here is a very simple code example:
This is the JS function:
$( selector ).tabs( {
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataFilter = function( response ) {
console.log( response );
ui.panel.html( response );
}
} );
This is the PHP function that works good:
<?php
echo 'Hello World!';
This is the PHP function that displays on the panel por a millisecond and then disappears.
<?php
wp_send_json_success( 'Hello World! );
In my opinion, I think something else is executing and erasing what I have displayed on the ui.panel.html but I'm not that expert in jQuery tabs so if there is anyone out there with more experience that can tell me what it's going on I would really appreciate it.
I got it working and the fix was obvious but I am still unsure if this is the best way to do it. This is what I did:
var html = $( '<div>' ).addClass( 'wrapper' );
$( selector ).tabs( {
beforeLoad: function( event, ui ) {
ui.ajaxSettings.dataFilter = function( response ) {
// Do whatever you want with the JSON object (obviously validations)
// In my case I want to create HTML elements with info from the response
var response_js_array = JSON.parse( response );
html.append( $( '<div>' ).text( response_js_array['message'] ) );
},
load: function( event, ui ) {
ui.panel.html( html );
// Do also whatever you want after the messages have been loaded. In my case,
// I scroll down to the last message
scrollDown(); // This is also a function I programmed
}
} );

the tooltip in bootstrap doesn't work after ajax

I have a file named index.php, which in I include another file named file1.php (in index.php I include all necessary files for jQuery, js etc.).
In file1.php I have a table with buttons which each opens a modal. the information in the modal is from an ajax call for file2.php. in file2.php I create a table. In the table I have the cell :
<button class='btn btn-default tooltip-default' data-toggle='tooltip' data-trigger='hover' data-placement='top' data-content='content' data-original-title='Twitter Bootstrap Popover'>AAA</button>
and, well, the tooltip doesn't work.
but, when I copy this and get it to file1.php, bellow the table, the tooltip does work.
Can anyone help me fix the tooltip ?
Thx.
Use selector on exist element like body
$('body').tooltip({selector: '[data-toggle="tooltip"]'});
I think you need to initialize the tooltip on the newly arrived data, e.g.
$('[data-toggle="tooltip"]').tooltip();
Place this code to your AJAX success handler, after the DOM manipulation.
You will have to put the tooltip initialization in Ajax callback function:
$.ajax({
method: "POST",
url: "some.php"
}).done(function( msg ) {
$('[data-toggle="tooltip"]').tooltip();
});
-OR-
instead of putting the initialization code in every Ajax callback function
you can implement it globally using the ajaxComplete event:
/* initializate the tooltips after ajax requests, if not already done */
$( document ).ajaxComplete(function( event, request, settings ) {
$('[data-toggle="tooltip"]').not( '[data-original-title]' ).tooltip();
});
This code will initialize the tooltip for every node which has the data-toggle="tooltip" attribute defined but do not have the attribute "data-original-title" (i.e tooltip not initialized).
I've tried everything and nothing worked for me.
So I took a closer look at tooltip when click* and found out that each time the shown.bs.tooltip is fired a aria-describedby property appears and its value changes every time.
So, my approach (and it works) is to change the content of this dynamic element.
I got this code:
$('body').on('shown.bs.tooltip', function(e) {
var $element = $(e.target);
var url = $element.data('url');
if (undefined === url || url.length === 0) {
return true;
}
var $describedByContent = $('#' + $element.attr('aria-describedby')).find('.tooltip-inner');
if ($element.attr('title').length > 1) {
$describedByContent.html($element.attr('title'));
return true;
}
$.ajax({
url: url,
method: 'GET',
beforeSend: function () {
$element.attr('title', 'Cargando... espere por favor.');
$describedByContent.html($element.attr('title'));
}
}).done(function (data) {
$element.attr('title', JSON.stringify(data));
$describedByContent.html($element.attr('title'));
});
return true;
});
In my case my tooltip has a data-url attribute to take the data for the title.
The original title is '-', and I don't want an ajax call every time I click* the element, just the first time.
To me it's not useful to make an ajax every time because I don't expect the data to change that fast.
The dynamic created element has an element with the class .tooltip-inner, so we just need to replace its content.
Hope this might help.
*click: I chose the click event because the default hover sometimes make the system turn crazy and the show.bs.tooltip was fired forever, switching its between the default and new value.
You can do this in one of these two ways:
you can write an ajaxComplete function so that every time after an ajax call completed it reinitialize the tooltip over and over again. This is useful when in most of your pages you have datatables and want to initialize the tooltip after every ajax datatable call:
$(document).ajaxComplete(function() {
$("[data-toggle=tooltip]").tooltip();
});
Or you can call tooltip function after ajax success callback:
function tool_tip() {
$('[data-toggle="tooltip"]').tooltip()
}
tool_tip(); // Call in document ready for elements already present
$.ajax({
success : function(data) {
tool_tip(); // Call function again for AJAX loaded content
}
})
I set up my tool tip by placement like so:
function setUpToolTipHelpers() {
$(".tip-top").tooltip({
placement: 'top'
});
$(".tip-right").tooltip({
placement: 'right'
});
$(".tip-bottom").tooltip({
placement: 'bottom'
});
$(".tip-left").tooltip({
placement: 'left'
});
}
initialize this with a document ready call:
$(document).ready(function () {
setUpToolTipHelpers();
});
This way I can determine the placement of the tool tip, and I only have to assign the tip with using a class and title:
<td class = "tip-top", title = "Some description">name</td>
Then I call, "setUpToolTipHelpers()" inside my success ajax function. Or you can call it on the complete function as well. This seems to work well for me.
run
$('#ding_me_tooltip').tooltip('dispose');
$('#ding_me_tooltip').tooltip();
after the ajax where #ding_me_tooltip is your selector

jQuery - load from another page after all elements are loaded

I want to display the rating of a product, witch is on the product page in div with id rating, on the category page, so I made a script below:
$('.product').each(function(){
var url = $(this).find('a').attr('href');
$(this).prepend('<div class="rating"></div>');
$(this).find('.rating').load(url +'#rating');
});
The problem is, that the rating on the product page is generated with another script, so the element #rating is not present on the site from the start, so after doing some search I tried adding ajaxcomplete function:
$('.product').each(function(){
var url = $(this).find('a').attr('href');
$(this).prepend('<div class="rating"></div>');
$(this).ajaxComplete(function(nxt) {
$(this).find('.rating').load(url +'#rating');
nxt();
});
});
But that also doesn't seem to work, so I'm wondering is there any solution for this to work?
Thanks
You need to load the script that does the rating using jQuery getScript. This way you can put processing dependent on the rating script in the success handler of the getScript call.
The code will look something like this:
$.getScript( "rating.js", function( data, textStatus, jqxhr ) {
console.log( "rating complete" );
$('.product').each(function(){
var url = $(this).find('a').attr('href');
$(this).find('.rating').load(url +'#rating');
}
});

Load javascript file after button click

I am trying to use a set of textboxes to define some data within my JavaScript file. So in a textbox I enter a Team name "Team name", and the javascript file uses this textbox to store the name of a team in order to print a set of tournament brackets.
The javascript file is included in my <head> so it loads before I have actually entered the data in the text boxes. I have this code for a button in the html like so:
script(type='text/javascript')
$('#buttontest').click(function() {
$('div.bracket').show();
$('div.teamList').hide();
});
So when the button is pressed, the textboxes are all hidden, and the brackets with the user-defined team names should appear....here is the code at the end of my javascript file:
$(function() {
$('#singleElim8').bracket({
init: singleElim8Data
})
$('.bracket').hide();
});
So within div.bracket I have the class #singleElim8 which the javascript uses. But how would I change it so that this javascript to initialize the brackets only runs once the button has been clicked? That way the brackets render AFTER the textboxes have been filled in. Any help appreciated.
Just use the getScript method of jQuery
It's very easy to use
$( '#buttontest' ).on( 'click', function() {
$.getScript( 'url to your js file', function( data, textStatus, jqxhr ) {
// do some stuff after script is loaded
} );
} );
When you pass a function as the parameter to jQuery it will execute that function during document.ready(). It allows your page to load all of the scripts before executing them.
$(function() {
$('#buttontest').click(function() {
$('div.bracket').show();
$('div.teamList').hide();
});
$('#singleElim8').bracket({
init: singleElim8Data
})
$('.bracket').hide();
});

Categories

Resources