0

failing to render an image returned by ajax post in json format.

How do I render the image which is posted by ajax to the GAE request handler?

$(document).ready(function() {
    $("button").click(function(){
        var data = {'imageSrc' : $(this).parent().find('img').attr('src')};
        console.log(data);
        var request = $.ajax({
            cache: false,
            url: "/i",
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data, status) {
                console.log(data, status);
            },
        });

        request.done(function(msg) {
            window.location = '/i'
            alert("Request succeeded: " + msg );
        });

        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    });
});

GAE

def post(self):
    self.response.headers['Content-Type'] = 'application/json'
    self.response.content_type = 'application/json'
    # imageSrc = self.request.POST['imageSrc']
    # logging.info("DoubleNumbers called for:" + imageSrc)
    # jsonData = {"img" : imageSrc}
    # logging.info(jsonData)
    # js = json.dumps(jsonData)
    # self.response.write(simplejson.dumps(jsonData['img']))
    self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
    # self.response.write(js)
    # self.response.write('''<img src="''')
    # self.response.write(json.JSONEncoder(jsonData['img']))
    # self.response.write('''">''')
    t = json.loads(self.request.POST['imageSrc'])
    self.response.write('''<html><body><img src="''')
    self.response.write(t['imageSrc'])
    self.response.write('''"></body></html>''')

UPDATE I'm getting the img src as JSON data But still failing to output/render it. I changed my JS script to:

$(document).ready(function() {
    $("button").click(function(){
        var data = {'imageSrc' : $(this).parent().find('img').attr('src')};

        var request = $.ajax({
            cache: false,
            url: "/i",
            type: "POST",
            data: JSON.stringify(data),
            dataType: "json",
        }).done(function(data){
                    console.log(data);
                });
    });
});

& my main.py file as:

def post(self):
    self.response.headers['Content-Type'] = 'application/json'
    data = json.loads(self.request.body)
    z = data['imageSrc']
    logging.info(z)
    logging.info(data)
    self.response.write(json.dumps(data))
    self.response.write('''<html><body><img src="http://mysite:8080%s"></body></html>'''%z)

How do I render the returned JSON data (img src file)?

Simon K Bhatta4ya
  • 977
  • 2
  • 12
  • 24

2 Answers2

1

replace:

data: JSON.stringify(data),

with:

data: data,

and to get imageSrc in the server:

imageSrc = self.request.get('imageSrc')

UPDATE: Redirecting to GET page

JS

// Add GET parameters to an URL
// Ex.:  site.com/?param=value
function addUrlSep( url ) {
    var sep = (url.indexOf('?') > -1) ? '&' : '?';
    return url + sep; }
function buildUrl( base, key, value ) {
    url = addUrlSep( base );
    return url + key + '=' + value; }

$(document).ready(function() {
    $("button").click( function(){

        base_url = "/i";

        url = buildUrl( base_url, 'imageSrc', 'https://www.google.com.br/images/srpr/logo6w.png' );

        window.location = url;  // Redirects to the URL

    });
});

PY

def get(self):
    z = self.request.get( 'imageSrc' )
    logging.info(z)
    self.response.write( "<!DOCTYPE html><html><body><img src='{}'></body></html>" .format( z ) )

def post(self):
    pass
