0

I want to update the value of an input field when I receive some information from an api. I tried using:

$('#txtFirstName').val($_SESSION['jUser']['first_name']);

But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?

I can't reload the entire window, because it will eliminate other information that the user of the website has put in.

  • 3
    You can either use AJAX or do something like this: [How do I edit PHP variable with JavaScript/jQuery?](https://stackoverflow.com/questions/54079448/how-do-i-edit-php-variable-with-javascript-jquery) – AndrewL64 Jun 09 '20 at 21:19
  • 1
    Once you're in JavaScript you must write JavaScript code, as in AJAX as Andrew suggests. `$.ajax` is your friend here. – tadman Jun 09 '20 at 21:32
  • Hi Caroline. Since you mentioned you receive the information from an API, and you obviously have access to the session data, why not include the first name (or any other data you want pre-filled) in that API response? Once the response is received, you just need to populate the form using JavaScript. – Romi Halasz Jun 10 '20 at 07:16

2 Answers2

0

1) put value into #txtFirstName from php script

// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo $_SESSION['jUser']['first_name'];
}   

// javascript code
function func(){
    $.ajax({
        type: "POST",
        url: "script.php",
        success: function (response) {
            $('#txtFirstName').val(response);
        },
        error: function (e) {
            console.log("ERROR : ", e);
        }
    });
}

2) put value into $_SESSION['jUser']['first_name'] from javascript

// javascript code
function func(){
    var your_value = "some_value";
    $.ajax({
        type: "POST",
        url: "script.php",
        data: { va: your_value },
        success: function (response) {
            console.log("value setted to session successfully");
        },
        error: function (e) {
            console.log("ERROR : ", e);
        }
    });
}

// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
    $_SESSION['jUser']['first_name'] = $_POST['va'];
    echo "ok";
}   
topolm
  • 1
  • 1
0

Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.

However, it can also be accomplished with the approach you've taken:

let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);

For further reading, you can visit How do I embed PHP code in JavaScript? .

Plabon Dutta
  • 6,819
  • 3
  • 29
  • 33