AJAX action in theme's functions.php - php

I've figured out that wp_ajax_my_action only works if it's placed in a plugin.
Does anyone know if it's possible to run it in my theme's functions.php?

Yes you can :
In your page template :
var AjaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
type: "POST",
url: AjaxUrl,
data: {
action: 'your_action'
},
Inside your functions.php :
function your_action() {
//write your code here
}
add_action('wp_ajax_your_action', 'your_action');
add_action('wp_ajax_nopriv_your_action', 'your_action');

Pass action in Html form
<form name="myform">
<input type="hidden" name="action" value="custom_action">
<input type="text" name="get_first_name" >
<input type="submit value="submit">
</form>
Your jQuery look like this
<script>
jQuery(document).ready(function ()
{
var $this = jQuery(this); // Cache this
jQuery.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>', // Let WordPress figure this url out...
type: 'post',
dataType: 'JSON', // Set this so we don't need to decode the response...
data: $this.serialize(), // One-liner form data prep...
beforeSend: function () {
// You could do an animation here...
},
success: function (data)
{
if (data.status === 'success') {
alert("Success");
// Here, you could trigger a success message
} else {
// fail
}
}
});
});
</script>
put this code in function file
function custom_action_function()
{
$first_name = $_POST['get_first_name'];
/* fetch your form variable here */
if('your condition') // your condition if success
{
echo json_encode(array('status' => 'success', 'message' => 'Message Sent.'));
exit;
}
else
{
echo json_encode(array('status' => 'error', 'message' => 'Message not sent'));
exit;
}
}
add_action('wp_ajax_custom_action', 'custom_action_function'); // Call when user logged in
add_action('wp_ajax_nopriv_custom_action', 'custom_action_function'); // Call when user in not logged in

Related

'Bad Request' with ajax and codeigniter

Windows 10, Codeigniter 3, Wamp3.
Ajax post throws a Bad Request error. This is an old chestnut but online research shows the problem usually to be CSRF. However I emphasize at the outset that I have csrf disabled for this test:
config['csrf_protection'] = FALSE;
I have set up some deliberately very simple test code. The controller looks like this:
class Ajax extends CI_Controller {
public function index() {
$this->load->view('pages/index');
}
public function hello($name) {
$fullname = $this->input->post('fullname');
echo 'Hello '.$fullname;
}
}//EOF
and the view looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:'<?php echo base_url('ajax/hello'); ?> + fullname',
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
</head>
<body>
Name <input type="text" id="fullname">
<input type="button" value="Hello" id="bttHello">
<br>
<span id="result1"></span>
</body>
</html>
The console shows a Bad Request
POST XHR http://localhost/faith/ajax/hello%20+%20fullname [HTTP/1.1 400 Bad Request 9ms]
So if csrf is not the culprit, is it a Wamp issue? Everything else seems to work fine. I have spent so much time on this!
What is going on?
Data are already sent through POST. No need to pass it through URL
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:"<?php echo base_url('ajax/hello'); ?>",
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
And, remove parameter $name from controller action hello().
public function hello() {
$fullname = $this->input->post('fullname');
echo 'Hello '.$fullname;
}
write url like this
"url": "<?php echo base_url().'ajax/hello';?>/" + fullname
after /fullname its a argument of function hello()
Try this..
<?php echo form_open('ajax/hello', [
'method' => 'post',
'class' => 'create_form'
]); ?>
<input type="text" name="fullname" value="Full Name"/>
<button type="submit">Create</button>
<?php echo form_close(); ?>
and ajax
$(document).on('submit', 'form.create_form', function (e) {
var self = this;
var formData = new FormData($(this)[0]);
$.ajax({
url: $(self).attr('action'),
type: 'POST',
data: formData,
async: false,
dataType: 'json',
success: function (res) {
console.log(res)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The CodeIgniter Controller:
<?php
class Ajax extends CI_Controller
{
public function index()
{
$this->load->view('pages/index');
}
/**
* #param $name
*/
public function hello($name)
{
// if no $name params value pass and post exist
if ( ! isset($name) && $this->input->post('fullname')) {
// get value from post params
$fullname = $this->input->post('fullname', true);
} elseif (isset($name) && ! $this->input->post('fullname')) {
// get value from pass param method
$fullname = $name;
} else {
// default value
$fullname = 'No Name found';
}
// show ajax response
echo $fullname;
}
/**
* Another way if we using GET params
* e.g. http://wwww.site.com/ajax/hello/my-name-value
* #param $name
*/
public function hello_another($name)
{
// if url has param as name value
// remember codeigniter will map all url params as method params as they provided
// no need to use get input, it will take from url string directly
if (isset($name)) {
// get value from get params
$fullname = $name;
} else {
// default value
$fullname = 'No Name found';
}
// show ajax response
echo $fullname;
}
/**
* Another way if we using GET params and security is on top
* e.g. http://wwww.site.com/ajax/hello/my-name-value
* #param $name
*/
public function hello_another_secure($name)
{
// if url has param as name value
// remember codeigniter will map all url params as method params as they provided
// no need to use get input, it will take from url string directly
if (isset($name) && preg_match("/^[a-zA-Z'-]+$/", $name)) {
// get value from method params
$fullname = $name;
} else {
// default value
$fullname = 'No Name or invalid name found';
}
// show ajax response
echo $fullname;
}
}
//EOF
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:'<?php echo base_url('ajax/hello'); ?>',
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'GET',
url:'<?php echo base_url('ajax/hello_another/'); ?> + fullname',
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
The CodeIgniter is fully capable to fulfil your needs, Just look their AWESOME Document first..
use this way
you should concate fullname variable after quatation.
like this
url:'<?php echo base_url('ajax/hello'); ?>' + fullname
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:'<?php echo base_url('ajax/hello'); ?>' + fullname,
success: function(result) {
$('#result1').html(result);
}
});
});
});

