Home Jquery ajax validator and wordpress
Reply: 0

Jquery ajax validator and wordpress

Rick Dreamer
1#
Rick Dreamer Published in 2017-12-07 20:42:17Z

I'm trying to make remote validation with jquery validator plugin. Validated wordpress meta field. This the code:

jquery

jQuery.validator.addMethod("checkUrl", function(value, element)
{
$.ajax(
{
    type: "POST",
    url: "/wp-admin/admin-ajax.php",
    dataType: "json",
    data: {
        "id_project_URL": $( "#id_project_URL" ).val(),
        "action": 'check_url'
    },
    success: function(data)
    {
        if (data !== true)
        {
          return 'This url is already registered.';
        }
        else
        {
           return true;
        }
    },
    error: function(xhr, textStatus, errorThrown)
    {
        alert('ajax loading error... ... '+url + query);
        return false;
    }
});
}, "");


form.validate({
 rules:{
  id_project_URL: {
   checkUrl: true
  }
 }
 messages:{
  id_project_URL:{
   checkUrl: "Your project already exists"
  }
 }
});

functions.php

add_action('wp_ajax_check_url', 'check_url_func');
add_action('wp_ajax_nopriv_check_url', 'check_url_func');
function check_url_func() {
  global $wpdb;
    $posts = get_posts([
             'post_type' => 'ignition_product',
             'posts_per_page' => -1,
             'no_found_rows' => true,
             'fields' => 'ids',
     ]);
     foreach( $posts as $post_id ){
         $projectarr[] = get_post_meta($post_id, 'id_project_URL', true);
     }
     $id_project_URL = $_POST['id_project_URL'];
if(in_array($id_project_URL, $projectarr)){
    echo json_encode('false');
}
else{
    echo json_encode("true");
}
die();
}

After validation if url is unique, code must return true result. In any case code return false.

Im also traing to use the remote method validation plugin, in this case the result was the same

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.330895 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO