Pedro
Pedro

Reputation: 21

Call Javascript function in PHP

I need to call a javascript function and use the results(Json) as variable for PHP. I have the following function:

<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>    
    <script>        
        $(function () {
            
            var baseUrl = 'https://XXXXXXXXX/';
            var uid = 'XXXX';
            var pwd = 'XXXX';
                        
            
            GetProd('DT.X0CEB.009', '1');

           function GetProd(cod_prod, qtd) {
                jQuery.support.cors = true;
                $.ajax({
                    url: baseUrl + 'api/Prod?ref=' + encodeURIComponent(cod_prod) + '&qtd=' + qtd,
                    type: 'GET',
                    jsonp: "callback",
                    dataType: 'jsonp',
                    username: uid,
                    password: pwd,
                    success: function (data, textStatus, xhr) {
                        document.write(data);
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        alert(xhr.responseText);
                   }
            });
        }
    });            
    </script>

This returns this:

Object { Ref: "DT.X0CEB.009", Desc: "Monitor UltraHD P2715Q 68.6cm 27"", State: 0, Price: Object, Tax: Object, Stock: 2, Availability: null }

Can anybody help me how to use this fields (ref, desc, state, ...)in php? Regards Pedro

Upvotes: 1

Views: 100

Answers (1)

Joe Fitter
Joe Fitter

Reputation: 1309

You are sending them as GET params therefore they should be available in your endpoint via $_GET. You could also try sending a data object via POST and retrieve them with $_POST in your php API.

$.ajax({
  url: 'yourUrl',
  method: 'POST',
  data: {
    param1: param1,
    param2: param2
  },
  success: function(data) {
    //do something with data
  }
});

PHP

$param1 = $_POST['param1'];
$param2 = $_POST['param2'];

Upvotes: 1

Related Questions