WordPress.org

Ready to get started?Download WordPress

Forums

Ajax not working (1 post)

  1. miguelsaddress
    Member
    Posted 1 year ago #

    Hello!

    Im using ajax in post submit.... when im editing a post (custom post type), when the user clicks on submit button i want to check a field and according to its value, abort the process. AKA: Its a mandatory field...

    When I validate in Javascript its all fine... it detects the failures and if the field has a correct value it goes on and saves.

    This is the Javascript:

    jQuery(document).ready(function() {
    
      var post_type = jQuery('#post_type').val();
      if( post_type != 'entrevistas') return;
          jQuery('#post').submit(function( ev ) {
              //ev.preventDefault();
              var artist_name = trim( jQuery('#entrevistas_artist').val() );
              if( artist_name.length == 0 ){
                   alert("El nombre del artista no puede estar vacío.\nNo se ha guardado");
                   resetLoaders();
                   return false;
               }
               var data = {
                   action: 'entrevistas_verify_hook',
                   artist_name: artist_name
               };
    
               jQuery.post(ajaxurl, data, function(response) {
                     var success;
                     if (response == "OK") {
                         success = true;
                     }else{
                         console.log(response);
                         alert( response );
                         success = false;
                      }
                      resetLoaders();
                      return success;
          });//jQuery.post
        });//jQuery.submit
    });//ready

    The problem comes in the answer. In my PHP code i have something like follows:

    public static function entrevistas_verify_hook(){
    
        $artist_name = $_POST['artist_name'];
        if( strlen( $artist_name ) == 0 ){
        	$msg = "El artista no puede estar vacío";
        }else{
            $msg ="OK";
        }
        die( $msg );
    }

    It does not work. I checked and, if in Javascript i do the ev.preventDefault(), the ajax answer works fine (i receive in the alert what the server prints) but it does not save the fields value (i guess because it doesnt submit)

    Anyone who can help me solve this issue? Right now I just do not see how :-(

    Thank you in advance,
    Miguel

Topic Closed

This topic has been closed to new replies.

About this Topic