I'm using flask to get the Predicion from keras model, so i'm using the get_json() to get the image and encoded it in the flask app but im facing bug in the web tells me
Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
the flask app is going to be like:
#app.route('/predict/', methods=['POST', 'GET'])
def predict():
message = request.get_json(force=True)
encoded = message['image']
decoded = base64.b64decode(encoded)
image = Image.open(io.BytesIO(decoded))
processed_image = preprocess_image(image, target_size=(224, 224))
prediction = model.predict(processed_image).tolist()
response = {
'prediction': {
'class-1': prediction[0][0],
'class-2': prediction[0][1]
}
}
return jsonify(response)
and the code in js:
$("#predict-button").click(function (event) {
let message = {
image: base64Image,
};
console.log(message);
$.ajax({
type: "POST",
url: "http://127.0.0.1:5000/predict/",
data: JSON.stringify(message),
success: function (response) {
$("#class-1").text(response.prediction[0][0].toFixed(6));
$("#class-2").text(response.prediction[0][1].toFixed(6));
console.log(response);
},
});
});
Related
View.py
def export(request):
if request.is_ajax():
ourid = request.GET.getlist("terid")
Case_Detail = Case_Info_Resource()
for i in ourid:
print(i)
queryset = Case_Info.objects.filter(id=i)
dataset = Case_Detail.export(queryset)
response = HttpResponse(
dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
print("breakpoint")
return response
Ajax Script
<script>
$(document).ready(function () {
$('#Download').click(function () {
var list = [];
$("input:checkbox[name='checkbox']:checked").each(function () {
list.push($(this).val());
});
$.ajax({
url: '/Account_Manager/Download/',
type: 'GET',
data: { 'terid': list },
traditional: true,
dataType: 'html',
success: function () {
alert("The best cricketers are: " + list.join(", "));
}
});
});
});
</script>
Error:
The view Apps.views.export didn't return an HttpResponse object. It returned None instead.
So, Ajax wants us to return the value in HttpResponse but I need to pass the response normally in order to download the excel which I am creating. I think I checked all the possible answers and struggling with it from the last 3 days. Thank you in advance for any help, suggestions, or edit.
I am running a python REST server, using Flask, to create a website. On the website, I have a number of buttons that call various 3rd party APIs, using AJAX, and get the information back.
The APIs work, and I can get the information back (confirmed that it is accurate using console.log). However, I can't figure out how, or where to pass the information from the AJAX to the server, so that I can process it.
My HTML/JS code is:
<script>
function Enquiry() {
var selection = document.getElementById("Selection").value
// Get values for API
var n = selection.indexOf(" ");
var symbol = selection.substring(0,n)
var API_URL = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=" + symbol + "&apikey=XXX"
// AJAX to API
$.ajax({
url: API_URL,
method: "GET",
data: "",
dataType: "JSON",
success: function(result){
console.log(result)
},
error: function(xhr,status,error){
console.log("error: "+status+" msg:"+error);
}
});
}
</script>
And my Flask script is:
#app.route("/")
def home():
return render_template(Stocks.html)
#app.route("/Stocks")
def getAll():
results = stocksDAO.getAll()
return jsonify(results)
#app.route("/Stocks/<int:id>")
def getById(id):
sel_stock = stocksDAO.findById(id)
return jsonify(sel_stock)
#app.route("/Stocks", methods=["POST"])
def create():
if not request.json:
abort(400)
stock = {
"Stock": request.json["Stock"],
"Name": request.json["Name"],
"Price": request.json["Price"],
}
values = (stock["Stock"], stock["Name"], stock["Price"])
newId = stocksDAO.create(values)
stock["ID"] = newId
return jsonify(stock)
I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.
I am trying to get a pdf of a div in my view.
I am doing the following:
I get the element, uri encode its html, then pass it to a method via ajax:
AJAX:
function getPDF(html) {
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) }
}).done(function (result) {
window.open("data:application/pdf; " + result);
$("#printArea").html(result);
}).fail(function (data) {
alert("Failed");
});
}
Method:
[HttpPost]
public void printPage(string html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
//var base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
Response.BinaryWrite(mem.ToArray());
//return File(mem, System.Net.Mime.MediaTypeNames.Application.Octet);
}
In the end I get a popup to open a pdf but it won't open, according to adobe acrobat it is corrupt.
I tried sending the html as a perameter to the method, but the perameter is too long
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
What would be a good way of doing this.
public JsonResult printPage(String html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
mem.Flush();
mem.Position = 0;
String b64Converted = Convert.ToBase64String(mem.ToArray());
return Json(b64Converted, JsonRequestBehavior.AllowGet );
System.Net.Mime.MediaTypeNames.Application.Octet);
}
Then in the view:
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) },
}).done(function (result) {
$("#printArea").append('PDF');
}).fail(function (data) {
alert("Failed");
});
Apparently its very easy
Just base64 the pdf and send it over at the json response.
This question already has answers here:
How to append whole set of model to formdata and obtain it in MVC
(4 answers)
Closed 6 years ago.
When passing uploaded file through ajax to asp.net MVC controller, file property is showing null value in controller.
image file object taken by document.getElementById('fileUpload').files[0] action and convert to JSON.stringify(fileName) but when pass that object to asp.net mvc controller
it is showing null value in mvc controller.
please if any one know how to pass that file to ajax to mvc controller, please post your answer
Admin controller
[HttpPost]
public string AddRetailer(HttpPostedFileBase file, string storeName, string storeUrl, string ecommercePlatform)
{
try {
Bswayed.Admin.Retailer retailer = new Bswayed.Admin.Retailer();
return JsonConvert.SerializeObject(data);
} catch (Exception ex) {
throw ex;
}
}
Asp.net upload form
<input type="file" id="fileUpload" name="fileUpload" onchange="this.parentNode.nextSibling.value = this.value"/>Browse
<input class="input-lg"
#Html.TextBoxFor(Model => Model.StoreLogo, new { placeholder=#ViewBag.StoreLogo})
Java script(Ajax)
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload').files[0]
$.ajax({
url: $("#addRetailer").val(),
cache: false,
type: "POST",
data: {
file:JSON.stringify(fileName),
storeName: storeName,
storeUrl: storeUrl,
ecommercePlatform: ecommercePlatform
},
dataType: "json",
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}
}
You don't need to stringfy uploaded image path. Below code is working in my application. I just used FormData() to get all form. After that added all items in form that i want to send to controller. In this case, you don't need to pass parameter in controller. You can get by Request.Files for image & Request.Form for extra data. I hope, It may helps you. If there is any wrong, then share with me, i will sort it out.
Java Script -
function AddRetailer()
{
try {
var storeName = $("#StoreName").val();
var storeUrl = $("#StoreURL").val();
var retailerLogoPath = $("#StoreLogo").val();
var ecommercePlatform = $("#EcommercePlatform").val();
var fileName = document.getElementById('fileUpload')..get(0).files;
var data = new FormData();
if (fileName.length > 0) {
data.append("userUploadedImage", fileName[0]);
data.append("storeName", storeName);
data.append("storeUrl", storeUrl);
data.append("ecommercePlatform", ecommercePlatform);
}
$.ajax({
url: $("#addRetailer").val(),
processData: false,
contentType: false,
type: "POST",
data: data,
success: function (data) {
},
error: function (resp) {
alert(resp);
}
});
}
catch (e) {
}}
Controller -
[HttpPost]
public string AddRetailer()
{
HttpPostedFileBase image = Request.Files["userUploadedImage"];
string storeName = Request.Form["storeName"];
string storeUrl = Request.Form["storeUrl"];
string ecommercePlatform = Request.Form["ecommercePlatform"];
}