AJAX no page reload - help executing file on submit

Hi all,

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 :slight_smile:

What is wrong with my code?

$(function () {
  $('#like').prop('disabled', $.cookie('like'));
    
  var baseURL = '/assets/razors/plus-one.cshtml';

  $('.vote').click(function(e) {
      
      $.cookie(this.id, 'true', { expires: 1 });
      $(this).prop('disabled', true);
      $(this).val("Thanks for voting!");

      $("div.success").fadeIn( 300 ).delay( 1500 );
      
      $.ajax({
        method: 'get',
        url: baseURL,
        data: {
          'myString': scriptString,
          'ajax': true
        },
        success: function(data) {
          $('#data').text(data);
        }
      });
      
      e.preventDefault();
    
    //alert('Thanks');

  });
});

Also wondering if I need the data: and success: settings.
Could I potential add the $("div.success").fadeIn( 300 ).delay( 1500 ); into success:?

And should I use GET or POST?

The file in discussion (plus-one.cshtml) has the below snippet inside it:

var query = "UPDATE CompEntry_Data SET Counter = Counter + 1 WHERE ID =" + CurrentNode.Data.Property_ID;

<input type="Submit" id="like" value="Vote for me" class="vote" />
<div class="alert-box success">Results coming soon.</div>

Thanks, Barry

I think I have something…

What I’ve done is remove:

data: {
          'myString': scriptString,
          'ajax': true
        },

What is this for, and do I need it?

And changed:

 success: function(data) {
          $('#data').text(data);
        }

to

success: function(data) {
          $("div.success").fadeIn( 300 ).delay( 1500 );
        }

Updated code

$(function () {
	//$('#like').prop('disabled', $.cookie('like'));
  	
    var baseURL = '..imageurl'; //used image as don't have access to server right now
	$('.vote').click(function(e) {
      
      $.cookie(this.id, 'true', { expires: 1 });
      $(this).prop('disabled', true);
      $(this).val("Thanks for voting!");
      
      $.ajax({
        method: 'get',
        url: baseURL,
        
        success: function(data) {
          $("div.success").fadeIn( 300 ).delay( 1500 );
        }
      });
      
      e.preventDefault();

	});
  });

Do this seem right?
Success function data faded in and no console errors.

Any tips or feedback thanks :nerd:

One other question:

Why doesn’t $(this).val("Thanks for voting!"); work inside the success function?

Example:

$("div.success") is executed.
But $(this).val("Thanks for voting!") is not

success: function(data) {
          $("div.success").fadeIn( 300 ).delay( 1500 );
          $(this).val("Thanks for voting!");
        }

Thanks.

Refer to the ajax docs context option.

http://api.jquery.com/jquery.ajax/

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.

2 Likes

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:

success: () => {
  // ...
},

(Note that these are not supported in IE though.)

1 Like

Thanks a lot m3g4p0p,

Plenty to digest here :nerd:

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.

The final ajax result:

$.ajax({
        method: 'post',
        url: '@path?vote=true',
        
        success: function(data) {
          $("div.success").fadeIn( 300 ).delay( 1500 );
        }
      });

Thanks for the detailed information, will come in very handy!

Best,
Barry

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.