Ajax request shows complete but data not submitted

I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()

using ajax from a php function

I am new with ajax. I have this php function already from functions.php
function checkUserEmailExistent($email){
...
return $boolean;
}
and this is for my views views.html
<input type='text' name='email' id='email'>
this is for the script.js
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'url',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
}
});
});
my issue is how can I call my php function in ajax to connect it to my html. when it blur it check the email value if it is exist or not.
work in WordPress
JS SCRIPT
jQuery( "#email" ).blur(function() {
jQuery.ajax(
{
url: ajax_url,
type: "POST",
dataType: "json",
data: {
action: 'checkUserEmailExistent',
email: $(this).val(),
},
async: false,
success: function (data)
{
if (data.validation == 'true')
jQuery('.email-massage').html('<div class="alert alert-success">×<strong>Success!</strong> successfully</div>');
else
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
},
error: function (jqXHR, textStatus, errorThrown)
{
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
}
});
});
WP SCRIPT in functions.php
add_action('wp_ajax_checkUserEmailExistent', 'checkUserEmailExistent');
add_action('wp_ajax_nopriv_checkUserEmailExistent', 'checkUserEmailExistent');
function checkUserEmailExistent() {
$email = $_POST['email']; // get email val
/*if() your condition
$email = 1;
else
$email = 0;
*/
if ($email == 1):
$email_val= 'true';
else:
$email_val = 'false';
endif;
echo json_encode(array("validation" => $email_val));
die;
}
in function.php Enqueue file after add this code like this
wp_enqueue_script('themeslug-default', get_template_directory_uri() . '/js/default.js', array('jquery'));
wp_localize_script('themeslug-default', 'ajax_url', admin_url('admin-ajax.php'));
Set url to the php file where you have checkUserEmailExistent function. Then:
function checkUserEmailExistent($email){
...
return $boolean;
}
return checkUserEmailExistent($_REQUEST['value']);
I give the example for validation.This will help you to check
Email id<input type="text" name="email" id="email" size=18 maxlength=50 onblur="javascript:myFunction(this.value)">
You need to add the script
<script>
function myFunction(em) {
if(em!='')
{
var x = document.getElementById("email").value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
document.getElementById("email").value = "";
return false;
exit();
}
var email=$("#email").val();
$.ajax({
type:'post',
url:'email_client.php',
data:{email: email},
success:function(msg){
if (msg.length> 0) {
alert(msg);
document.getElementById("email").value = "";
}
}
});
} }
</script>
Create a page 'email_client.php' and add the code
<?php
$s=$_POST['email'];
include "config.php";
$echeck="select email from client where active=0 and email='".$_POST['email']."'"; //change your query as you needed
$echk=mysql_query($echeck);
$ecount=mysql_num_rows($echk);
if($ecount>='1' && $s!='0')
{
echo "Email already exists";
}
?>
You would call it in your url parameter. However, you'll need to manage your AJAX handler in the PHP script.
AJAX
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'functions.php',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
if (result.success) {
//handle success//
} else if (result.failure) {
//handle failure//
}
}
});
});
PHP
function checkUserEmailExistent($email){
...
return $boolean;
}
if ($_POST['value']) {
$status = checkUserEmailExistent($email);
if ($status === true) {
echo json_encode (array('status' => 'success'));
} elseif ($status === false) {
echo json_encode (array('status' => 'failure'));
}
}
you don't call your server function inside Ajax you only send your data in JSON format to the server on getting this data,server will route(if MVC) it to specific function and return a response to client in JSON format so now inside Ajax you perform operation on success (what to do next ) and in case of failure show the error
How server will route it to specific function that depend on framework you use, but i think they simply use regexp to match with URL

