Single Cross Domain AJAX Request needed - ajax

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?

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#mail.com',
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.

Related

Twilio awaits response, I don't want server to respond

I am using a Slack webhook to process incoming SMS messages from Twilio. However, the way I have it set up, It seems that Twilio is expecting the web server (slack) to respond to it. This causes errors to be generated in Twilio, and I obviously don't want errors because I'll be getting emails.
I am using the twilio-ruby gem in Ruby to send out the SMS messages, and using the slack-ruby-client to monitor incoming messages from Slack.
How do I stop Twilio from trying to expect a response from the web server when it POSTS to the Slack webhook? Is that even possible or do I have this all configured incorrectly?
EDIT
Here's the function that I have which sends the forwarded SMS to Slack:
const https = require("https");
// Make sure to declare SLACK_WEBHOOK_PATH in your Environment
// variables at
// https://www.twilio.com/console/runtime/functions/configure
exports.handler = (context, event, callback) => {
// Extract the bits of the message we want
const { To, From, Body } = event;
// Construct a payload for slack's incoming webhooks
const slackBody = JSON.stringify({
text: `!asi SMS\nFrom: ${From}\nMessage: ${Body}`
});
// Form our request specification
const options = {
host: "hooks.slack.com",
port: 443,
path: context.SLACK_WEBHOOK_PATH,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": slackBody.length
}
};
// send the request
const post = https.request(options, res => {
// only respond once we're done, or Twilio's functions
// may kill our execution before we finish.
res.on("end", () => {
// respond with an empty message
callback(null, new Twilio.twiml.MessagingResponse());
});
});
post.write(slackBody);
post.end();
};
Twilio developer evangelist here.
Twilio is always going to expect at least a 200 response or will timeout at 15 seconds for incoming message webhooks.
You could avoid the error messages by using something in between Twilio and Slack, like Zapier (example in this blog post) or using a Twilio Function (as described here) or with Twilio Studio (from the documentation here).
Hope one of those ideas helps!
Update
Further to my earlier answer, and given the code you used to make the call, I have an update.
When making a request using Node's built in https module you will not get the end event until you have read the data. This is what is causing the timeout between Twilio and the Twilio Function, you are never responding to it because you don't consume the data from the request.
In a quick test I found that just listening for the data event meant that the end event did fire. So update your function to:
const post = https.request(options, res => {
// only respond once we're done, or Twilio's functions
// may kill our execution before we finish.
res.on("data", () => {});
res.on("end", () => {
// respond with an empty message
callback(null, new Twilio.twiml.MessagingResponse());
});
});
And it should work.

how to control multiple ajax requests in laravel 5.2

