I have an API integartion where the SMS service wants us to send data in this format with content-type as json.
{
"from": "91887654681",
"to": ["918757077777"],
"body": "Hi this is my message using Mblox SMS REST API"
}
I have a form with input texts namely from, to and body.
This is how my form submits.
$("#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);
});
});
I am not sure ...what should be used to pass a similar format.... of which the "to" is an array.
Simply make your input fields to
array
<input type="number" name="to[]" value="918757077777"/>
<input type="number" name="to[]" value="918757077778"/>
<input type="number" name="to[]" value="918757077779"/>
Why don't you use jQuery Form plugin? http://malsup.com/jquery/form/#getting-started
You can use $.ajaxSubmit instead.
@WEBjuju's comment was very helpful.... Why to do such Integrations in client side... its really a novice and bad practice. Finally I am managing this on the Server side...creating such json using PHP. Below is the sample that could help someone. This is a PHP function to make a HTTP REST call using cURL.
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.".";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.