Illep Illep - 5 months ago 8
Javascript Question

Unable to pass values back to HTML page

I am using

EJS
to send some values to my page. Following is the code .

app.post('/ttt', function (req,res){
res.render('index.ejs', {titles: 'CAME IN'})
});


HTML

<form id="mc-form" action="http://local_host:8081/ttt" method="post" enctype="multipart/form-data">
<input type="email" value="" name="dEmail" class="email" id="mc-email" placeholder="type email &amp; hit enter" required="">
<input type="submit" name="subscribe" >
<label >REEEEE <%= titles %></label>
</form>


JS

$("#mc-form").submit(function(e) {
// e.preventDefault(); // Prevents the page from refreshing
var $this = $(this); // `this` refers to the current form element
$.post(
$this.attr("action"), // Gets the URL to sent the post to
$this.serialize(), // Serializes form data in standard format
function(data) { /** code to handle response **/
alert(data);
},
"json" // The format the response should be in
);
});


However, after the user clicks on the submit button the text
CAME IN
is not getting displayed on the form. How can I sort this ?

Answer

Return a json for the ajax not a view

node.js

app.post('/ttt', function (req,res){
   res.setHeader('Content-Type', 'application/json');
   res.send(JSON.stringify({titles: 'CAME IN'}));

}); 

plain.js

$("#mc-form").submit(function(e) {
    e.preventDefault(); // Prevents the page from refreshing
    var $this = $(this); // `this` refers to the current form element
    $.post(
        $this.attr("action"), // Gets the URL to sent the post to
        $this.serialize(), // Serializes form data in standard format
        function(data) { /** code to handle response **/
            $this.find('label').text(data.titles);//append the title to the form
        },
        "json" // The format the response should be in
    );
});