jQuery: passing variables from AJAX generated html into javscript function

Hi
I've been struggling to get this to work and have attempted several solutions none work

Workflow:
User clicks a URL which calls a PHP script, this loads into a div below the link
Within the new content is a button which has attributes these need passing into a new function which again loads new content in this Div  

I tried passing 2 variables within the onclick like here  This caused ReferenceError: MyWord is not defined or SyntaxError: missing ) after argument list if using My Word  

I'm now getting
"id {object HTMLButtonElement) Tag undefined

$(function(){
$('a').click(function(e) {
    e.preventDefault();
    $(this).next('.resp').load( $(this).attr('href') );
});

function myFunction(me){
  var ID = me.getAttribute("id");
  var Tag = me.getAttribute("tag");
  
 $(this).closest(".resp").html ("<p>ID " + ID + "Tag" + Tag + "</p>>");

}

  });

Open in new window


HTML

    <div>
      <a id="1" href="myfile.php?param=My Word&ID=1">My Word</a>
      <div id='resp_1' class='resp'></div>
      <a id="2" href="myfile.php?param=MyWord&ID=2">MyWord</a>
      <div id='resp_2' class='resp'></div>
      
    </div>

Open in new window


HTML generated from first load function

<button id="Butt_1" data-tag="My Word"  onclick="myFunction(this)">My Word</button>
<!-- or second URL -->  
<button id="Butt_2" data-tag="MyWord"  onclick="myFunction(this)">MyWord</button>

Open in new window

LVL 1
trevor1940Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Are you getting errors or is it just not working.

There are a lot of variables in this question.

For instance you have $('a').click - if you are expecting this to bind to <a> elements in the returned html it won't as it is statically bound - you would need to use .on() for that to work.

I am also not clear on the flow. I understand the first bit where the <a> click is being intercepted and loaded into the next <div> but where does the <button> code come in - is that what is being loaded into the <div> - if so what is it that is not working?
0
trevor1940Author Commented:
Are you getting errors or is it just not working.
Yes
"id {object HTMLButtonElement) Tag undefined

