flask upload python-base64 image - javascript

I'm trying to upload a base64 image (encoded in Python) to my webapp using Flask.
I get the encoded image but get an error when modifying the src of the image element.
Ajax:
$.ajax({
dataType: "json",
type: 'POST',
url: getWebAppBackendUrl("return_cam"),
data: {
image_bytes: img_b64
},
success: function (filter_bytes) {
let data = filter_bytes.heatmap
document.getElementById("cam").src = "data:image/png;base64," + data;
}
});
server side:
#app.route('/return_cam', methods=['GET', 'POST'])
def return_cam():
img_b64 = request.form.get("image_bytes") #get POST data
api_result = client.run_function("returnCAM", image=img_b64)
response = api_result.get("response")
result_dict = json.loads(response)
return json.dumps(result_dict)
The 'data' variable looks like this when printed in the console:
b'ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj/ADj...'
and I get ERR_INVALID_URL.
I guess there is some processing to do on this data variable...
Thanks for the help!

Looks like you need to decode that value. Something like:
img_b64 = request.form.get("image_bytes")
img_b64 = img_b64.decode('utf-8')
#...
Not sure if client.run_function will appreciate this, as it's not clear from your question what that method does. Perhaps you could put the above mod within that function if you wrote it yourself, so that the correctly decoded value ends up within response as expected.

Related

jQuery ajax post URL with query string cannot get $_POST in server side

My url parameter need to included the query string due to the system need to pass the token everytime request a link. I would like to use ajax POST to my PHP page.
Below is my ajax code:-
var data = new Array();
data[0] = $('#coupon_code').val();
data[1] = $('#coupon_value').val();
var jsondata = {"data": data}
var json = JSON.stringify(jsondata);
$.ajax({
url:"index.php?route=coupon/create&token=csrf1234567",
cache:false,
processData: false,
type: 'post',
dataType: 'json',
contentType: 'application/json',
data:{json},
success:function(){}
});
However, my PHP script is like below to make sure I have everything passed to server side:
public function create()
{
var_dump($_REQUEST);
}
It only have following output:-
array(2) {
["route"]=>
string(13) "coupon/create"
["token"]=>
string(11) "csrf1234567"
}
Inside the chrome insepct it shows
**Query String Paramaters**
route:coupon/create
token:csrf1234567
**Request Payload**
[object Object]
It does not have POST variable to pass to my PHP. I want to use type POST, and json to accomplish this, any idea how to solve it?
SOLVED:
data:{json},
change to
data:json,
Thanks for the solution!
SOLVED:
data:{json},
change to
data:json,
Thanks for guest271314!

I am having issue with handlebars. Its not compiling the data

I've shifted my server, Handlebar is working fine on my previous server. The same code is not working on my new linux server. Data is not being compile.
My json response is fine its returning data properly. Any guide please!
Code:
var $deferredsLocal = [];
$deferredsLocal[0] = $.ajax({ url: tabUrl, type: "POST"});
$deferredsLocal[1] = $.ajax({url: 'templates/tabs_contact_detail.html', type: "GET", cache: true});
$.when.apply(null, $deferredsLocal).then(function (json, htm) {
var htmls = htm[0];
var template = Handlebars.compile(htmls);
var completeHtml = template(json[0]);
$('#content').empty();
$('#content').html(completeHtml);
$('#content').find('td.question_label').each(function (index, element) {
$(this).html($('<div/>').html($(this).html()).text());
});
$("#preloader").hide();
});
// tabUrl is returning json response
Hi Guys there was json format issue. The data i was getting was looking into json format but it was not in json actually. I just moved the header: header('Content-Type: application/json'); up and placed it in the start of my code.

Json serialization: how to send c# data to javascript script. Error: Invalid character

I'm trying to send data from Entity Framework database to js script on my webpage. This is my MVC Controller:
public ActionResult Index()
{
var wordsToShow = db.Words.Where(w => w.OwnerName == User.Identity.Name); // && DateTime.Compare(w.NextReview, DateTime.Now) <= 0
ViewBag.wordsToShow = HttpUtility.HtmlDecode(new JavaScriptSerializer().Serialize(wordsToShow));
var test = ViewBag.wordsToShow;
return View();
}
And in index.cshtml I've put this code:
<script>
var wordsJson = "#ViewBag.wordsToShow.ToString()";
var wordsAsObject = JSON.parse(wordsJson);
</script>
The problem is, javascript says:
Invalid character
In the line where I'm parsing json to javascript object. The reason is: json string doesn't look like it should. This is part of what's inside "wordsJson" variable in web browser:
What can I do to make it work?
You're going about in an overly roundabout way. JSON is called "JavaScript Object Notation" for a reason. There's no need to put it in a string and re-parse it. You can just use the JSON as JavaScript.
ASP.NET MVC has a helper for serializing values as JSON, so you can just use that and assign it to a variable in your JavaScript:
<script>
var wordsAsObject = #Html.Raw(Json.Encode(ViewBag.wordsToShow));
</script>
This would eliminate the need to do the JSON serialization within your Action.
I suspect that the reason you're encountering this issue is that by default, values inserted into a view with # are automatically HTML encoded. You can use Html.Raw() to prevent this, as I've done above, but as I said, there's no reason to put it into a string first and parse it.
I always create Method that return JsonResult/string
like:
public string GetData()
{
//your logic here
string json_sales = JsonConvert.SerializeObject(<<your data>>);
return json_sales;
}
and in JavaScript I just do AJAX request:
$.ajax({
url: 'PUT_YOUR_URL_HERE_To_METHOD_GetData',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Make: maka.value }),
async: true, // Or false
cache: false,
success: function (data) {
//do something
}
},
error: function (xhr) {
alert('error');
}
})

Using ajax to post json data to a sinatra route and send to a database

I am have some issues learning how JavaScript sends data around my application. Right now what I can't figure out is how to get some JSON data back to my Sintra POST route that creates a new database entry. I'm not really getting any error messages and my application shows the data on the screen but it never writes to the database.
Here is my latest unsuccessful attempt
With some alerts I've been able to determine that the JSON I'm sending looks like this
{"description":"test","created_at":"2014-09-25T10:31:29-04:00","updated_at":"2014-09-25T10:31:29-04:00"}
JavaScript Code
t.saveTask = function(task) {
var t = ko.toJSON(task);
$.ajax({
type: "POST",
url: "/tasks/new",
dataType: 'json',
contentType: "application/json",
data:JSON.stringify(t)
}).done(function(){
alert (t);
});
Sintra Code
post "/tasks/new", :provides => :json do
begin
params = JSON.parse(request.env["rack.input"].read)
#task = Task.new
#task.complete = false
#task.description = params[:description]
#task.created_at = DateTime.now
#task.updated_at = DateTime.now
#task.save
rescue Exception => e
return e.message
end
end
Try to #task.save before rescue, I think it's missing.
Thanks everyone. I think I found a solution and I'm sure part of the problem was the #task.save. But in my efforts to fix the issue, I think I may have caused more issues. Here is my updated code that seems to work. Not sure why when I used ko.toJSON(task) it did not work, but with ko.toJS(task)
JavaScript Code
t.saveTask = function(task) {
var t = ko.toJS(task);
alert (t);
$.ajax({
type: "POST",
url: "/tasks/new",
data: t
}).done(function(){
alert (t);
});
}
Sinatra Code
post "/tasks/new" do
content_type :json
#task = Task.new
#task.complete = false
#task.description = params[:description]
#task.created_at = DateTime.now
#task.updated_at = DateTime.now
#task.save
end

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

Categories

Resources