最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Why is my ajax call refreshing the page?

programmeradmin0浏览0评论

I'm attempting to upload an audio file via AJAX form.

Here is my HTML in the profile-edit template.

<form method="post" id="my_upload_form" action="" enctype="multipart/form-data">
  <input type="file" name="file" id="my_file_input" accept="audio/*">                                      
  <input type="submit" class="btn-submit btn-sumary" value="upload audio file" name="submit" id="my_audio_submit">                                      
  <div id="my_error_report"></div>                                  
</form>

Here is my jQuery:

$('#my_upload_form').submit(function () {

    var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;';
    var html = '<strong><em> ' + '<p style="' + css + '">' + '*';
    var endHtml = '</p></em></strong>';

    var formData = new FormData();
    var fileArray = jQuery('#my_file_input').prop('files');

    if(fileArray.length > 0) {
        var theTrack = fileArray[0];
        formData.append("music", theTrack);
    } else {
      jQuery('#my_error_report').html( html + 'no track selected' + endHtml );
      return false;
    }

    $.ajax({
      url: '/wp-admin/admin-ajax.php',
      type: 'POST',
      // async: false,
      data: {
          action      : 'my_track_upload',
          some_data   : formData
      },
      // dataType: 'text'
      }).success( function( data ) {
          /* You win! */
          alert('ajax was called success');
      }).fail( function( data ) {
          /* You lose, show error */
          alert('ajax was called failure');
    });
    return false;  
}); 

Finally here is my plugin code:

add_action('wp_ajax_my_track_upload', 'my_track_upload');
function my_track_upload()
{
  die('hello');
}

Problem (more to come): Why is the page refreshing? I return false in the jQuery 'submit' event.

************************EDIT********************

I changed my code to the following and it works now, though I'm not sure specifically where the problem was.

... ... ...

var theTrack = fileArray[0];
        formData.append('action', 'musistic_track_upload');
        formData.append("music", theTrack);
enter code here

... ... ...

$.ajax({
  url: '/wp-admin/admin-ajax.php',
  type: 'POST',
  data: formData,
  enctype: 'multipart/form-data',
  contentType: false,
  processData: false,
  datatype: "script",
  beforeSend: function() {
    jQuery('#my_error_report').html('');
  }
})plete(function( data ) {
  jQuery('#my_error_report').html( html + data.responseText + endHtml );
  jQuery('#my_audio_submit').val("Upload Audio File", function() {
    jQuery(this).prop('disabled', false);
  });
});

return false;

I'm attempting to upload an audio file via AJAX form.

Here is my HTML in the profile-edit template.

<form method="post" id="my_upload_form" action="" enctype="multipart/form-data">
  <input type="file" name="file" id="my_file_input" accept="audio/*">                                      
  <input type="submit" class="btn-submit btn-sumary" value="upload audio file" name="submit" id="my_audio_submit">                                      
  <div id="my_error_report"></div>                                  
</form>

Here is my jQuery:

$('#my_upload_form').submit(function () {

    var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;';
    var html = '<strong><em> ' + '<p style="' + css + '">' + '*';
    var endHtml = '</p></em></strong>';

    var formData = new FormData();
    var fileArray = jQuery('#my_file_input').prop('files');

    if(fileArray.length > 0) {
        var theTrack = fileArray[0];
        formData.append("music", theTrack);
    } else {
      jQuery('#my_error_report').html( html + 'no track selected' + endHtml );
      return false;
    }

    $.ajax({
      url: '/wp-admin/admin-ajax.php',
      type: 'POST',
      // async: false,
      data: {
          action      : 'my_track_upload',
          some_data   : formData
      },
      // dataType: 'text'
      }).success( function( data ) {
          /* You win! */
          alert('ajax was called success');
      }).fail( function( data ) {
          /* You lose, show error */
          alert('ajax was called failure');
    });
    return false;  
}); 

Finally here is my plugin code:

add_action('wp_ajax_my_track_upload', 'my_track_upload');
function my_track_upload()
{
  die('hello');
}

