Fineuploader possible solution to force header return true if default server will not return following JSON Data - fine-uploader

Not sure if it's possible to force fineuploader to fire true success upload in anyway. im facing the issue of submitting form to a url "http://119.29.222.368:8991/upload"(sample ip due to P&C) where it will return only Status : "OK" without Success : true.
Following is my code, pretty sure that it successfully submitted, but my UI will get error due to the API is not returning the value success.
var uploader = new qq.FineUploader({
element: document.getElementById("uploader"),
cors: {
allowXdr: 'true',
expected:'true'
},
request: {
method:'POST',
// endpoint: '/upload',
endpoint: 'http://119.29.222.368:8991/upload',
forceMultipart:'true',
inputName:'filename',
params: {
'token': <%- JSON.stringify(token) %>,
'path':"/images/feed/"
}
}
})

This was originally requested in github.com/FineUploader/fine-uploader/issues/1325. Follow the linked pull request at the end of that issue for updates. – Ray Nicholus 20 hours ago

Related

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.

fineUploader Failed in the Request To endpoint and the cause in onError Callback is UnKnown Reason

kindly i have to pages using fineUploader ,
the first page is working correctly but the second isn't : the response in debugging browser console is:
My Html Body will be existing here.
Simple upload request failed for 0
[Fine Uploader 5.11.8] Error when attempting to parse xhr response
text (Unexpected token < in JSON at position 0)
for the point one :(the request didn't reach the endpoint because i made a tester in the endpoint page if any script accessed it)
so the request in the first page is working and the same request with the same path in endpoint property isn't working in the second
i read many articles with the same error but all of them were not identifying correct endpoint path , which i did correctly and tested in the first Page.
var uploader = new qq.FineUploader({
debug: true,
element: document.getElementById('my-uploader'),
request: {
endpoint: "http://localhost/fineuploader/endpoint.php",
// endpoint: "http://localhost/fineuploader/endpoint.php",//commented to prove that i used //both of the relative and absolute paths
},
chunking: {
enabled: true,
concurrent: {
enabled: true
},
success: {
endpoint: "http://localhost/fineuploader/endpoint.php?done",
}
},
deleteFile: {
enabled: true,
endpoint: "http://localhost/fineuploader/endpoint.php"
},
retry: {
enableAuto: true,
showButton: true
},
form:{element:"FormId", },
callbacks: {
onError: function(id, name, errorReason, xhrOrXdr) {
alert(qq.format("Error on file number {} - {}. Reason: {}", id, name, errorReason));
},
});
The Answer of Mr Ray Nicholus Here was useful but i want to provide the solution in my case and my mistake, my problem was that in the first page i didn't provide action attribute in form tag and in the second i did , so when i provided in the second page the action of the form a different value than what is specified in
<form id="test" action="form.php">
request: {
endpoint: "http://localhost/fineuploader/endpoint.php",},
the requests were going to the action attribute value path(form.php) not for the above request value (endpoint.php).
It's really very simple, and there is no other answer to this question: either your endpoint is incorrect (and of course the response will be invalid too) or your endpoint is correct but your endpoint is not returning valid JSON. You'll need to look at the response closely to determine the issue.
In your case, your endpoint is returning HTML, not JSON. You'll have to fix this on your server.

Ext Data Session and bad server response ("[W] Ignoring server record: ...")

Our application handles and manages records changes on the client side. We use ExtJS5 Data Session mechanism.
A session tracks records that need to be updated, created or destroyed
on the server. It can also order these operations to ensure that newly
created records properly reference other newly created records by
their new, server-assigned id.
Let me introduce short use case.
User opens and fills a form. Behind the scene fields are binded to entity object which is tracked by session. When user clicks Submit then session is synchronized, i.e. Ext sends requests to the server and parse response. Here I've encountered a problem.
Server returns following object but Ext does not recognize it:
[{"success": false, errorMessage: "error"}]
Ext prints warning:
[W] Ignoring server record: {"success":false}
or
[W] Ignoring server record: {"success":true}
My question is how should look server response in order to indicate that record is not accepted/saved by backend?
The source code where above warning is printed: http://docs-origin.sencha.com/extjs/5.0/apidocs/source/Operation.html (in function doProcess)
Below I put snippet how I'm starting a batch operation (sync session):
var session = this.getViewModel().getSession(),
saveBatch = session.getSaveBatch();
saveBatch.on('complete', function (batch, operation, eOpts) {
// whole batch processing has been completed
/*...*/
});
saveBatch.on('exception', function (batch, operation, eOpts) {
// exception has been occurred (possible for each operation) (such as HTTP 500)
/*...*/
});
saveBatch.on('operationcomplete', function (batch, operation, eOpts) {
// single operation has been completed
// now, every operation is marked as successful
/*...*/
});
saveBatch.start();
update 26.09.2014
Sencha developer has suggested including an id of object in the response. so I've modified server response to:
[{"id": 10, "success": false}]
but this does not solve the problem.
I spend some time on debugging Ext.data.operation.Operation.doProcess method and I analyzed a sample code from sencha support. Ultimately I've found the solution.
There is my proxy config:
proxy: {
type: 'rest',
// ...
reader: {
type: 'json',
rootProperty: 'data',
totalProperty: 'totalCount',
successProperty: 'success',
messageProperty: 'errorMessage'
}
}
Server response when some error occured:
{
"success": false,
"errorMessage": "<error message>"
}
Server response when data was successfully saved:
The minimal form for delete or update record without changing data:
{
"success": true,
}
The extended form for creating or updating record with changing record data:
{
"success": true,
"data": [{
clientId: 5, // clientIdProperty
id: 5,
// [optional] fields to change, e.g.:
name: 'new name'
}]
}
I modified a demo which I have from sencha support:
https://fiddle.sencha.com/#fiddle/bem
in proxy config use data2.json for error and data3.json for success response.

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