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>

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.