sergioo
sergioo

Reputation: 361

Pass data from a javascript variable to PHP variable

I made an Ajax request using JavaScript. I put the result in a variable called 'response'. I want to use the 'response' variable as a PHP variable "$response". How can I do it?

<html>
<head>
 <script src="{{asset("jquery/jquery.js")}}"></script>
</head>

<body>
<h1>AJAX</h1>
<div id="id01"> {{$response}}</div>

<script type="text/javascript">
 var req = new XMLHttpRequest();
 req.open("GET","{{route('allcontacts')}}",true);
 req.onload  = function() {
    if (req.readyState == 4 && req.status == 200) {
        response = JSON.parse(req.responseText);
        $("id01").html(response);
    }
};
req.send();
</script>

</body>
</html>

Upvotes: 0

Views: 39

Answers (2)

Doggit
Doggit

Reputation: 111

You will need to send the variable to PHP by using either a POST or GET request.

The simplest way would be to redirect to a URL including the javascript variable passed with it as a GET variable.

req.onload  = function() {
    if (req.readyState == 4 && req.status == 200) {
        response = JSON.parse(req.responseText);
        $("id01").html(response);
        responseGET = JSON.stringify(response);
        window.location.href = `yourphpfile.php?response=${responseGET}`; 
    }
};

Then deal with the variable in the yourphpfile.php file.

Upvotes: 1

Riki95
Riki95

Reputation: 726

You can use Javascript in server side.

<script type="text/javascript">
var res = '';
var req = new XMLHttpRequest();
 req.open("GET","{{route('allcontacts')}}",true);
 req.onload  = function() {
    if (req.readyState == 4 && req.status == 200) {
        res= JSON.parse(req.responseText);
        <?php $res = "<script>document.write(res)</script>"?>  
    }
};
req.send();
</script>
<div id="id01"> <?php echo $res;?> </div>

Upvotes: 1

Related Questions