Single Cross Domain AJAX Request needed

81 Views Asked by At

Trying to implement sending sms features in my ecommerce store.

I use service called esteria.lv and they provided me with API link that looks like this: http://api1.esteria.lv/send?api-key=api_key&sender=example.com&number=11223344&text=message

If the message is sent then it outputs message ID, now it outputs error number 3(unable to authenticate).

To get it working with my ecommerce store, I found this resource: http://www.ajax-cross-origin.com/examples/cross-origin.htm, and made this code:

$(function() {

$( '#btn' ).click(function(){
  $.ajax({
    crossOrigin: true,
    url: 'http://api1.esteria.lv/send?api-key=api_key&sender=example.com&number=11223344&text=message',
    success: function(data) {
      $( '#test' ).html(data);
    }
 });
 }); 
}); 

It works, but the problem is, it sends 6 messages (requests) instead of just one. I need just 1 request and one sent sms. Anyone have any suggestions?

1

There are 1 best solutions below

3
peppeocchi On

To answer your comment, this is what you should do.

In your javascript you should have an ajax call to your server

// collect sms data
$.ajax({
  url: 'yourserver/handlesms',
  method: 'post',
  data: {
     sender: '[email protected]',
     number: '1234567',
     message: 'Test message'
  }
}).then(function (data) {
  alert("Message sent!");
});

In your server you should have an handler for sending the sms, something like (I don't know what's your platform, I'll just write a really simple php example)

$data = $_POST;
$apiKey = '12345643223213ds';

$endpoint = 'http://api1.esteria.lv/send';

// Create new curl request
$ch = curl_init($endpoint);
// curl settings, add your data, api key etc...
$result = curl_exec($ch);

// Result will contain the response from your api call
// Then you can send a result back to your client (js)
echo json_encode(['status' => 'Message sent!']);

This is just an example, the server code depends on your platform.

In this case you don't have any cross origin request (all the js request will be sent to your server, that then is in charge of contacting your sms provider and send the messages.

The problem that's executed 6 times I think depends on something else but it's hard to say without looking at the rest of the code (you can try debugging the click event on #btn and see how many times is executed every time you click on the button.