Damon Qu
Damon Qu

Reputation: 71

PHP client post request to Server side and server side post request to remote server

My scenario is as follows:

  1. when button clicked, client side will post request to server side
  2. once server side receive the request, it will post another request to remote sever to get the result
  3. once the response comes, server side should echo the response to client.

client

$.post('login_server.php'{act:"post",phone:phone,passwords:passwords},function(e){
      alert(e);
    },'json');

server

$act = isset($_POST["act"]) ? $_POST["act"] : "default";
if($act == "default"){
    var_dump(123123);
}elseif($act == "post"){
    $phone = $_POST["phone"];
    $password = md5($_POST["passwords"]);
    $data_array = array('phone' => $phone,'password' =>$password );
    $jsonStr = json_encode($data_array);
    $url = "http://xx.xx.xx.xx/xxxx/userinfo/login";
    $data = http_post_json($url, $jsonStr); 
    echo json_encode(123);  
}

function http_post_json($url, $jsonStr)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                      'Content-Type: application/json; charset=utf-8',
                      'Content-Length: ' . strlen($jsonStr)
                )
            );
  $response = curl_exec($ch);
  $abc = json_encode($response);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  return array($httpCode, $response);
}

I checked the login_server. It can get the response from remote server. But if I add

$response = curl_exec($ch);
the callback function doesn't work.

Is there anyone know this?

BRs Damon

Upvotes: 6

Views: 1802

Answers (1)

Igor Paiva
Igor Paiva

Reputation: 683

This doesn't work because you encode your array.

$jsonStr = json_encode($data_array);

Try that

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_array);

or

Here you need get the 'json'and decode on your page.

curl_setopt($ch, CURLOPT_POSTFIELDS, 'json='.$jsonStr);

http://php.net/manual/en/function.curl-setopt.php

Upvotes: 1

Related Questions