fardad fardad - 6 months ago 13
PHP Question

Using Ajax and PHP in wordpress

Hi guys i am new to wordpress and ajax , i use this code for checking an input value before submitting the form :

$j("#ninja_forms_field_75").focusout(function(){
var content = document.getElementById("ninja_forms_field_75").value;
$j.ajax({
url : 'check.php',
data : {'mid':content},
type : 'POST',
success : function(resp){
if(resp == '1'){
//success message or whatever
},
error : function(resp){
alert("some error occured !");
}
});
});


problem is i dont know where shall i put that php file to work with database...
please help me!!!

pardon my english...

Answer

Inside your js file write your code above:

javascript.js

$j("#ninja_forms_field_75").focusout(function() {
  var content = document.getElementById("ninja_forms_field_75").value,
        my_data = {
        'action': 'my_action',
        'mid': content
      };
  $j.ajax({
      url: ajaxurl,
      data: my_data,
      type: 'POST',
      success: function(resp) {
        if (resp == '1') {
          //success message or whatever
        },
        error: function(resp) {
          alert("some error occured !");
        }
      });
  });
});

Then the php part begins, I prefer to store it inside the functions.php if it's just one ajax request. If it is more than one create a file like ajax-handler.php and include it inside your functions.php

functions.php

if ( defined( 'DOING_AJAX' ) ) {
  include_once( 'ajax-handler.php' );
}

ajax-handler.php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'wp_ajax_my_action', 'my_custom_ajax_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_custom_ajax_action' );
function my_custom_ajax_action() {
    $result = 'Hello';

    wp_send_json( $result );
}