Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element id into PHP variable

Tags:

php

mysql

Is it possible to get an element id into a PHP variable?

Let's say I have a number of element with IDs:

<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>

How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:

<script language="JavaScript">
$(document).ready(function(){
    $(".myElement").click(function() {
        $.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
    });
});
</script>

I need to pass $(this).attr('id') into $newID in order to run

SELECT * from t1 WHERE id = $newID

jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.

Thanks.

like image 695
santa Avatar asked Mar 02 '11 03:03

santa


1 Answers

This is like your question: ajax post with jQuery

If you want this all in one file (posting to active file) here is what you would need in general:

<?php 
  // Place this at the top of your file
  if (isset($_POST['id'])) {
    $newID = $_POST['id'];  // You need to sanitize this before using in a query

    // Perform some db queries, etc here

    // Format a desired response (text, html, etc)
    $response = 'Format a response here';

    // This will return your formatted response to the $.post() call in jQuery 
    return print_r($response);
  }
?>

<script type='text/javascript'>
  $(document).ready(function() {
    $('.myElement').click(function() {
      $.post(location.href, { id: $(this).attr('id') }, function(response) {
        // Inserts your chosen response into the page in 'response-content' DIV
        $('#response-content').html(response); // Can also use .text(), .append(), etc
      });
    });
  });
</script>

<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>

<div id='response-content'></div>

From here you can customize the queries and response and what you would like to do with the response.

like image 181
Laxman13 Avatar answered Oct 02 '22 01:10

Laxman13