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...
h1
inside ap
tag which could cause strange behavior – Tomanow$("smsId")
will search for a html element with the tagNamesmsId
(<smsId>
) but not for an element with theid
smsId
(<h1 id="smsId">
) – t.niesep
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