I am working on an application where different ajax requests fires depending upon different actions.
For example, there is a chat window having send button. When i click on that button an empty message is sent with ajax, successfully. It work nice. But when I hit the send button too many times, at start some requests respond 200 (ok) but then it respond 500 (internal server error). Due to this the other requests that are going continuously like updateLastActivity also disturb.
The preview of the error in developer's tool is:
Whoops like something went wrong.
Note: When I make this chat system in core PHP, it work fine. There is no internal server error when I send too may requests.
Here is the code I am using
//the following code is used to send the message
$(document).on('click','.send_message_bt',function(event){
event.preventDefault();
var id=$(this).data('id');
var name=$(this).data('name');
var message=$("#message_field-"+id).val();
$.ajax({
//headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
headers: { 'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!} },
url:'{{route('user.sendmessage')}}',
type:'POST',
data:{
id:id,
message:message
},
success:function(data,status){
//clear the message field value
$("#message_field-"+id).val('');
//update the chat history
fetchChatHistory(id,name);
},
error:function(response){
if(response.status==401){
alert('You are not logged in!');
window.location=window.location.href;
}
}
});
});
here is the back end code
public function sendMessage(Request $request){
$message=new Userchatmessage();
$message->message=$request->message;
$message->sender_id=Auth::user()->id;
$message->receiver_id=$request->id;
$message->save();
return response('success');
}
How to fix this issue.
I guess it's not a problem with Laravel or anything, but with your browser. Each browser has a maximum amount of simultaneous connections it will open for a certain domain.
Read more about this problem here and here.
If you want to make a realtime chat application, consider using something like NodeJS and Socket.io.
Async and await can help. Let an async function
async function doAjax(){
await runFirstAjaxCall();
await runAfterFirstAjaxCallSuccess();
....
....
}
doAjax();

Shopify order API returns OK but does not update order using JS

I'm trying to create an order using JS. I've authenticated my app and have a function that POST's to orders.json. I see a status code of 200, indicating that the request submitted OK (right?) but the order itself never gets created. I've heard something about disabling cookies in my request, but I don't know how to do that, so if that's what I need to do please let me know.
I'm putting up my entire function, since I'm new to this entire thing and it seems that it's probably the structure of my request, not the API call. I'm seeing the "Error" log in the console, so clearly the error function is running.
function submitShuffle(prodid)
{
console.log(prodid);
var params = {
"order": {
"line_items": [
{
"variant_id": prodid,
"quantity": 1
}
]
}
};
$.ajax({
type: 'POST',
url: 'https://<my-usrnam>:<my-pass>#toyboxshufflesandbox.myshopify.com/admin/orders.json',
dataType: 'application/json',
data: params,
success: function(data){
console.log(data);
},
error: function(data){
console.log("Error");
console.log(data);}
});
}
You cannot retrieve information from Shopify Admin API by AJAX. There is a limitation about this because you have to expose your username/key and password which is not a good idea.
You have to use some service/app or just to create a custom app.
Shopify returns an Object when you make a call. Hence 200 OK status. Inspect the object returned. A failed create POST object will not have an ID. So there is clue number one. Secondly, you'll see that Shopify tells you what the problem was in the Error key of the returned object. If you cannot figure out what you did with the message from Shopify, make the same call to the GraphQL endpoint if you can, as the error messages Shopify returns from those endpoints are currently much better. They are backporting them to the older REST API, but for now, GraphQL is more expressive.

October CMS - API Generator - how to create and update data in database

I try to send data to the database using AJAX and plugin in October CMS called "API Generator".
I can't find in its documentation or in Google anything that will help me.
The code I have is this:
$data = [{'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01', 'departure': '2018-04-03,', 'reservation_type': 'owner'}]
$.ajax({
url: '/api/v1/booking/create',
data: $data,
type: "post"
})
.done(function() {
console.log('Success')
})
.fail(function() {
console.warn('Something went wrong');
});
I don't get any error, in fact, I get 'Success' message in console, but data is not added to the database.
What am I doing wrong?
Please help.
Thanks.
Actually you are doing it little wrong [ You are firing Ajax request at wrong end-point ] that Api Plugin is based on https://laravel.com/docs/5.6/controllers#resource-controllers Resource Controller
So, To create an item you need to fire only POST request to Created Api-End Point. You don't need to send Array just send simple plain Object
Refactored your code ( this should work ):
// Plaing object no array
$data = {'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01',
'departure': '2018-04-03,', 'reservation_type': 'owner'};
$.ajax({
url: '/api/v1/booking', // <- just your Api-End [no create/store]
data: $data,
type: "post" // <- this post request indicates that you want to create/insert
})
.done(function(response) {
// this will always fire when status code is 200
console.log('Success', response);
})
.fail(function() {
// when status code is not 200 this will execute
console.warn('Something went wrong');
});
Why you get success although its not Creating Record ?
Because according to Resource Controller there is no method create in api generator controller so October CMS is treating /api/v1/booking/create [POST] request as 404 page not found and its serving [200] status code with 404 page not found as ajax response.
And 404 page is having 200 status code so it fall in to success category and Ajax thinks it's a successful request and prints success message in console.
if any doubts please comment.

.ajax posts and gets response on local server, no response on web host

I'm using an ajax call to do a minor calculation then return the value and display it in the page same page where the form is submitted. In Firebug it says it calls the function, however doesn't get a response. (I have a similar form that writes to a database that works fine, seemingly because it doesn't need a response - firebug says it fails to get a response on that script as well.) The odd thing is that I wrote this on my local server before implementing it on the site and everything worked as planned. I'm using Code Igniter on both the local server and the web server, but I don't know if that has something to do with it. Anyways, any help would be great. I'm marginally new so this is kinda outta my realm at this moment.
Thanks
EDIT: .js
$(document).ready(function() {
$('#submit').click(function(){
var formdata = {
years: $('#years').val(),
rate: $('#rate').val(),
principle: $('#principle').val(),
periods: $('#periods').val(),
continuous: $('#continuous').val()
}
$.ajax({
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
type: 'POST',
data: formdata,
success: function(data){
$('#replace').replaceWith('<p>'+data+'</p>');
}
});
return false;
});
});
php submit function
function submit(){
$years = $this->input->post('years');
$rate = $this->input->post('rate');
$principle = $this->input->post('principle');
$periods = $this->input->post('periods');
$isCont = $this->input->post('continuous');
$params = array(
'years' => $years,
'rate' => $rate,
'principle' => $principle,
'periods' => $periods,
'isCont' => $isCont
);
$this->load->library('timevalue', $params);
return $this->timevalue->FVFactor();
}
Could it be that the request is being made cross-domain? Remember that mydomain.com is considered a different domain to www.mydomain.com.
I ran into a similar situation recently. I requested a page from mydomain.com which made an AJAX request to a script on www.mydomain.com. The request was not made because it was considered cross-domain. It had the same symptoms that you describe. In Firebug and Chrome Developer Console I saw an empty response and no error message.
The problem is that CodeIgniter generates absolute URLs based on the $config['base_url'] setting. If you access the site using a different domain name to what is configured in $config['base_url'] you can run into this type of problem.
This works on the dev and not on the server because you are calling localhost!
// this will have the client call itself on this particular page (wont work)
url: "http://localhost:8888/CodeIgniter_1.7.2/index.php/timevalueshow/submit",
The above code should be just:
// this is relative to the document ROOT, will work on server but not on dev!
// you can set it relative to the calling page using ../ as needed
url: "/index.php/timevalueshow/submit",

Resources