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

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.

Related

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.

Single Cross Domain AJAX Request needed

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.

jQuery AJAX request error status 0

I've been developing an application locally and am running into trouble on the actual server.
Whenever I submit an AJAX request with jQuery it gives me an error with error status:0 and and statusText: 'error'.
The Chrome inspector doesn't even show a response code for the request, it just says failed.
When I inspect it closer, I notice that all of the data was sent and the PHP file actually processed it. For example, in the request below, the user was indeed created. The bad response code is preventing other requests from executing (since they depend on a 'successful' response).
Here is a sample request:
var cct = $.cookie('ttc_csrf_cookie'); // csrf protection
var sUrl = "<?= base_url(); ?>user/create/";
var serialized = {
name: me.name,
email: me.email,
oauth_provider: 'facebook',
oauth_uid: me.id,
ttc_csrf_token: cct
};
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
error: function(someStuffHere) {
//* THIS CODE RUNS. SHOWS ERROR STATUS: 0 */
},
success: function(user_id) {
//******** THIS HERE NEVER RUNS ***********///
}
});
And here is the corresponding PHP code:
public function create() {
if($this->input->post()) {
$user['name'] = $this->input->post('name');
$user['email'] = $this->input->post('email');
$user['oauth_provider'] = $this->input->post('oauth_provider');
$user['oauth_uid'] = $this->input->post('oauth_uid');
$user['last_activity'] = date('Y-m-d H:i:s');
$user_id = $this->Users->create_user($user);
$this->session->set_userdata('user_id', $user_id);
echo $user_id;
}
}
These two snippets are only an example. All AJAX requests won't work on the live sever.
What could it possibly be? Thanks!
UPDATE: I've narrowed it down and the issue occurs when echo'ing a result. When I comment out the echo, no error is thrown (but, of course, no result is sent).
Turns out that the issue was caused by the compress_output option in CodeIgniter. When it's set to true, the echo's don't work. Thanks for everyone that tried to help!

sencha touch - ajax call to server (url , extra parameter formation)

I am using this to get the result from server
controller.allVisitStore = new Ext.data.Store({
model: 'allVisit',
autoLoad : true,
proxy: {
type: 'ajax',
id: 'allvisit_app_localstore',
url: '/RadMobApp/api',
extraParams:{
action:'query',
queryName:'GET_ALL_VISIT',
authToken: localStorage.getItem("auth_token"),
patTicketId: localStorage.getItem("patientId"),
retFormat:'XML',
keyValuePair:'yes'
},
// the return will be XML, so lets set up a reader
reader: new Ext.data.XmlReader({
// records will have an "T4" tag
record: 'data'
})
}
});
but i am not getting any thing.But i formed this url in browser and checked this i got the correct result. now here i want to check is there any problem in the url formation.How to check the url formation with extra parameter which is pass through ajax. I have checked in Inspect element-> network -> api there is no any api request found there.Is anything wrong in my code. Thanks in advance...
Use Firebug for Firefox or Chrome's developer tools to see what's going on when that store attempts to load itself. My hunch is that your url is incorrect and should be url: '/api' because RadMobApp is probably your app root.

Django Posts Not Working:

I am using Django 1.2.3 to develop a site. My ajax get requests work fine but the post requests work in development mode (127.0.0.1:8000) but not when I push the site into production using apache + nginx.
Here is an example
urls.py:
(r'api/newdoc/$', 'mysite.documents.views.newdoc'),
views.py
def newdoc(request):
# only process POST request
if request.is_ajax():
data= dict(request.POST)
# save data to db
return HttpResponse(simplejson.dumps([True]))
in javascript:
$.post("/api/newdoc/", {data : mydata}, function(data) { alert(data);}, "json");
my alert is never called .... this is a problem because i want to sanitize this data via a django form and the post requests do not seem to making it to the server (in production only).
what am i doing wrong?
UPDATES:
solution: crsf tokens need to be pushed ajax post requests (not gets) as of django 1.3
also, per the link provide below, the following javascript
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$("#csrfmiddlewaretoken").val());
}
}
});
needs to be changed as follows:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken",
$('input[name="csrfmiddlewaretoken"]').val());
}
}
});
the way the csrf token gets rendered in the form must have changed between 1.25 - 1.3??
regardless, it works. thanks for all your help everyone
Can you directly access your javascript files from the production server? Which Django version are you using in production? If you are using 1.2.5+ in production, you will need to push the csrf token to the server during an AJAX post operation.
See the release notes in 1.2.5 and CSRF
To check your Django version:
import django
django.get_version()
Print the above in your production site or from the shell in your production server while making sure you are using the proper Python path.
Your code appears fine with a cursory glance, but I'll show you an example of my ajax form processing code in a hope it'll help with figuring out the error that's occurring. Though, what #dmitry commented should be your first debugging step - use firebug or the inspector to see if the ajax call returns an error.
// js (jQuery 1.5)
$(form).submit(function(event) {
event.preventDefault();
$.post(post_url, $(form).serialize())
.success(function(data, status, jqxhr) {
if (data.success) { // form was valid
$(form)
// other irrelevant code
.siblings('span')
.removeClass('error')
.html('Form Successful');
} else { // form was invalid
$(form).siblings('span').addClass('error').html('Error Occurred');
}
})
.error(function(jqxhr, status, error) { // server error
$(form).siblings('span').addClass('error').html("Error: " + error);
});
});
// django
class AjaxFormView(FormView):
def ajax_response(self, context, success=True):
html = render_to_string(self.template_name, context)
response = simplejson.dumps({'success': success, 'html': html})
return HttpResponse(response, content_type="application/json", mimetype='application/json')
// view deriving from AjaxFormView
def form_valid(self, form):
registration = form.save()
if self.request.is_ajax():
context = {'competition': registration.competition }
return self.ajax_response(context, success=True)
return HttpResponseRedirect(registration.competition.get_absolute_url())
def form_invalid(self, form):
if self.request.is_ajax():
context = { 'errors': 'Error Occurred'}
return self.ajax_response(context, success=False)
return render_to_response(self.template_name, {'errors':form.errors})
Actually, comparing the above to your code, you may need to set the content_type in your django view so that jQuery can understand and process the response. Note that the above is using django 1.3 class-based views, but the logic should be familiar regardless. I use context.success to signal if the form processing passed or failed - since a valid response (json) of any kind will signal the jQuery.post that the request was successful.

Resources