I have a front-end where I track what element has been clicked and send it back to the server to do some work on the backend depending on what that element is. The code is setup like so...
$('body').on('click', function(e) {
$.post( '/edit', {el: $( e.target ).serialize()}, function(response) {
console.log( response );
});
});
But I get el as an empty string on the server. What else can I do to get the e.target info to my server?
Update:
I think my question could benefit from some context.
The basic function of the app is to enable in-page editing. A node server loads the HTML page I want to edit. Clicking on any element on this page lets me change the text in that element, which is then POSTed back to the node server, where I use the cheerio module to change the DOM representation and overwrite the original HTML file. Reloading the page now gives me the new version of the page with the edits I had made.
But to apply the edits I have made on the front-end, cheerio needs the e.target to find the right element in its DOM representation and then change the text, since many of the elements on the page don't have ids.
This is the whole app...
var
express = require( 'express' )
, fs = require( 'fs' )
, cheerio = require( 'cheerio' )
, $ = ''
, app = express()
, html = ''
, injected = "<script> \
$( 'body').on( 'click', function(e) { \
$( e.target ).text( prompt('Enter new value:') ); \
$.post( '/edit', {el: $(e.target).serialize(), newVal: $(e.target).text()}, function(response) { \
alert( response ); \
}); \
}); \
</script>";
app.use( express.static(__dirname) )
app.use( express.bodyParser() )
app.get( '/', function( req, res ) {
fs.readFile( process.argv[2], 'utf8', function(err, data) {
$ = cheerio.load( data )
err? console.log( err ): res.send( data.replace('</body>', injected + '</body>') )
})
})
app.post( '/edit', function(req,res) {
$( req.body.el ).text( req.body.newVal )
fs.writeFile( process.argv[2], $.html(), function(err) {
err? res.send( err ): res.send( 'file saved with changes!' )
})
})
app.listen( 8080 )
I then run the app:
node cms.js "E:\Dropbox\sites\index.html"
Theoretically, this should let me edit index.html "in-page" and without a code editor. But getting the e.target back to the server intact remains the hurdle.
Workaround:
My current workaround is to just POST the entire HTML of the page using $( 'html' ).html() so regardless of which element is clicked, I can get the new state of the page in it's entirety and overwrite the existing file with this new state. But I have browser extensions that inject their own HTML/JS and I want to avoid the painful process of stripping those away before saving to file. For that, I need to tell cheerio exactly which element has been clicked.