Search code examples
javascriptphpjquerylaravelsquare-connect

How Do I Access My PHP Response in Javascript in My View?


I'm trying to use my PHP response in a view and output to the console using JavaScript. I can pass the variable $e->getResponseBody()->errors['0']->detail and use it in my view, but how do I access it in JavaScript?

// My controller
try {

} catch (\SquareConnect\ApiException $e) {
    return View::make('reservations.paymentForm')->with('e', $e)->render();
}

// My view JavaScript
$(document).ready(function (e) {
    console.log(e.detail);
});

When a user submits, and an error occurs I want to redirect them back to the form view and show error in console with JavaScript (example: CVV code incorrect). Ultimately I won't be using the console but once I get that I feel confident manipulating the rest.


Solution

  • After much help here is the answer. I ended up not actually using javascript in the end but my answer will show it. If you pass the variable to the view, you can use it in javascript.

    // My controller
    try {
    
    } catch (\SquareConnect\ApiException $e) {
    return View::make('reservations.paymentForm')->with('myVariable', $myVariable)->render();
    

    }

    // My view JavaScript
    $(document).ready(function () {
    var myVariable = '<?php echo $myvariable ; ?>';
    console.log(myVariable);
    });