Problem (more to come): Why is the page refreshing? I return false in the jQuery 'submit' event.

************************EDIT********************

I changed my code to the following and it works now, though I'm not sure specifically where the problem was.

... ... ...

var theTrack = fileArray[0];
        formData.append('action', 'musistic_track_upload');
        formData.append("music", theTrack);
enter code here

... ... ...

$.ajax({
  url: '/wp-admin/admin-ajax.php',
  type: 'POST',
  data: formData,
  enctype: 'multipart/form-data',
  contentType: false,
  processData: false,
  datatype: "script",
  beforeSend: function() {
    jQuery('#my_error_report').html('');
  }
})plete(function( data ) {
  jQuery('#my_error_report').html( html + data.responseText + endHtml );
  jQuery('#my_audio_submit').val("Upload Audio File", function() {
    jQuery(this).prop('disabled', false);
  });
});

return false;
Share Improve this question edited Jan 27, 2016 at 23:16 Keenan Diggs asked Jan 25, 2016 at 19:21 Keenan DiggsKeenan Diggs 1851 gold badge1 silver badge9 bronze badges 8
  • Have you checked your javascript console.log using developer tools in the case there's javascript errors? Have you tried returning false at the top of your submission listener to narrow down the issue? – Howdy_McGee Commented Jan 25, 2016 at 19:24
  • The error is: Uncaught TypeError: Illegal invocation Could it be that the AJAX call wants a string in the some_data parameter? I've seen many examples using the same method I have above. – Keenan Diggs Commented Jan 25, 2016 at 19:28
  • Double check $ is set to jQuery. By default it is not. – jgraup Commented Jan 25, 2016 at 19:30
  • Thanks for your comment jgraup. I open my js file with 'jQuery(document).ready(function($) {', so I don't think that's the error. I also have another function that disables the submit button when it is clicked. – Keenan Diggs Commented Jan 25, 2016 at 19:32
  • Ah yes, I've run into this same issue recently. It has nothing to do with WordPress ( so it's off topic here ) but the issue is that you need to append your action to your formData() object so that the only thing that gets passed into data is: data: formData. No brackets, no name identifier just exactly like that. You can append your action exactly like you're appending music. Hopefully that works for you! – Howdy_McGee Commented Jan 25, 2016 at 19:35
 |  Show 3 more comments

2 Answers 2

Reset to default 7

Try using preventDefault(), it's a jQuery function for preventing default actions called by the browser.

First you should call an event handler by firing up your submitter. You can do this as follow:

$('#my_upload_form').submit(function (event) {

After catching a submit and giving an event with it, you should prevent the default refresh of a browser:

event.preventDefault();

Now your code will look as follow:

$('#my_upload_form').submit(function (event) {

    event.preventDefault();

    var css = 'font:Helvetica; color:red; font-size:1.5em; padding:inherit;';
    var html = '<strong><em> ' + '<p style="' + css + '">' + '*';
    var endHtml = '</p></em></strong>';

    var formData = new FormData();
    var fileArray = jQuery('#my_file_input').prop('files');

    if(fileArray.length > 0) {
        var theTrack = fileArray[0];
        formData.append("music", theTrack);
    } else {
      jQuery('#my_error_report').html( html + 'no track selected' + endHtml );
      return false;
    }

    $.ajax({
      url: '/wp-admin/admin-ajax.php',
      type: 'POST',
      // async: false,
      data: {
          action      : 'my_track_upload',
          some_data   : formData
      },
      // dataType: 'text'
      }).success( function( data ) {
          /* You win! */
          alert('ajax was called success');
      }).fail( function( data ) {
          /* You lose, show error */
          alert('ajax was called failure');
    });
});

BTW: Always try to place preventDefault() on top of the function, it should prevent the default action before anything else is done.

I was missing a crucial line in my AJAX query. Without this option, the call fails, and the pages refreshes.

processData: false,
发布评论

评论列表(0)

  1. 暂无评论