php - Calling different POST variables using Ajax

806

I'm still new to jQuery and stuck trying to figure this one out, hope someone can help. I have this jQuery code that needs to pass different values depending on the clicked element. Each element created has a unique number in it's ID (which is needed). If I manually change the jQuery code to a specific ID and call, for example:

http://mysite/examplepost?effect=113

This will work. But I need to have $('#div- ...different numbers here...') to be able to handle multiple elements on the same page. I already have the PHP side producing different values using:

if($_GET['effect'] == $id){

I just need this to work with ajax so that it doesn't reload the page.

Example:

$('#div-113').on('click', function() {

    var dataString = 'effect=113';  

        jQuery.ajax(
            {
            type:'GET',
            url:'?',
            data: dataString,
            success: function(data){
                alert('Works');         
            }
          }
        );

      });

Any help would be appreciated.

296

Answer

Solution:

I would give all yourdivs a common classname (i.e.myClickableDiv) and also a specificdata-id.

This way you can target all your divs by that common classname, rather than having to figure it out depending on how theid is formed. Thedata-id allows you to only provide very specific information to the click handler (like an integer), without having to parse theid.

HTML:

<div class=".myClickableDiv" id="div-XXX" data-id="XXX">My Div</div>

JS:

$('.myClickableDiv').on('click', function() {

    var dataString = $(this).attr('data-id');  

    jQuery.ajax({...});

});

People are also looking for solutions to the problem: Where do I find a copy of Zend PHP Debugger for PHP 5.4?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.