jquery - how to create condition in success function

I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?
logout.php
<?php
if( !$user->is_logged ) {
echo 'true';
}else{
echo 'false';
}
?>
jquery function in index.html
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
if(resp =='true'){
document.location = '../login_test.html';
}
if(resp=='false'){
alert('U are logged');
}
}
});
});
Change some errors and made it to better view:
PHP:
<?php
header('Content-Type: application/json');
if( !$user->is_logged ) {
echo json_encode(array('status' => 'ok'));
}else{
echo json_encode(array('status' => 'bad'));
}
?>
Javascript:
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
var state = JSON.parse(resp).status
if(state == 'ok'){
document.location.href = '/login_test.html';
}
else{
alert('U are logged');
}
}
});
});
If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.

Using jQuery JSON in CodeIgniter

In CI, I have setup a controller with a method of logsig(). Then in my index() method I'm calling a view called startpage. In my view I'm using JSON to make an asynchronous call between my view and my controller. How would I code the call. Below is the code I have:
Contoller:
function logsig() {
$this->load->view('startpage', $sync);
header('Content-type:application/json'); .............
View:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// blink script
$('#notice').blink();
$("#action_button").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "processing/logsig.php",
data: dataString,
json: {session_state: true},
success: function(data){
if(data.session_state == true) { // true means user is logged in.
$("#main1").hide();
$('#main1').load('<?=$sync?>').fadeIn();
} else if(data.session_state == false) { // false means user is being registered.
$("#action_button").remove();
$('#success').load('<?=$sync?>');
// onLoad fadeIn
}
}
});
}
});
});
</script>
You can't have your controller load a view and return JSON at the same time. Break out the JSON portion to a separate function.
An oversimplified example could look like this:
// Your existing function, but only displaying the view
function logsig() {
$this->load->view('startpage', $sync);
}
// A new function whose sole purpose is to return JSON
// Also notice we're using CI's Output class, a handy way to return JSON.
// More info here: codeigniter.com/user_guide/libraries/output.html
function get_json() {
$this->output->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
}
Then, in your JavaScript, call get_json:
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url('processing/get_json.php'); ?>",
// ... truncated for brevity ...
});
If I read your question correctly, your JS postback code isn't working:
url: "processing/logsig.php",
Your CI url should be something like:
url: <?php echo site_url("processing/logsig"); ?>,
The site_url() function requires the URL helper. Load that in the beginning of your loadsig() function:
$this->load->helper('url');
Try This
Controller ---------
public function AjaxTest() {
$rollNumber = $this->input->post('rollNumber');
$query = $this->welcome_model->get_students_informationByRoll($rollNumber);
$array = array($query);
header('Content-Type: application/json', true);
echo json_encode($array);
}
View-----
<?php echo validation_errors(); ?>
<?php echo form_open('welcome/SearchStudents'); ?>
<input type="text" id="txtSearchRoll" name="roll" value="" />
<input type="submit" name="btnSubmit" value="Search Students" onclick="return CheckAjaxCall();"/>
<?php echo '</form>'; ?>
Scripts ----------
function CheckAjaxCall()
{
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>welcome/AjaxTest',
dataType:'json',
data:{rollNumber: $('#txtSearchRoll').val()},
cache:false,
success:function(aData){
//var a = aData[0];
//alert(a[0].roll);
$.map(aData, function (item) {
var stData = "<td>"+ item[0].roll +"</td>" +
" <td>"+item[0].Name+"</td>" +
"<td>"+item[0].Phone+"</td>" +
"<td> Edit </td>"+
"<td> Delete </td>";
$('#tblStudent').text("");
$('#tblStudent').append(stData);
//alert (item[0].roll + " " + item[0].Name);
});
//alert(aData);
},
error:function(){alert("Connection Is Not Available");}
});
return false;
}

Categories