Bartosz Zieliński
Bartosz Zieliński

Reputation: 41

Symfony 2 send json by ajax

For the purposes of testing I'd like to send parameter of using ajax to Symfony controller but the controller can not read the request.
I Twig I'm trying to send the value of input element via ajax request to Symfony controller. Code in twig:

<body>
<h1>JQuery Ajax Json example</h1>

<script type="text/javascript">
    $(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"/payu",
                type:"POST",
                data:{
                    customerIp:$("#customerIp").val()

                },
                dataType:"JSON",
                success:function(jsonStr){
                    $("#result").text(JSON.stringify(jsonStr));
                }
            });
        });
    });
</script>


<div id="result"></div>
<form name="contact" id="contact" methode="post">
    customerIp:<input  name="customerIp" id="customerIp" value="123.123.123.123"/></br>

    <input type="button" value="submit" name="submit" id="submit"/>
</form>

<h1>{{ result }}Format Data{{ result }}</h1>
</body>

In controller action, I'm reading the request content and decoded it using json_decode function. Code in controller:

 public function payuAction(Request $request)
 {
     $veriable=[];
     if ($content=$request->getContent()) {
         print_r($request);
         $veriable = json_decode(getContent(),true);
         print_r($veriable);
     }

     return $this->render('BartekPsiutekBundle:Default:payu.html.twig', array('result' => $veriable));
}

Upvotes: 1

Views: 3505

Answers (7)

Bartosz Zieliński
Bartosz Zieliński

Reputation: 41

I will intend catch value of parameters in html using ajax and on the controler(symfony) send data in json using curl.

<script type="text/javascript">
    $(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"send",
                type:"POST",
                crossDomain: true,
                headers: {
                    'Authorization':'Basic MTQ1MjI3OjEzYTk4MGQ0Zjg1MWYzZDlhMWNmYzc5MmZiMWY1ZTUw',
                    'Content-Type':'application/json'
                },
                dataType: 'jsonp',
                data:{
                    customerIp:$("#customerIp").val(),
                    merchantPosId:$("#merchantPosId").val(),
                    description:$("#description").val(),
                    totalAmount:$("#totalAmount").val(),
                    currencyCode:$("#currencyCode").val(),
                    products1name:$("#products1name").val(),
                    products1unitePrice:$("#products1unitePrice").val(),
                    products1quantit:$("#products1quantit").val(),
                    notifyUrl:$("#notifyUrl").val(),
                    continueUrl:$("#continueUrl").val()


                },

                beforeSend:function(){
                    console.log($("#customerIp").val());

                }

            });
        });
    });
</script>
<div id="result"></div>
<form name="contact" id="contact" methode="post">
    customerIp:<input  name="customerIp" id="customerIp" value="123.123.123.123"/></br>
    merchantPosId:<input name="merchantPosId" id="merchantPosId" value="145227"/></br>
    description:<input name="description" id="description" value="Opis zamówienia"/></br>
    totalAmount:<input  name="totalAmount" id="totalAmount" value="1000"/></br>
    currencyCode:<input  name="currencyCode" id="currencyCode" value="PLN"/></br>
    products1name:<input  name="products1name" id="products1name" value="Produkt 1"/></br>
    products1unitePrice:<input  name="products1unitePrice" id="products1unitePrice" value="1000"/></br>
    products1quantit:<input  name="products1quantit" id="products1quantit" value="1"/></br>
    notifyUrl:<input  name="notifyUrl"  id="notifyUrl" value="http://shop.url/notify" /></br>
    continueUrl:<input  name="continueUrl" id="continueUrl" value="http://shop.url/continue" /></br>

    <input type="button" value="submit" name="submit" id="submit"/>
</form>

In Controller in symfony

