PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How can I implement the Ajax error function?

 September 08, 2022     ajax     No comments   

Issue

This is my app.py code:

@app.route('/index', methods=['GET', 'POST'])
def test_post():
    theName=request.form['name']
    theAge=request.form['age']
    if theName and theAge:
        return jsonify({'output':'Your name is '+theName+' , and your age is '+theAge+' , right?'})
    return jsonify({'error': 'Missing Data!'}) 

This is my index.html code about Ajax:

<script>
    $(document).ready(function () {
        $('#form').on('submit', function (e) {
            $.ajax({
                data: {
                    name: $('#name').val(),
                    age: $('#age').val(),
                },
                type: 'POST',
                url: '/index'
            })
                .done(function (data) {
                    $('#output').text(data.output).show();
                });
            e.preventDefault();
        });
    });
</script>

I want to know, if the entered name and age are empty, how can the returned 'Missing Data!' on the page. Thanks for your help very much!


Solution

You just have to paste this in your .data function,

.done(function(data){

 if(data.error == "Missing Data!"){
          alert("Missing Data");
     }else{
          $("#output").text(data.output);
     }

Hope this works fine for you



Answered By - Ali Usman
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing