0

Getting error on ajax URL path in wordpress. It's working on localhost, But it's not working on the server. And my upload-file.php is located at domainname.com/wp-content/themes/mytheme/upload-file.php How can I define the URL path jquery ajax? Please help me to solve the issue.

Here is my code sample:

$.ajax({
     url:'upload-file.php',
     method:"POST",
     data: form_data,
     contentType: false,
     cache: false,
     processData: false,
Devbuddy
  • 231
  • 4
  • 15

1 Answers1

2

Use wp_localize_script for ajax in wordpress. The URL of the WordPress admin-ajax.php file, where the data to be sent for processing.

//add in function.php
function ajax_script() {
    wp_enqueue_script( 'ajax_operation_script', get_template_directory_uri() . '/js/script.js', array('jquery'), '1.0.0', true );
    wp_localize_script( 'ajax_operation_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relataive' )));  
    wp_enqueue_script( 'ajax_operation_script' );
}
add_action( 'wp_enqueue_scripts', 'ajax_script' );

The Ajax action hook called wp_ajax_. You need to hook a custom function into it which will be executed during the Ajax call.

//add in function.php
add_action('wp_ajax_upload_file', 'upload_file');
add_action('wp_ajax_nopriv_upload_file', 'upload_file');

function upload_file(){
    parse_str($_POST['form_data'], $my_array_of_vars);
    print_r($my_array_of_vars);
    die;
}

Ajax Code.

$.ajax({
    url: myAjax.ajaxurl,
    method:"POST",
    data : {action: 'upload_file',
    form_data:form_data 
    },
    contentType: false,
    cache: false,
    processData: false
Shivendra Singh
  • 2,986
  • 1
  • 11
  • 11
  • Thank you dear, I have a doubt.. What about admin-ajax.php? is that upload-file.php? – Devbuddy Jun 03 '19 at 11:24
  • No it's not a upload-flile.php it's just call your ajaxfile action. – Dhruv Jun 03 '19 at 11:30
  • Just follow this https://medium.com/techcompose/how-to-use-ajax-precisely-in-wordpress-custom-themes-dc61616720a8 why worpdress use nopriv function to call every ajax call – Dhruv Jun 03 '19 at 11:32
  • Nopriv it's handle your ajax request – Dhruv Jun 03 '19 at 11:33
  • 1- admin-ajax.php is core wordpress file to run AJAX calls from the web-browser. 2- The Ajax action hook called wp_ajax_. You need to hook a custom function into it which will be executed during the Ajax call. – Shivendra Singh Jun 03 '19 at 11:34
  • In your ajax request I pass extra attribute action:upload_file within data. And I create a function 'upload_file' and attached with wp_ajax. upload_file function is used to execute the ajax call. – Shivendra Singh Jun 03 '19 at 11:39