How to use ajax in Wordpress? - ajax

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me.
Here it is my wordpress action and hook.
function ajax_enqueuescripts() {
wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajax_enqueuescripts);
add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );
function my_action_callback(){
//echo "Df";print_r($_POST);die;
}
and here it is my js code
jQuery(document).ready(function(){
jQuery('#event-form').submit( function () {
var email = jQuery('#event_name').val();
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function() {
alert(email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
return false;
});
});

The value that you alert in your success ajax function must come from your php function so you would have something like this:
PHP
function my_action_callback(){
echo $_POST['email']; die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
in your case data in javascript will be equal to anything that you echo out in your php function.
You can send json objects to javascript by encoding arrays in which case you would have
PHP
function my_action_callback(){
echo json_encode('email' => $_POST['email']));
die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data.email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
I only gave you example of the places in your code that needed to be replaced, the rest seems alright.

Related

Laravel Message from API (Ajax)

I have a Laravel project and would like the API server to return a message (validation) that will be displayed in Laravel.
Laravel
<script>
jQuery('#ajaxSubmit').click(function(e){
$.ajax({
type: 'post',
url: $("#r").val(),
data: {
i:$("#i").val(),
c:$("#c").val(),
cn:$("#cn").val(),
s:$("#s").val(),
m:$("#m").val(),
},
success: function(response) {
if($.isEmptyObject(response.error)){
location.reload();
}else{
printErrorMsg(response.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
</script>
API Server
return response()->json(['error' => 'My Message']);
I believe
response.error
must be
response.data.error

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

Laravel 5.4 TokenMismatchException Ajax call

I get a TokenMismatchException error only when I submit a form with an ajax call? If I don't use an Ajax call I don't get the error.
What is causing this?
Laravel 5.4
I have this in the head of my app.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
My ajax.js
$( document ).ready(function() {
// storing comments
$('#storeComment').on('submit', function(e) {
e.preventDefault();
$.ajax({
method: 'POST',
url: '/comments',
data: {},
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
});
I also use the bootstrap.js that automatically registers the value of the csrf-token meta tag with the Axios HTTP library. As explained in the Laravel documentation.
Controlle Method:
public function store(CommentRequest $request)
{
$comment = Auth::user()->comments()->save(new Comment($request->all()));
$response = array(
'status' => 'success',
'comment' => $comment
);
return response()->json($response);
}
Add the token to the ajax's data :
$.ajax({
type: 'POST',
......
data: {'_token': '{{ csrf_token() }}'},
........
Instead of calling jQuery you can call Axios directly and have this automatic csrf injection, with the following code:
var data = ['name' => 'Nikola', 'lastName' => 'Gavric'];
axios.post('/comments', data).then(function(response) {
console.log(response);
});
EDIT: Complete example for axios is
$('#storeComment').on('submit', function(e) {
e.preventDefault();
// Retrieve form data
var temp = [];
var data = $(this).serializeArray();
$.each(data, function(index, field) {
temp[field.name] = field.value;
});
// Post request with temp as data
axios.post('/comments', temp).then(function(data) {
console.log(data);
});
});
And this is the code for jQuery, use whichever approach you like better:
$.ajax({
method: 'POST',
url: '/comments',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
'name': 'Nikola',
'lastName': 'Gavric'
},
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
$.ajax({
type: 'POST',
........
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
...........
});
try this...
Add csrf-token to head of your application :
<meta name="csrf-token" content="{{ csrf_token() }}">
then :
$.ajax({
url: '/some/url',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(res){
// Your result
console.log(res);
}
});
You can try to disable CSRF verification on specific route in App\Http\Middleware\VerifyCsrfToken.php
protected $except = ['/comments'];

Error Code using $Ajax, phpjson and sqlsrv_fetch_array

I have code like this in dataset.php
$query = "SELECT A,B,C from Table ";
$stmt = sqlsrv_query($link2,$query);
$data = array();
while($row=sqlsrv_fetch_array($stmt))
{
$data['data'][]= array (
'kodeLang' => $row['A'],
'nama_lang' => $row['B'],
'address' => $row['C']
);
}
echo json_encode($data);
and , i want to load the dataset.php in index.php with code like this :
<script>
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'dataset.php', //Relative or absolute path to response.php file
data: '',
dataType: 'json',
contentType: "application/json",,
success: function(data){
alert(data);
$("#atotal td#aTotal").html(data[0]['kodeLang']);
},
error : function (jqXHR,textStatus, errorThrown){
$('#errorr').fadeIn(1000).show();
}
});
event.preventDefault();
});
</script>
But when i using alert(data) in index.php, there's no alert. Is there any missed with my code ?
Trims
I have answer by my self, the proble about the array. I modified the file in index.php
<script>
$(document).ready(function(){
$.ajax({
type: 'post',
dataType: 'json',
url: 'dataset.php',
data: '',
contentType: 'application/json',
success: function(response){
$("#atotal td#aTotal").html(response.data[0].A);
},
error : function (jqXHR,textStatus, errorThrown){
$('#errorr').fadeIn(1000).show();
}
});
event.preventDefault();
});
</script>

JQuery Ajax POST in Codeigniter

I have searched a lot of tutorials with POST methods and saw answered questions here too but my POST still doesn't work...I thought i should post it here if you guys see something that i don't!
My js - messages.js:
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: base_url + "chat/post_action",
data: {textbox: $("#textbox").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
return false;
});
});
My view - chat.php:
<?php $this->load->js(base_url().'themes/chat/js/messages.js');?> //i use mainframe framework which loading script this way is valid
<form method="post">
<input id="textbox" type="text" name="textbox">
<input id="send" type="submit" name="send" value="Send">
</form>
Last My controller - chat.php
//more functions here
function post_action()
{
if($_POST['textbox'] == "")
{
$message = "You can't send empty text";
}
else
{
$message = $_POST['textbox'];
}
echo $message;
}
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: base_url + "chat/post_action",
data: {textbox: $("#textbox").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have missed this bracket
return false;
});
});
In codeigniter there is no need to sennd "data" in ajax post method..
here is the example .
searchThis = 'This text will be search';
$.ajax({
type: "POST",
url: "<?php echo site_url();?>/software/search/"+searchThis,
dataType: "html",
success:function(data){
alert(data);
},
});
Note : in url , software is the controller name , search is the function name and searchThis is the variable that i m sending.
Here is the controller.
public function search(){
$search = $this->uri->segment(3);
echo '<p>'.$search.'</p>';
}
I hope you can get idea for your work .
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class UserController extends CI_Controller {
public function verifyUser() {
$userName = $_POST['userName'];
$userPassword = $_POST['userPassword'];
$status = array("STATUS"=>"false");
if($userName=='admin' && $userPassword=='admin'){
$status = array("STATUS"=>"true");
}
echo json_encode ($status) ;
}
}
function makeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
cache: false,
data: $('#userForm').serialize(),
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
The question has already been answered but I thought I would also let you know that rather than using the native PHP $_POST I reccomend you use the CodeIgniter input class so your controller code would be
function post_action()
{
if($this->input->post('textbox') == "")
{
$message = "You can't send empty text";
}
else
{
$message = $this->input->post('textbox');
}
echo $message;
}
<script>
$("#editTest23").click(function () {
var test_date = $(this).data('id');
// alert(status_id);
$.ajax({
type: "POST",
url: base_url+"Doctor/getTestData",
data: {
test_data: test_date,
},
dataType: "text",
success: function (data) {
$('#prepend_here_test1').html(data);
}
});
// you have missed this bracket
return false;
});
</script>

Resources