April 7, 2012

Put DIV ID into a PHP Variable

Question by drummer392

I am wanted to get the id’s of all the divs on my page with the class archive and put them in a MySQL query to check and see if the ids are archived in the database.

So basically I am wondering how I can do this: $div = $(this).attr('id');

Then I would throw it into the loop to check:

$matches = mysql_query("SELECT * FROM content WHERE `div` = '$div'");
        while ($post = mysql_fetch_assoc($matches)) 
        {
            if (mysql_num_rows($matches) > 0)
            { 
              //DO THIS
            }
        }

UPDATE

I have this code for the AJAX now:

$('div.heriyah').each(function() { 
var curID = $(this).attr('id'); 
$.post("admin/btnCheck.php", { div : curID }, function(data) {
if (data == "yes") {
    $('#' + curID).html('<div class="add"><div id="add_button_container"><div id="add_button" class="edit_links">  + Add Element</div></div></div><div class="clear"></div></div>');
} else {
    $('#' + curID).html('<div class="add"><div id="add_button_container"><div id="add_button" class="edit_links">  + Set As Editable Region</div></div></div><div class="clear"></div></div>');
}
  });
});

And my PHP:

$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['div']."'");
 if (mysql_num_rows($matches) > 0)
 { 
    echo "yes";
 } else {
    echo "no";
 }

What am I doing wrong?

Answer by Starx

You cannot throw a javascript variable to PHP script like that. You have to send an ajax request to the page

$div = $(this).attr('id');
$.post("yourquerypage.php", { divid : $div }, function(data) {
    // Something to do when the php runs successfully
});

Next, configure your query to get the variable from $_POST()

$matches = mysql_query("SELECT * FROM content WHERE `div` = '".$_POST['divid']."'");

And of course, you have to take measures for injection.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!