kelvinss
  • 465
  • 2
  • 12
  • no, still i can't render the image, I changed my .py file `self.response.write('''''')` I got error as KeyError: "No key 'imageSrc': Not an HTML form submission (Content-Type: application/json)" – Simon K Bhatta4ya Oct 08 '13 at 15:21
  • Try: imageSrc = self.request.get('imgSrc') – kelvinss Oct 08 '13 at 15:56
  • http post request status is 200 but I get `parseerror` & the image is not rendered. – Simon K Bhatta4ya Oct 08 '13 at 16:00
  • Where are you getting 'parseerror'? Can you post the response you are getting from the server, using a random URL ? – kelvinss Oct 08 '13 at 21:48
  • if I use JSON in my `.py` script as `def post(self): self.response.headers['Content-Type'] = 'application/json' data = json.loads(self.request.body) z = data['imageSrc'] self.response.write(json.dumps(response))` I get error as `ValueError: No JSON object could be decoded` for **data** attribute – Simon K Bhatta4ya Oct 09 '13 at 06:47
  • I'm getting the value send from ajax post in the server `main.py` file I have updated the code above the `logging.info(data)` shows the data as `{u'imageSrc': u'img/allofthethings.png'}`, but the Only issue is I can't render it, so currently I'm checking 4 some alternatives & looking into this http://stackoverflow.com/q/4315900/2541442 If you can suggest some options, would be gr8. – Simon K Bhatta4ya Oct 09 '13 at 10:47
  • You just want to show the image? You are using ``, that include the tags. To render this, you'll need to write the response inside an iframe, or replace the entire document. Try `document.open("text/html"); document.write( data ); document.close();`, in your 'done' function. – kelvinss Oct 09 '13 at 11:16
  • And why the `self.response.write(json.dumps(data))` line ? – kelvinss Oct 09 '13 at 11:17
  • `self.response.write(json.dumps(data))` for debugging nothing specific, & how do I use the above code in my response function? would it be something like this: `.done(function(data){ var url = "/i"; var txt=" "; window.location.href = url; document.open("text/html"); document.write( txt ); document.close(); });` I tried the above code but didn't work. – Simon K Bhatta4ya Oct 09 '13 at 11:35
  • Also I'd like to add that I'm looking to render the response (the image) on another URL. say from http://mysite.com/image to http://mysite.com/selectedimage after the ajax post. – Simon K Bhatta4ya Oct 09 '13 at 11:39
  • On the server, remove `self.response.write(json.dumps(data))`, and send only the URL: `self.response.write(z)`. On JS, `.done(function(data){ var txt = " "; document.open("text/html"); document.write( txt ); document.close(); });`. Instead of using an URL like, `img/allofthethings.png`, use `/img/allofthethings.png` with a bar. – kelvinss Oct 09 '13 at 11:45
  • hmm, I changed the code as you mentioned but he document at URL `/i` still shows as blank.. the header response status is 200 & response shown is `img/interesting.jpg` missing the `HTML Doctype` any ideas. I've upload the [code here](http://pastebin.com/MsQHKdwa) if you would like to take a close look. Thanks in advance. – Simon K Bhatta4ya Oct 09 '13 at 12:17
  • When you click the button the page goes blank ? Try to view the source code of the blank page. – kelvinss Oct 09 '13 at 13:18
  • checked the src its blank. – Simon K Bhatta4ya Oct 09 '13 at 13:20
  • wow.. one last thing, I tried the code & the ajax post the data & updates the current page itself, is there a way I can update a different page, say from current URL is `http://mysite.com/i.html` & render the image on `http://mysite.com/xyz.html`? – Simon K Bhatta4ya Oct 09 '13 at 14:52
  • You can use GET instead of POST method on `/xyz.html`, and redirect to it. Or use a [hidden form](http://stackoverflow.com/questions/8389646/send-post-data-on-redirect-with-javascript-jquery). – kelvinss Oct 09 '13 at 15:00
  • ok, so do I use the GET in `.py` or the `.js` by changing ajax POST to GET & then use the `.html()` with a redirect. – Simon K Bhatta4ya Oct 09 '13 at 15:32
  • `self.request.body` doesn't worked with the get function here. So, I made some changes. – kelvinss Oct 09 '13 at 23:03
  • Thanks a lot for your efforts, I nearly went bald pulling my hair off searching for options to get this silly task done, Thanks. Up voting for sure :) – Simon K Bhatta4ya Oct 10 '13 at 11:53
0

In your Javascript, you need something like:

request.done(function(msg) {
        window.body = msg;
        alert("Request succeeded: " + msg );
});

I can tell this is just an exercise, but what you're doing here doesn't make much sense. You're not actually sending the image to the server, you're just sending the url to the server, getting it back, and then having the browser load the url.

dragonx
  • 14,752
  • 24
  • 41
  • hmm, ok, yeap I might be just sending the URL, I updated js with `window.body = msg;` it didn't work either, any ideas? & how can I send the image instead of URL if that what's happening? – Simon K Bhatta4ya Oct 08 '13 at 16:07