1

I have PHP code inside jQuery scriptm, and I want to pass a jQuery variable to PHP.

This is my code :

$(document).ready(function() {
 $('.editclass').each(function() {
  $(this).click(function(){
    var Id = $(this).attr('id');
      <?php 
            include "config.php";
            $query="SELECT * FROM users WHERE UserId=\'id\'";

      ?>
 $("#user_name").val(Id);
   });
});

});

I want the value of id to be exist in php code ($query)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M1M6
  • 915
  • 3
  • 17
  • 33
  • Technically jQuery doesn't have variables, JavaScript does. – Sterling Archer Jun 30 '14 at 18:32
  • 1
    impossible. PHP executes on the server, JS executes on the client. You cannot EVER mix your code like this. You need an ajax request to talk js->php. php cannot talk to JS except when the page is built, or via ajax responses. – Marc B Jun 30 '14 at 18:32
  • Your php code is compiled and sent to the user's browser. After the page is sent, the user's browser runs the javascript. The only way to send your variable to php is for the javascript to send it back to the webserver. You can do that a lot of different ways, but one way is to use jquery's [$.ajax](http://api.jquery.com/jquery.ajax/) method. – David Sherret Jun 30 '14 at 18:35

1 Answers1

2

Use $.post:

$(this).on('click', function(e){
    e.preventDefault();

    var Id = $(this).attr('id');

    $.post("yourscript.php", { 
        Id: Id 
    }, function(data){

        var theResult = data;
}, 'json' );

});

This is going to send two parameters (param1 and param2 to a php script called yourscript.php. You can then use PHP to retrieve the values:

$Id= isset($_POST['Id']) ? $_POST['Id'] : '';

The idea is you're sending variables from the client side to the server side via Ajax.

Yourscript.php

 <?php 
     include "config.php";
     $query="SELECT * FROM users WHERE UserId=$Id";

    /* Get query results */

    $results = use_mysql_method_here();

    /* Send back to client */

    echo json_encode($results);
    exit;    
 ?>
What have you tried
  • 11,018
  • 4
  • 31
  • 45