public function sendAction(Request $request)
    {
        print('Jestem tutaj');
        $variable = '';
        $merchantPosId='';

        if ($request->request->get('customerIp') != null) {
            $variable = $request->request->get('customerIp');
        }

        if ($request->request->has('merchantPosId')) {
            $merchantPosId = $request->request->get('merchantPosId');
        }
        if ($request->request->has('merchantPosId')) {
            $merchantPosId = $request->request->get('merchantPosId');
        }
        if ($request->request->has('description')) {
            $description = $request->request->get('description');
        }
        if ($request->request->has('totalAmount')) {
            $totalAmount = $request->request->get('totalAmount');
        }
        if ($request->request->has('currencyCode')) {
            $currencyCode = $request->request->get('currencyCode');
        }
        if ($request->request->has('products1name')) {
            $products1name = $request->request->get('products1name');
        }
        if ($request->request->has('products1unitePrice')) {
            $products1unitePrice = $request->request->get('products1unitePrice');
        }
        if ($request->request->has('products1quantit')) {
            $products1quantit = $request->request->get('products1quantit');
        }
        if ($request->request->has('notifyUrl')) {
            $notifyUrl = $request->request->get('notifyUrl');
        }
        if ($request->request->has('continueUrl')) {
            $continueUrl = $request->request->get('continueUrl');
        }
        if (isset($variable)) {
            $data = array(
                "customerIp" => $variable,
                "merchantPosId" => $merchantPosId,
                "merchantPosId" =>$merchantPosId,
            "description=" =>$description,
            "totalAmount=" =>$totalAmount,
            "currencyCode=" =>$currencyCode,
            "products"=>array(
                "name" =>$products1name,
                "unitPrice"=>$products1unitePrice,
                "quantity" =>$products1quantit
            ),
            "notifyUrl=" =>$notifyUrl,
            "continueUrl=" =>$continueUrl

            );
            $data_string = json_encode($data);
            $ch = curl_init('https://secure.payu.com/api/v2_1/orders');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Authorization:Basic MTQ1MjI3OjEzYTk4MGQ0Zjg1MWYzZDlhMWNmYzc5MmZiMWY1ZTUw'
            ));
            $contents = curl_exec($ch);
            curl_close($ch);

        }


        print_r($variable);
        return $this->render('BartekPsiutekBundle:Default:send.html.twig',array('result' => $data_string));
    }

Upvotes: 0

Zain Saqer
Zain Saqer

Reputation: 304

Your javascript/jquery code send your data as application/x-www-form-urlencoded type not as JSON. And to read post data in your controller use $variable = $request->request->get('customerIp');, as @Pitchwaiz mentioned in his answer.

Your javascript code could be like:

$(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"/payu",
                type:"POST",
                data:{
                    customerIp:$("#customerIp").val()

                },
                success:function(data){
                    $("#result").text(data);
                }
            });
        });
    });

And your controller code could be like:

public function payuAction(Request $request)
{
     $veriable='';
     if ($request->request->has('customerIp')) {
         $veriable = $request->request->get('customerIp');
         return new Response($veriable);
     }

     return $this->render('BartekPsiutekBundle:Default:payu.html.twig', array('result' => $veriable));
}

Controller check in POST data for variable named customerIp, if the variable is there the controller will send it back.

Upvotes: 0

Bartosz Zieliński
Bartosz Zieliński

Reputation: 41

But in script in twig, there should be this below

<script type="text/javascript">
    $(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"/payu",
                type:"POST",
                data:{
                    customerIp:$("#customerIp").val()
                },
                dataType:"json"

            });
        });
    });
</script>

Upvotes: 1

Pitchwaiz
Pitchwaiz

Reputation: 43

You should get your data by name, controller should look like

public function payuAction(Request $request)
{
    $variable = '';
    if ($request->request->get('customerIp') != null) {
        $variable = $request->request->get('customerIp');
    }

    return $this->render('BartekPsiutekBundle:Default:payu.html.twig', array('result' => $variable));
}

Since you are sending POST request, this is the way to get your data. You can find documentation here: http://symfony.com/doc/current/book/http_fundamentals.html

Upvotes: 0

Ricardo
Ricardo

Reputation: 522

You're trying to access getContent, you've put the value of it in $content earlier. Strangely enough calling getContent like a function should return an error. The correct way of calling it is $request->getContent()

So instead of:

json_decode(getContent(),true)

You should see if this works:

json_decode($content,true)

Upvotes: 0

Kevin
Kevin

Reputation: 1569

I think you should do

$(document).ready(function(){
    $("#submit").click(function(){
        $.ajax({
            url:"/payu",
            type:"POST",
            data:JSON.stringify(values),
            dataType:"JSON",
            success:function(jsonStr){
                $("#result").text(JSON.stringify(jsonStr));
            }
        });
    });
});

and in your controller

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);

Upvotes: 0

CiTNOH
CiTNOH

Reputation: 186

This is because, you send plain text. Your Ajax call requests the answer to be in JSON (with dataType). You cant define the sending format.

To encode your value use as described here

Upvotes: 0

Related Questions