#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    195
    Rep Power
    45

    Ajax: Populating data string to be sent based on button clicked


    I cringe every time I venture out of the PHP forums to visit the Javascript forum, and I'm sure you do as well. I just don't work with this stuff enough to retain it all, and it feels like I'm learning Javascript all over again each time I try.

    With that in mind, hopefully this will not be too horrific of a n00b question.

    I'm working on an Ajax function that adds a "like" into the mysql database when someone clicks on the like link. I have that aspect of it working just fine, as long as I hard-code the values I want to submit into the dataString.

    But there will be many "like" links on this page, so I need some way to pass information specific to whichever link they click on into the Ajax function.

    So here is my test code:

    javascript Code:
     
    <script type="text/javascript">
    $(document).ready(function(){
    	$('#likeButton').click(function(e){
    		dataString = 'type=' + 'project' + '&id=' + '9';
    		 $.ajax({
    			 type: 'GET',
    			 url: 'sql_like.php',
    			 data: dataString,
    			 success: function(data){
    				$('#output').html(data);
    			 },
    			 error: function(request, status, error){
    				 alert(request.responseText);
    			 }
    		 })
    		})
     })
    </script>
     
    <h2>Result:</h2>
    <a href="#" id='likeButton'>Like</a>
    <div id="output">2</div>


    I need to be able to change the "type" and "id" values depending on which link they click.

    Help?
    Last edited by BlackAce; October 10th, 2012 at 02:01 PM.
  2. #2
  3. No Profile Picture
    Lost in code
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 2004
    Posts
    8,316
    Rep Power
    7170
    Within your click event handler, this represents the HTML element that was clicked.

    You can insert data elements into your HTML to contain data:
    Code:
    <a href="#" id="likeButton" data-type="1" data-id="2">Like</a>
    You can retrieve attribute values using jQuery's attr function:
    Code:
    $(this).attr('data-type');
    PHP FAQ

    Originally Posted by Spad
    Ah USB, the only rectangular connector where you have to make 3 attempts before you get it the right way around
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    195
    Rep Power
    45
    Originally Posted by E-Oreo
    Within your click event handler, this represents the HTML element that was clicked.

    You can insert data elements into your HTML to contain data:
    Code:
    <a href="#" id="likeButton" data-type="1" data-id="2">Like</a>
    You can retrieve attribute values using jQuery's attr function:
    Code:
    $(this).attr('data-type');
    Boy, you are all over around here! Thanks for steering me in the right direction.
    Last edited by BlackAce; October 11th, 2012 at 01:26 PM.
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    195
    Rep Power
    45
    Oreo,

    I ran into a setback today. For some reason, if I have multiple "Like" buttons on a page, only the first one works with the Ajax. I know they are all coded exactly the same, because it's a PHP loop that creates the page with all the buttons. If I change the order of the records, no matter which one is first, that is the only one that works.

    Is there a way I can debug what is happening when I click the other buttons on the page?

    I'm wondering if is has to do with the span I am using to output the response to. That span is given an ID of "output".

    javascript Code:
     
    success: function(data){
    				$('#output').html(data);
    			 },


    EDIT: Yes, I was able to confirm that the Ajax is actually working when I click the other buttons, but it is only updating the first "#output" span instead of the span associated with that button.

    How do I tell the Ajax script to output to a unique span ID instead of a generic "output"?

    EDIT2: Fixed it, wasn't as complicated as I thought.

    javascript Code:
     
    divname = '#output_' + $(this).attr('data-id');
    ...
    success: function(data){
    	$(divname).html(data);
    },
    Last edited by BlackAce; October 11th, 2012 at 01:36 PM.
  8. #5
  9. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,128
    Rep Power
    4304
    As you found out through trial-and-error, IDs should be unique. A class can often be used instead.
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    195
    Rep Power
    45
    More roadblocks. Grrrr.

    So I've modified my code a bit. Previously, I had the <a> tag used to trigger the ajax sequence as a fixed part of the source page and not part of the output returned by Ajax.

    However, if someone has already "liked" a post, I want to return a different link for them to click on instead. Thus, I moved the #output div from my earlier code to the outside of the <a> tag so the entire <a> tag will be replaced when the link is clicked.

    When I click on the default link on the source page, the Ajax function works correctly, returning an updated link code to the source page. But clicking on the new link does nothing.

    Any thoughts?

    html Code:
     
    <span id='output_".$project_ID."'>
    	<a href='#' class='likeButton' data-id='".$project_ID."' data-type='project' data-mode='like'>".$like_count." likes</a>
    </span>


    And if they click on that link, this is what is returned from the other page via Ajax:

    html Code:
     
    <a href='#' class='likeButton' data-id='$id' data-type='$type' data-mode='unlike'>".$like_count." unlike</a>
    Last edited by BlackAce; October 11th, 2012 at 03:14 PM.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    195
    Rep Power
    45
    Sorry guys, I gotta bump this, as I'm stuck here.
  14. #8
  15. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,128
    Rep Power
    4304
    The onclick handler was only bound to elements that existed when the page first loaded (technically, when the "DOMContentLoaded" event fired), so elements that are loaded via AJAX won't have it applied to them.

    The best solution to this is to use event delegation, which is quite easy with jQuery 1.7+. I recommend you read JavaScript Event Delegation is Easier than You Think.

    Change
    Code:
    $('.likeButton').click(function(e){
    to
    Code:
    $('body').on('click','.likeButton',function(e){
    Last edited by Kravvitz; October 15th, 2012 at 05:20 PM.
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2010
    Posts
    195
    Rep Power
    45
    Originally Posted by Kravvitz
    The onclick handler was only bound to elements that existed when the page first loaded (technically, when the "DOMContentLoaded" event fired), so elements that are loaded via AJAX won't have it applied to them.

    The best solution to this is to use event delegation, which is quite easy with jQuery 1.7+. I recommend you read JavaScript Event Delegation is Easier than You Think.

    Change
    Code:
    $('.likeButton').click(function(e){
    to
    Code:
    $('body').on('click','.likeButton',function(e){
    Thank you for posting both a working solution, and a link to where I can go learn more. Many people seem to do just one or the other. As I read through this, it's jogging my memory a bit on events and bubbling. I had not yet done this with jQuery, so I appreciate it!
  18. #10
  19. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,128
    Rep Power
    4304
    You're welcome.

    I probably post links more often than I post code. In this case, the change was to a single line, so I posted it as well as two links. I'm here to help people learn (and hope to learn something occasionally myself). Just posting code fixes tends not to help people as much in the long term.
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).

IMN logo majestic logo threadwatch logo seochat tools logo