I have a vote button which will update a value in the database once the button is clicked. This previously worked without AJAX. I’m now trying to execute this file using the AJAX below so I don’t need to reload the page.
The problem is, when I submit the form the AJAX request is not executed. I’ve tried playing with e.preventDefault(); which I think is causing the problem.
Bit of a novice using AJAX any help on this much appreciated
Also I take you you aren’t in the habit of intelligently debugging with break points. I highly recommend using breakpoints and the chrome debugger. If you do you can place a breakpoint on that line and see exactly what “this” is at run time rather than guessing or using the evil console.log.
Since you’re sending data to the server, you should use POST – especially as it modifies the database. GET is used for retrieving data only… like the names suggest. :-)
That is said data you’re sending to the server. Now scriptString is undefined in your snippet, so maybe that was breaking your script and nothing happened (including the .preventDefault() call). You should actually see a reference error in the console then.
Because this generally refers to the context in which a given function was invoked. As .success() is a method of your options object, this refers to this very object. Outside that object but still inside the click handler function, this refers to the .vote element on which the event occurred. And outside that function again, this refers to the document.
You can however bind this to the outer context like so:
success: function () {
// Now `this` refers to the `.vote` element
}.bind(this)
Another way is to use arrow functions, which don’t have their own this binding at all:
I’ve had a heavy day trying to call the C# razor file into the ajax, turned out I couldn’t execute the file due to a CurrentContext (something in the CMS) and needed to post to itself and add a page.cshtml?vote into the URL to achieve the result. Still not sure how it worked, though at a good stage right now.