2017-02-13 7 views
0

私はどこでも私の質問の答えを得るために検索しました。私は本当に私の問題を助けるために専門家が必要です。私は外部APIのURLにajaxを使用してデータをPOSTするためのコードを作成しました。Ajax JQuery外部apiにPOSTデータを送信

私が作成したコードは以下のようなものです:

$.ajax({ 
 

 
    url: "https://www.billplz.com/api/v3/collections", 
 
    beforeSend: function(xhr) { 
 
    xhr.setRequestHeader("Authorization", "Basic " + "73eb57f0-7d4e-42b9-a544-aeac6e4b0f81:"); 
 
    }, 
 
    type: "POST", 
 
    data: { 
 
    "title": "My First API Collection" 
 
    }, 
 
    contentType: 'application/json', 
 
    dataType: 'jsonp', 
 
    success: function(data) { 
 
    alert("Successfully Registered.."); 
 
    }, 
 
    error: function(xhRequest, ErrorText, thrownError) { 
 
    alert("Failed to process correctly, please try again"); 
 
    console.log(xhRequest); 
 
    } 
 

 
});

私はAPIドキュメントからこのサンプルカールコードを取得しようとしました:

# Creates an open collection 
 
curl https://www.billplz.com/api/v3/open_collections \ 
 
    -u 73eb57f0-7d4e-42b9-a544-aeac6e4b0f81: \ 
 
    -d title="My First API Open Collection" \ 
 
    -d description="Maecenas eu placerat ante. Fusce ut neque justo, et aliquet enim. In hac habitasse platea dictumst." \ 
 
    -d amount=299

APIのドキュメントはhere

私は以前の問題ではありましたが運がないすべての方法を試しました。私はまた、PHPなしでJQuery/AJAXでこれをやろうとしました。

+0

サーバーのアドレスは何ですか? 'http'または' https'? –

+0

https @AtaurRahmanMunnaを使用している外部API –

+0

ブラウザのコンソールに表示されるエラーは何ですか?これをチェックできますか? –

答えて

0

私はこれをどうやってできるのか分かりません。しかし、ここに私の質問に対する答えがあります。私はそれが他人を助けることができることを望む

まず、AJAXは誰でも読むことができるJSONオブジェクトを投稿するため、AJAXを使用して認証キーをPOSTしないでください。 curlプロセスでは、Perl、PHP、Python、Ruby、JavaScript(ノード)、Scala、Java、Go、ASP.NET、ColdFusionなどのサーバーサイドスクリプトを使用する必要があります。

私の場合、ここで私はカールのプロセスを行うためにPHPを使用します。以下は、Ajaxのポストのための私のコードは次のとおりです。

$.ajax({ 
 
      url: 'creating_bill.php', 
 
      data: { 
 
       item : 'item' 
 
      }, 
 
      type: "POST", 
 
      dataType: "json", 
 
      success: function (data) { 
 
       alert('Success ! You will redirect in 100 seconds'); 
 
       console.log(data)    
 
       window.open(data.url, '_blank'); 
 
       setTimeout(function() 
 
       { 
 
        window.location = 'index.html'; 
 
       },10000); 
 
      }, 
 
      async: false, 
 
      error: function(data) { 
 
       handleRequestError(data); 
 
      } 
 
     }) 
 
}
以下

カールプロセスを行うには、PHPで私のコードです:

<?php 
 

 
$item = $_POST['item']; 
 

 

 
$api_key = ''; 
 
$api_url = ''; 
 
$collection_id = ''; 
 
    
 
$data = array(
 
      'item' => $item, 
 
); 
 
    
 
$process = curl_init($api_url); 
 
curl_setopt($process, CURLOPT_HEADER, 0); 
 
curl_setopt($process, CURLOPT_USERPWD, $api_key . ":"); 
 
curl_setopt($process, CURLOPT_TIMEOUT, 30); 
 
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE); 
 
curl_setopt($process, CURLOPT_POSTFIELDS, http_build_query($data)); 
 
    
 
$result = curl_exec($process); 
 
curl_close($process); 
 

 

 
print_r($result); 
 
$return = json_decode($result, true); 
 
?>

関連する問題