0

I'm sending data to a php page for processing through jQuery and ajax and as result I will get

success: function(data){
mydata = data;
}

my data is an url that looks like mydata = https://myurl.com. Now I want to set mydata to a php variable and use it again inside another function in the main page, means: to set $url = mydata;. How can I do that?

Thanks,

Joe Jeffry
  • 33
  • 6
  • You can't set a PHP variables from JS on the same page. PHP is executed on the server, then the result of that gets sent to the client where the JS gets executed. If you want to pass the JS variable through a PHP function, you need to do a new Ajax call. – M. Eriksson Jun 03 '18 at 11:31
  • Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – M. Eriksson Jun 03 '18 at 11:33

3 Answers3

0

You can do that using Post via a from, GET via a query string or you can use cookie like in this solution

how to assign javascript variable value to php variable

  • Reading the question, it looks like the OP wants to set a PHP variable on the same page after an Ajax request, not in another script (POST or GET) or after a page reload (Cookies). – M. Eriksson Jun 03 '18 at 11:40
  • If that's the case he can use another ajax request to trigger the function that will set the variable. – Niroj Maharjan Jun 03 '18 at 13:44
  • No, the OP wants to store the response from an ajax request in a PHP variable _on the same page_. That simply can't be done. – M. Eriksson Jun 03 '18 at 13:45
0

You can send the mydata variable to PHP by calling an XMLHttpRequest() via AJAX.
For example

var ajax = new XMLHttpRequest(); // Create new request
ajax.open("POST", "mainpage.php"); // Open the file where you want to send it with POST
ajax.send("mydata="+mydata); // Send mydata variable to PHP

Then in PHP you can check for the variable mydata

if(isset($_POST['mydata'])){
    // do something
}
squancy
  • 565
  • 1
  • 7
  • 25
-1

PHP scripts execute when you open a file and before everything else. Ajax calls exectue when the Javascript is completely loaded. (After php).

So you cant do it. could you give me more detail about what do you want to do?

Masih IT
  • 52
  • 10
  • Is it possible to set `$url` to the result of output `
    ` that can be shown after adding this below code to `success: function(data)` and the code is: `$('#result').html(data)` ?
    – Joe Jeffry Jun 03 '18 at 11:44
  • Actually No. PHP is executed on the server. JS is executed on the client computer and they cant communicate with each other without someting like Ajax Call or Fetch or ... . – Masih IT Jun 03 '18 at 11:51