2016-12-02 14 views
0

私は、SMSサービスがコンテンツタイプをjsonとしてこの形式でデータを送信することを希望するAPI統合を持っています。Jquery Ajaxは、フォームデータを使用してJSON配列形式を渡します。

{ 
    "from": "91887654681", 
    "to": ["918757077777"], 
    "body": "Hi this is my message using Mblox SMS REST API" 
} 

私は、from、to、bodyという入力テキストを持つフォームを持っています。

これは私のフォームの送信方法です。

$("#sendSMSForm").submit(function(event){ 
    event.preventDefault(); 
    // Serialize the form data. 
    var form = $('#sendSMSForm'); 
    var formData = $(form).serialize(); 
    //alert(formData); 
    $.ajax({ 
     type: 'POST', 
     dataType: 'json', 
     contentType: "application/json", 
     url: $(form).attr('action'), 
     data: formData 
    }).done(function(response) { 
     // Do some UI action stuff 
     alert(response); 
    }); 
}); 

私はよく分かりません... "to"が配列である同様の形式を渡すために使用する必要があります。

+1

クライアントサイドのjqueryでこの統合を行うと、誰かがあなたのSMS請求書を実行します。このサーバ側をPHPで処理します。とにかく、これはなぜPHPでタグ付けされていますか? – WEBjuju

答えて

3

単にあなたの入力フィールドあなたはjQueryのフォームプラグインを使用していないのはなぜto配列

<input type="number" name="to[]" value="918757077777"/> 
<input type="number" name="to[]" value="918757077778"/> 
<input type="number" name="to[]" value="918757077779"/> 
+0

うん。そのとおり。あなたはこの答えを確かに考えることができます。 – Perumal

+0

@VishalKumar https://plugins.jquery.com/serializeJSON/ – Justinas

0

@ WEBjujuのコメントは非常に参考になった....クライアント側でこのような統合を行う理由は...その本当の初心者や悪い練習。最後に、私はこれをサーバー側で管理しています... PHPを使用してそのようなjsonを作成します。以下は、誰かを助けることができるサンプルです。これは、cURLを使用してHTTP REST呼び出しを行うPHP関数です。

function callAPI($to, $body) 
{ 
try{ 
// I am creating an array of Whatever structure I need to pass to API 
$post_data = array('from' => ''.$this->from.'', 
'to' => array(''.$to.''), 
'body' => ''.$body.''); 

//Set the Authorization header here... most APIs ask for this 
$curl = curl_init(); 
$headers = array(
'Content-Type: application/json', 
'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXX' 
); 
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 

//If you have basic authorization, next 3 lines are required 
$username ="venturecar15"; 
$password = "voaKmtWv"; 
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password); 

//Not receommended but worked for me 
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 

curl_setopt($curl, CURLOPT_URL, $this->ApiURL); 
curl_setopt($curl, CURLOPT_POST, true); 
//This is how we can convert an array to json  
$test = json_encode($post_data); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $test); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
$result = curl_exec($curl); 
} catch(Exception $e) { 
    return "Exception: ".$e->getCode()." ".$e->getMessage(); 
} 

if($result === FALSE) { 
    $error = curl_error($curl)." ".curl_errno($curl); 
    return "Error executing curl : ".$error; 
} 
curl_close($curl); 
return "SMS sent successfully to ".$to."."; 
} 
関連する問題