Modifying existing JavaScript in Google Tag Manager - google-tag-manager

Can I use Tag Manager to change this line:
function verify(...
$.ajax({...
...
success: function (data, textStatus, jqXHR) {
if (data) {
...
if (data.imagePixelUrl) {
$("#footer").append("<img id='imagePixel' src='" + data.imagePixelUrl + "'/>");
to this:
function verify(...
$.ajax({...
...
success: function (data, textStatus, jqXHR) {
if (data) {
...
if (data.imagePixelUrl) {
$("#footer").append("<img id='imagePixel' src='" + data.imagePixelUrl + "'/>");
dataLayer.push({'event' : 'success'});
?
The new line is the dataLayer.push. Note it's inside a success call of an AJAX command.

Use the global ajax event handlers in jQuery, specifically the success handler. To discern between your different functions you can i.e. check the settings.url (i.e. the url you called to make your ajax request which is presumably different per function). E.g.:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "ajax/urlone.html" ) {
dataLayer.push({'event' : 'verfiy'});
} else if ( settings.url == "ajax/urltwo.html" ) {
dataLayer.push({'event' : 'function two'});
} else {
dataLayer.push({'event' : 'default'});
}
});
Update: I just found a sort-of-solution for the same question asked on Linkedin (I assume asked by the same person), so I might as well add it here. "Sort-of-solution" because it does not answer the question but solves the problem.
As the added pixel is an image and an image has an onload event one can simply attach an function to the onload handler of that image.
<script>
$('#imagePixel').on('load',function() {
alert("I am pixel hear me roar");
});
</script>
This fires as soon as the image is appended. I tested this with simple setup and it seems to work nicely.

Related

jquery accordion effect doesnt work when I use ajax

When I use ajax, I noticed that Jquery effects don't work. The reason is "The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time "
another similar question
Therefore, I changed my code to following but still I don't get the jquery effects.
Where I have done the mistake?
Previous code
$("#sendemp").click(function(e) {
e.preventDefault();
var submit_val = $("#searchbox").val();
//alert('submitval is ' + submit_val);
$.ajax( {
type : "POST",
//dataType :"jason",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_pimary_details',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion21').html(data);
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
});
New code
$("button").on( "click", "#accordion3",function(){
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'employee_deatils_search',
user_name : submit_val
},
success : function(data) {
// alert('hhh');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
$("#accordion3").accordion({ heightStyle: "fill", active: 0 });
// $( "#searchbox" ).autocomplete({
// source: data
// });
}
});
} );
I have following submit button
<input type="submit" id="sendemp" value="Search" />
I don't think your click binding is correct, if you want to handle clicks on button inside #accordion3 change it to:
$("#accordion3").on( "click", "button",function(){...});
It is hard to tell without your html, but it looks like in your old code you are replacing the sendemp button. In your new code your event delegation is incorrectly specified. You are applying delegation to a button element (which doens't exist since your sendemp button is an input element).
Apply delegate to something that is the parent of #sendemp like so:
$('body').on('click', '#sendemp', function() {
// your ajax call
});
I could fix the issue, I tried the above solution that is using on method. However, it doesn't make sense to my problem.
As following artical explain I think, Accordion is already instantiated and effects are persistance. When it is called second time, it won't create again since there is already the effects.
Therefore, I needed to destroy it and recreate accordion.
support link
I changed the code on success as follows
success : function(data) {
// alert('hhh');
$('#accordion3').accordion('destroy');
$('#accordion3').html(data);
$("tr:odd").css("background-color", "#F8F8F8");
//$("#accordion3").accordion( "disable" );
$("#accordion3").accordion({ active: 0 });
}
And out of $(document).ready(function() {
I added
$(function() {
$("#accordion3").accordion({
// heightStyle: "fill",
active: 0 });
});

Have a script (JS) run when I click the month button

I am trying to figure out how to have a script run when I select "month" in a full calendar derivative.
How would I go about this? Click it and EVERYTHING else happens, but a script of my choosing also runs.
regardless of whether you are using the select or dayclick, you should be able to have a function run within that callback and then use $.ajax function to run your php script (assuming you are using php since you did not specify). Here is a short example...
var calendar = $('#calendar').fullCalendar({
select: function(s, e, a) {
myfunction();
}
});
And then outside of the calendar var...
function myfunction(){
$.ajax({
url: 'myscript.php',
data: {myvariable: myvariable},
type: 'post',
success: function(data){
alert(data);
}
});
}
I cant see why this wouldn't work
Here you go:
$(document).ready(function() {
// ... you can have other things here ...
$('.fc-button-month > .fc-button-inner').live('click', function() {
alert('I am here ..');
});
});

How to call a serverside method using jquery?

I'm trying to call a server side method, using jquery, on the textchange event of a textbox which is generated dynamically on the clientside (I dont know how to fetch the id of this). Can somebody help me to do this stuff? The script im using is as follows:
<script type="text/javascript">
$(init);
function init() {
$('#test').droppable( //Div Control where i'll be dropping items
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
function handleDropEvent(event, ui) {
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
$('.textChangeClass').live('change', function() {
/* Evokes on the text change event for the entire textboxes of class .textChangeClass. Is it possible to specify the dynamic textbox generated # clientside here? (like for e.g. : $('#mytextbox').click(function () ) */
$.ajax({
type: "POST",
url: "Webtop.aspx/ServerSideMethod", //This is not getting called at all.
data: "{'param1': AssignedToID}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
alert("From Server");
}
})
});
});
function addColumn(column) {
var iHtml;
//This is how i'm generating the textboxes along with a checkbox bound by a div.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="textChangeClass" type="text" id="aln' + column + '"> </div>';
return iHtml
}
</script>
I think you have an extra "});" although this probably isn't the problem.
What is "AssignedToID"? Try adding single quotes around that. I seem to remember having a weird problem a couple years ago related to quoting in the json.
Can you see the request in Fiddler/firebug/etc? Is the content correct?
You should be careful of your use of inferred semi-colons too. If you ever minify your javascript (yeah, I know this is embedded, but I'd like to hope that one day it will be moved to a seperate js file) you're eventually going to have a problem. Imagine some other developer comes along, does some refactoring and needs to add a return value after the ajax call.
$.ajax({...})return foo}
EDIT
Fiddler/Firebug Net panel are your friends... They will allow you to inspect the request and the response from the server. This way you don't have to add the error handler (although you may want to for other reasons eventually)
EDIT
To answer the other part of your question, you can access the textbox for which the change event was triggered through the use of the 'this' keyword inside of the event handler.
$('.textChangeClass').live('change', function(event) {
//Note that the 'event' parameter has interesting things in it too.
var changedText = $(this).val();
alert("The value in the textbox is: '" + changedText + "'");
var data = {
param1: changedText
};
$.ajax({
...
//Using json2 library here to create json string
data: JSON.stringify(data),
...
});
});
Note that I added the optional 'event' parameter to the event handler. It has interesting things in it and it's something that is often overlooked by people who are new to jQuery. Read about it here.
You need to write you code of adding the event to textbox after generation of textbox otherwise it's not get fire.
add text box
After that write code to add event to text box or bind event to text box
just follow the above step will do your work
EDIT
Add the error function to your ajax call you will get the error ... will allow you to proceed further
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//...
},
error: function (request, status, error) {
alert(request.responseText);
}
});

How do I access jQuery AutoComplete extraParams with ASP.NET

I'm using the following jQuery script to send a 'Make' parameter to filter my 'Models':
$(document).ready(function () { $(".autocomplete_make").autocomplete("/AutoComplete/Make.ashx"); });
$(document).ready
(function () {
$(".autocomplete_model").autocomplete("/AutoComplete/Model.ashx"
, extraParams: {
make: function() {return $(".autocomplete_make").val(); }
}
);
});
The text entered is passed to the .ashx file as a 'q' querystring, however, I'm not sure how I access my extraParam 'Make' so I can pass this to my stored procedure in the Generic Handler file. How do I do this?
Thanks,
Curt
It should be as simple as:
context.Request("make")
Which I believe you know already.
The only other problem I see is that your javascript looks a little flawed because you are not passing in an object as the second parameter (the options).
Here is the corrected code (I hope):
$(document).ready(function () {
$(".autocomplete_model").autocomplete("/AutoComplete/Model.ashx", {
extraParams: {
make: function() {
return $(".autocomplete_make").val();
}
}
});
});

jQuery Function Question

I have a question concerning functions with jQuery. I have a function that once the browser is ready the function finds a specific table and then adds hover & click functionality to it.
I am trying to call this function from code behind in an asp .net page due to the fact that once someone adds to the database the update panel fires and retrieves a gridview (the table that has been affected by the function at document.ready). When it comes back it is the plain table again.
Here is the original functions:
$("#GridView1").find("tr").click(function(e) {
var row = jQuery(this)
//var bID = row.children("td:eq(0)").text();
$('#tbHiddenBatchID').val(row.children("td:eq(0)").text());
//Took out repetitive code, places values from table into modal
e.preventDefault();
$('#modalContentTest').modal({ position: ["25%", "5%"] });
//row.addClass('highlight');
//$('#tbEdit').val(bID);
});
//here is the function that adds hover styling
$("#GridView1").find("tr").click(function() {
return $('td', this).length && !$('table', this).length
}).css({ background: "ffffff" }).hover(
function() { $(this).css({ background: "#C1DAD7" }); },
function() {
$(this).css({ background: "#ffffff" });
});
OK, what I tried to do is create a function, call it on document.ready and also in the code behind when after the database has been updated.
Here's what I did:
function helpGrid() {
$("#GridView1").find("tr").click(function(e) {
var row = jQuery(this)
//var bID = row.children("td:eq(0)").text();
$('#tbHiddenBatchID').val(row.children("td:eq(0)").text());
//
e.preventDefault();
$('#modalContentTest').modal({ position: ["25%", "5%"] });
//row.addClass('highlight');
//$('#tbEdit').val(bID);
});
//Haven't even tried to add the hover stlying part yet; can't get this to work.
}
When I try to call helpGrid(); I get an error that's it not defined...
Obviously I'm a jQuery newb but I do have jQuery in Action & I'm scouring it now looking for an answer...
Please help..
Thanks!!!
Since you are using an update panel, the entire page does not postback and the document.ready stuff never gets hit... Below is where you can add a function to run at the end of the update, so resetMyTableStuff(); is where you'll want to do your magic...
Try adding something like this...
function pageLoad() {
if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequest);
}
}
function endRequestHandler(sender, args) {
resetMyTableStuff();
}
function initializeRequest(sender, args) {
//just in case you need to do it...
}

Resources