0

I have an app with a form. I put all the info retrieved from the form in an object and then call JSON.stringify on it so that it becomes a json object. Then I post it with an ajax call and my flask app gets it sucessfully when I set a variable equal to request.json. So far so good. BUT I can no longer render an html page or send flash messages (which I can replace by javascript code I know). So when I hit submit on my form, I cannot send the user to the next page. I'm always getting the same EM:Blocked loading mixed active content:‘http://ide50-oyz1.cs50.io:8080/createWord’.[more info] And then I can go to an MDN page that gives me detailed and difficult info about security. (https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content) So, it is not a bug, it is a feature. I tried to add dataType: 'html' to the ajax call but that didn't work either. Then I tried posting the json object to another endpoint but now the page with my html form no longer responds to anything. Of course not, there's no event triggering a response. Is there a way of making one endpoint talk to the other ? What am I to do? That json object comes in really handy. I do not want to give it up. I tried to jsonify an object on the flask backend but that did not produce an object I could work with. In the network page of my dev tools I see a 302 code and cause : 'xhr' next to posting my html page. I also tried to work with two ajax calls and it works. No EM, two sucessful responsese. (In the html I post data to the endpoint that receives the json object (processWord)).But I still can't send users to another page or redirect them to the same page. Yes, this is probably caused by event.preventDefault() but if I don't use that I cannot post a json object. It is driving me crazy. When I do not use a json object I have no problem whatsoever. Have I hit flask limits or is there a solution to this ?

Here's the simplified object and code:

```

JS file:
forminfo= {word: 'meisje', opposite: ['man', 'meisje'], image:      
               'image.png'} 

sendFormData = JSON.stringify(forminfo);
$('#formulier').on('submit', function(event) {
    $.ajax('createWord',{
    url : "/createWord",
    type: 'POST',
    data: forminfo,
    success: function(response) {
         console.log('heel erg prima');
    },
    error: function(error) {
        console.log(error);
    }
});

$.ajax('createWord',{
    url : "/createWord",
    type: 'POST',
    contentType:'application/json',
    data: sendFormData,
    success: function(response) {
         console.log('prima');
    },
    error: function(error) {
         console.log(error);
    }
});
event.preventDefault();

flask app:
@app.route('/createWord', methods=['GET','POST'])
def createWord():

    if request.method == "POST":
        formulier = request.json
        newWord = formulier["word"]
        # tell user that a word is required
        if len(newWord) < 1:
            flash("You have to enter a new word before you hit submit")
            return redirect(url_for("createWord"))

        return render_template("showWord.html")
    return render_template("createWord.html")  

html file
{% extends d"wordIndex.html" %}

{% block head %}
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" 
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="  
   crossorigin="anonymous"></script>
  <script src="{{url_for('static', filename='woord.js')}}"></script>
{% endblock %}

{% block main %}
    <form id="formulier" action="{{url_for('processWord')}}" method="POST"
       enctype=multipart/form-data>
        <div>
            <label for="idWord">Enter a word</label>
            <input id="idWord" name="word" type="text">
        </div>
        <br>
        <div class="containeropposite">
            <label>Opposite:
                    <input class="opposite relationship"  
                         name="opposite" type="text">
            </label>
        </div>
        <br>            
         <div>
            <label for="idImage">Image:</label>
            <input id="idImage" name="image" type="file">
        </div>
        <br>
        <div>
            <button id='formSubmit' type="Submit">Submit</button>
        </div>
    </form>
{% endblock %}

```

0

I am using two consecutive ajax calls to two different endpoints. (For different but connected reasons, I have decided to create two forms. I trigger the second submit event inside the first ajax call when it is successful. The first submit posts a json object and the second submit simply posts one of the forms (using jquery trigger() so that I can access it with request.form and request.files(for images). The user is unaware and sees only one button. I've replaced the success and error keys of the request by a promise with done and fail callbacks. I found an easy example in an article that states it makes it easier to create conditional callbacks. (https://blog.revathskumar.com/2016/06/why-i-prefer-ajax-promise.html). Frankly, I don't really know why but it seems to work better. I use session to access the json values posted to one endpoint in the other endpoint and that works very well.

javascript:

$('#jsonSubmit').on('submit', function(event) { $.ajax({ url : "/processWord", type: 'POST', contentType:'application/json', data: sendFormData }).done(function(response) { $('#formulier').trigger('submit') }).fail(function(xhr) { console.log('error', xhr); } }); event.preventDefault(); }); });

application.py:

```

import session

@app.route('/processWord', methods=['POST'])
def processWord():
     formulier = request.json
     session['formulier'] = formulier


@app.route('/createWord', methods=['GET','POST'])
def createWord():

     formulier = session.get('formulier', None)

I do hope I am making some sense. It is very difficult to describe the situation in a few words.

1
  • Actually , the problem is still not completely solved. I have no idea what to do. Working on cloud9 I don't understand what's going on underneath the cover. I can see "HTTPS://ide50-blabla" as the url in my browser. I don't see why this EM crops up. It says: Laden van gemengde actieve inhoud ‘HTTP://idea50blabla" geblokkeerd[Meer info]. HTTP and not HTTPS, where does that come from? I really don't see it. I see the EM when the session is empty. When it has been filled with data, it disappears. I really don't understand this. – Karin May 17 '18 at 17:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .