0

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>
1

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>

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.