CloudSeph
CloudSeph

Reputation: 883

How to pass ajax val to php variable on the same page?

$('#test-test_id').change(function() {
        var myValue = $(this).val();
    });

// $getMyValue = $(this).val();

For example, by using the code above, I want to pass $(this).val to the php variable on the same page. How is this possible?

Upvotes: 1

Views: 1041

Answers (2)

Jack jdeoel
Jack jdeoel

Reputation: 4584

windown.location can reload page with parameters . You can try that in sending val to php variable like below...

<input type="text" id="test-test_id">
<?php
   if(isset($_GET["val"])){
     $sent = $_GET["val"];
     echo "<h2>".$sent."</h2>";
   }
?>
<script type="text/javascript">
$('#test-test_id').change(function() {
        var myValue = $(this).val();                            
        window.location = '?val=' + myValue; //redirect page with para ,here do redirect current page so not added file name .                      
    });   

Update code for without refresh

$('#test-test_id').change(function() {

        var myValue = $(this).val();
        $.get("",{val:myValue},function(data){
            $("body").html(data);
        });               
     //you can try with many option eg. "$.post","$.get","$.ajax"
     //But this function are not reload page so need to replace update data to current html
    });   
</script>

Upvotes: 2

SyncroIT
SyncroIT

Reputation: 1568

What you want to do is a bit complicated, first you must make an AJAX request where you pass the variable from client to server, like this:

$.post('/', { variable: "your_value_here" }, function() {
   alert('Variable passed');
}); 

This simple code, made in Javascript sends a POST Request to a URL that you pass to function as the first parameter, in this case we pass to $.post the same page. Now, in PHP you must handle the POST request:

session_start(); // We start a session where we'll set the value of variable.
if(isset($_POST['variable'])) {
   $_SESSION['your_var'] = $_POST['variable'];
} else {
   /* Your page code */ 
}

You can also register the variable in the database, but if it's a temporary variable you can just register it in the session. Remember to use session_start() in every page before using $_SESSION global variable.

Helpful documentation: jQuery.post() , PHP Sessions

Upvotes: 0

Related Questions