Mahmoud Jbor Mahmoud Jbor - 7 months ago 109
Javascript Question

How to use jQuery variable inside php code?

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
)

Answer

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;    
 ?>
Comments