skip to Main Content

I’m using Node.js as server-side with express and ejs with Twitter Bootstrap as front-end. The page has a modal with a form and 2 submit buttons. I want to display different messages depending on what button was used to submit with ajax (later I will add other handlings but for now I just want to display messages). My problem is that I can’t get the value of the submitted button.

index.ejs

<!DOCTYPE html>
<html lang="fr">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>test</title>

    <link href="/css/style.css" rel="stylesheet">

    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </head>

    <body>
        <button type="button" class="btn btn-lg btn-primary" 
        data-toggle="modal" data-target="#modalCreateMdl">Click here</button>


        <div id="modalCreateMdl" class="modal fade" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Form</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" id="formTest" action="test" method="post">
                                <div class="form-group">
                                    <div class="col-sm-offset-2 col-sm-10">
                                        <button type="submit" name="sub" class="btn btn-primary" value="submit1">SUBMIT 1</button>
                                    </div>
                                    <div class="col-sm-offset-2 col-sm-10">
                                        <button type="submit" name="sub" class="btn btn-primary" value="submit2">SUBMIT 2</button>
                                    </div>
                                </div>
                                <div id="msgTest" style="display:none"></div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>

        <script src="/js/ajax.js"></script>
    </body>
</html>

test.js

var express = require('express');
var bodyParser = require('body-parser')

var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("/home/mainuser/test_node/"));

app.post('/test', function(req, res) {
    console.log(req.body.sub);
    if(req.body.sub == "submit1") {
        obj = {test : "json1"};
        console.log("submit number 1");
    } else if(req.body.sub == "submit2") {
        obj = {test : "json2"};
        console.log("submit number 2");
    } else {
        obj = {test : "json_default"};
        console.log("default");
    }
    res.json(obj);
});

app.get('/', function(req, res) {
    res.render('index.ejs');
});

app.listen(8080);

ajax.js

$(document).ready(function() {
    $('#formTest').submit(function() {
        $.ajax({
            method : $(this).attr('method'),
            url : $(this).attr('action'),
            data : $(this).serialize(),
            success : onSuccessLoad,
            error : onError
        });
        return false;
    });
});
// ready

function onSuccessLoad(json) {
    $('#msgTest').fadeOut('slow');
    $('#msgTest').html(json.test);
    $('#msgTest').fadeIn('slow');
}

function onError(returnation) {
    alert("problem");
}

When I click on SUBMIT 1 button, I get the following output in the terminal :

undefined
default

and json_default is displayed on the page.

when it should be this in the terminal :

submit1
submit number 1

and json1 on the page.

When I remove ajax.js the console output is fine but obviously the json is displayed in a new page which is not what I want.

2

Answers


  1. ‘$(this).serialize()’ return ‘string’, not ‘object’

    Login or Signup to reply.
  2. <button type="button" class="btn btn-lg btn-primary"
                        data-toggle="modal" data-target="#modalCreateMdl">Click here</button>
    
    
        <div id="modalCreateMdl" class="modal fade" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Form</h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" id="formTest" action="test" method="post">
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <input type="text" name="sub" class="btn btn-primary" value="submit1">
                                </div>
                                <div class="col-sm-offset-2 col-sm-10">
                                    <input type="text" name="sub" class="btn btn-primary" value="submit2">
                                </div>
                            </div>
                            <div id="msgTest" style="display:none"></div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
     <script>
         $('input[name="sub"]').on('click',function() {
             var serializeStr = $('#formTest').serialize();
             var serializeArray = serializeStr.split('&');
             var params = {};
             for(var i=0;i<serializeArray.length;i++){
                var value = serializeArray[i].split('=');
                 params[value[0]] = value[1];
             }
             $.ajax({
                 method : $('#formTest').attr('method'),
                 url : $('#formTest').attr('action'),
                 data : params,
                 success : onSuccessLoad,
                 error : onError
             });
             return false;
         });
         function onSuccessLoad(json) {
             $('#msgTest').fadeOut('slow');
             $('#msgTest').html(json.test);
             $('#msgTest').fadeIn('slow');
         }
    
         function onError(returnation) {
             alert("problem");
         }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search