Akshay
Akshay

Reputation: 191

how to send query string parameters in XMLHttpRequest to php page

I have following php variable of name

    $name=$_POST["name"];
    <script>
    pge = '<?php echo $name ;?>';        
    var url = "searchCustomerByNameApi2.php"
    //some code 
   xmlhttp.open("GET", url, true);
   xmlhttp.send();

how can I send pge variable along with url as aquery string and access it on the php page ??

Upvotes: 1

Views: 3899

Answers (4)

Dileep Kumar
Dileep Kumar

Reputation: 1107

Try "searchCustomerByNameApi2.php?pge="+pge and get it on php page like $_REQUEST['pge'].

Upvotes: 1

Fernan Vecina
Fernan Vecina

Reputation: 153

Have you tried below?

var url = "searchCustomerByNameApi2.php";
var test = "name=<?php echo $_POST["name"]; ?>";

xmlhttp.open("GET", url, true);
xmlhttp.send(test);

Hope this resolve your issue.

Upvotes: 0

Dharmendra Singh
Dharmendra Singh

Reputation: 1226

Simple you have your javascript code look like this.

<script>

   var  name  = '';

   name = '<?php print $_POST["name"]?>';   
   var url = "searchCustomerByNameApi2.php?name"+name;
   xhttp.open("GET", url, true);
   xhttp.send(); 

</script>

and php code look like searchCustomerByNameApi2.php page

   $name = $_REQUEST['name'];

Upvotes: 1

Alexander Higgins
Alexander Higgins

Reputation: 6923

You can use a function to create a query string from an object:

And append that result to your url:

$name=$_POST["name"];

<script>
function encodeQueryData(data) {
   let ret = [];
   for (let d in data)
          ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
   return ret.join('&');
 }

pge = '<?php echo $name ;?>'; 
var data = {pge: pge};
var query =encodeQueryData(data);       
var url = "searchCustomerByNameApi2.php";
url += "?" +query;
xmlhttp.open("GET", url, true);
xmlhttp.send();

Upvotes: 0

Related Questions