I changed $('a').click(function(e)

to
$(document).on("click", "a", function(e)
also tried

$('a').on("click", function(e)

I'm still getting the same error


<a> click is being intercepted and loaded into the next <div>
The Button code is generated by PHP as a result of this click / query

Clicking this button I get the error
0
Julian HansenCommented:
What are you expecting to happen when you click the button?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Julian HansenCommented:
I see the problem - working on a sample now
0
trevor1940Author Commented:
I've also changed

function myFunction(){
  var ID = $(this).attr('id');
  var Tag = $(this).attr("data-tag");
  
 $(this).closest(".resp").html ("<p>ID " + ID + "Tag" + Tag + "</p>>");

}

Open in new window


On clicking the generated button I now get error

"id undefined Tag undefined"
0
trevor1940Author Commented:
On clicking the button I'm expecting the div containing the button to be replaced
0
Julian HansenCommented:
Lots going on here that needs attention

1. me.getAttribute("tag") is not going to work against data-tag="My Word"
Either (JavaScript)
var Tag = me.dataset.tag;

Open in new window

OR (jQuery)
var Tag = $(me).data('tag');

Open in new window


2. Scoping - your myFunction is inside the jQuery document ready which means its scope is going to be limited to that code block - you can't call myFunction outside of the document ready.
Either bind the click event handler to your button using jQuery inside the document ready

$('.resp').on('click', 'button', function() ...

Open in new window


OR
Move myFunction outside of the document ready block

3. $(this).closest(',resp')  also not going to do what you think it does. You are inside a JavaScript function - not an event handler - "this" is going to refer to the window. If you used the on('click'...) suggestion above then "this" would refer to the button clicked but not in this instance.
Either change to using the on('click'...) above
OR
Change your code to
$(me).closest('.resp' ....

Open in new window


Minor issue - there is a double >> in your string adding the <p>

I have put together a sample using the above concepts you can see it working here
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
trevor1940Author Commented:
Julian Thanx

After 2 days It works, I've been trying to work it out myself and  tried multiple things which is probably why i've been confused.
BTW my dev is done on a closed system so I'm surprised there wasn't more typos or errors in the code posted here like location of MyFunction

For future reference can to explain the following

Why use
$('a').on("click", function(e)
and not  
 $('a').click(function(e)

I was under the impression using the jQuery .load() handled binding new content to the dom

According to the jQuery manual you get the data attributes like so

var tag = $(this).data('tag');

Why did this fail and you code work

  var tag = this.dataset.tag

In the PHP I've not seen the use of {} around variables why is this used

<button id="Butt_{$id}" data-tag="{$id}">My Word</button>
0
Julian HansenCommented:
Why use
$('a').on("click", function(e)
and not  
 $('a').click(function(e)
The main difference is static vs dynamic binding. With the $('a').click() jQuery is binding to the <a> elements that are on the page when the jQuery runs. That means if you add new <a> to the document (say with AJAX) they won't be bound to the click handler.

However - in your example above they still will not be as you are binding too low down. You need to bind the .on() to a parent element that is static and then specify the target in the function parameters In other words

$('.resp').on('click','a', function() { ...

Open in new window

Binds to the .resp class - so any clicks on that element will be caught by the event hander - jQuery will then check the origin of the event and see if it matches the selector list (in this case the 'a' after the 'click') - if it does the event handler fires.

In your example the effect of the two bits of code will be the same.

I was under the impression using the jQuery .load() handled binding new content to the dom
Load will load the content into the DOM on the specified element - it does not rebind event handlers. Any content that placed in the page will need to bind its own event handlers with inline script - or the host document will need dynamically bound event handlers as shown above.

According to the jQuery manual you get the data attributes like so

var tag = $(this).data('tag');

Why did this fail and you code work

This did not fail - you tried getAttribute('tag') and attr('data-tag');

the correct way to do it is either with jQuery
var tag = $(this).data('tag');

Open in new window

or JavaScript
var tag = this.dataset.tag;

Open in new window


$(this).attr('data-tag') 

Open in new window

should also work but is not the right way of doing it.

In the PHP I've not seen the use of {} around variables why is this used
The {} are optional but I always use them for reasons I will state later.
The purpose of the brackets is to tell PHP what parts within a string are variables and what is part of the string to output.

Consider this string
$value = 'Something';
echo "The value is $valueX";

Open in new window

Is the 'X' part of the string or part of the variable name - there is no way for the compiler to tell. The { } tells the compiler to take the value of what is inside the { }

So
$value = 'Something';
echo "The value is {$value}X";

Open in new window


I use them as a standard as I find it makes the code easier to read in terms of where variables are placed in strings.
1
trevor1940Author Commented:
Thanx I think I'll need to study this in the morning

One thing that seems to catch me is when too bind elements that don't exist

You need to bind the .on() to a parent element that is static

So what do you do when the only static element is the body or <body> <div class=content> and you have multiple buttons / elements loaded dynamically that need to call different functions depending on there parent or class which is also loaded dynamically?

You can't call this because each button will do the same thing

$('.content').on('click','button', function() { ...

Open in new window


and if I'm understanding correctly  you can't do this either because Myclass dosn't exist when $(function is run

$('.content').on('click','button .Myclass', function() { ...

Open in new window


nor this as ".ButtonParent" dosn't exist when $(function is run

$('.ButtonParent').on('click','button', function() { ...

Open in new window


I'm guessing you'll have to load the content and then call a 'BindIt' function  and put the code within it?


I realise I'm taking this to ex-streams and I'm going off topic now
0
Julian HansenCommented:
So what do you do when the only static element is the body
Same principle as with static binding - just pick a static parent and add the right selector.
You bind to body
$('body').on(...

Open in new window


and if I'm understanding correctly  you can't do this either because Myclass dosn't exist when $(function is run
No, that is not how it works - lets assume you have a button that is bound dynamically in a div that has class XXX also loaded dynamically, you would do this
$('body').on('click', '.XXX button', function() { ...

Open in new window

This does not bind to .XXX it binds to body - when the click comes in it is triggered at the body level in the hierarchy - jQuery then does a check to see if the child element from which the event originated matches the selector (at event time - not bind time) and then proceeds accordingly.
I'm guessing you'll have to load the content and then call a 'BindIt' function  and put the code within it?
Nope - see above
1
trevor1940Author Commented:
Thank you for your help and more so for the explanation
0
Julian HansenCommented:
You are welcome.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.