1
votes

I'm getting a json object, parse it's fields and try to set (update) a header field (h1) which is not updated, and I cant understand why ?

The server side looks:

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

app.use(bodyParser.urlencoded({    
  extended: true
})); 


app.get('/', function (req, res) {
   console.log("Got request from: ", req.ip);   
   var clientPage = fs.readFileSync('AjaxSO.html');   
   res.send(clientPage.toString());
})

app.post('/result', function (req, res) {      
   console.log('Got Personal Information: ' + req.body.firstName + " " + req.body.lastName);   
   response = {
       first_name:req.body.firstName,
       last_name:req.body.lastName,
       id:'1234'
   };
   console.log(response);
   res.send(JSON.stringify(response));  
})

var server = app.listen(8081, function () {

  var host = server.address().address
  var port = server.address().port
  console.log("Listening at http://%s:%s", host, port)
})

The client side:

<html>
<head>
    <title> Test AJAX </title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">        
    </script>
</head>
<body>      

     <p>            
        <h1 id="smsId"> Info: <h1>      
     </p>    
     <p>
        <form id="form">        
            <fieldset>
                <legend>Personal information:</legend>
                 First name: 
                <input type="text" name="firstName">
                <br>
                Last name:
                <input type="text" name="lastName">
                <br>
                <button id="button1"> Button </button>
            </fieldset>
        </form> 
     </p>

    <script type="text/javascript">

        $(document).ready(function(){
            $("#button1").click(function(){

                f = $("firstName").val();
                l = $("lastName").val();    

                $.post("/result",
                {
                  firstName: f,
                  lastName: l
                },
                function(data,status){      
                    var obj = jQuery.parseJSON(data);
                    console.log("Data: " + data + "\nStatus: " + status);           
                    console.log("Id:" + obj.id);
                    $('#smsId').text(obj.id);                   
                });
            });
        });     

    </script>

</body>

</html>

The console output is: XHR finished loading: POST "http://127.0.0.1:8081/result".m.ajaxTransport.send @ jquery.js:9664m.extend.ajax @ jquery.js:9215m.each.m.(anonymous function) @ jquery.js:9361(anonymous function) @ ?firstName=&lastName=:35m.event.dispatch @ jquery.js:4670m.event.add.r.handle @ jquery.js:4338 ?firstName=&lastName=:42 Data: {"id":"1234"} Status: success ?firstName=&lastName=:43 Id:1234 Navigated to http://127.0.0.1:8081/?firstName=&lastName=

So as you can see I'm parsing the right value '1234', but for some reason the field is not updated...

Thanks for your help...

1
You have an h1 inside a p tag which could cause strange behaviorTomanow
same result if I remove the p tag ...user3668129
@Fundhor $("smsId") will search for a html element with the tagName smsId (<smsId>) but not for an element with the id smsId (<h1 id="smsId">)t.niese
@user3668129 the p is not a problem in this particular case, but the first thing you should do when you have a problem is to make your html and js code valid. Because an invalid html code can always be the reason for DOM manipulation not to work as expected.t.niese

1 Answers

2
votes

Clicking the button will submit the form, because its default type is submit, you can see this in the last message of your log: Navigated to http://127.0.0.1:8081/?firstName=&lastName=. Depending on the speed of your connection and on the cache configuration the redirect will either happen befor you success callback is called or right after it, but in both situation you won't see that h1 will change because of the redirect.

So you either need to prevent the default behaviour of the button.

$("#button1").click(function(e){
   e.preventDefault();

   //rest of your code
});

Or you need to change the button type to button:

<button id="button1" type="button"> Button </button>