Having Trouble using AJAX with jquery in Wordpress FrontEnd - ajax

Hello I am developing a plugin for Word Press,
Admin area is all ok but i want to use AJAX in front end to send some data to my server.
I am using AJAX in jquery like
jQuery.AJAX({
My code.....
})
But its not working, As the same code approach working well at admin side.
the file where I post my data is in my plugin directory
I am attaching the code please check what am i doing wrong thanks
This is the front end file
jQuery(document).ready(function(){
var url= jQuery('#url').val();
jQuery.ajax({
type:"POST",
URL:url,
data:{
data:'azam'
},
success:function(data)
{
}
})
});
Here is my php file
function hello($a)
{
$a = $_POST['data'];
echo $a;
}
add_action('wp_ajax_hello', 'hello');
add_action('wp_ajax_nopriv_hello', 'hello');
Please dont give me online links caz i search whole internet already but i cant understand how it works. please help

If u use wp_enqueue_script, i suggest u to add this function in your main php file.
function plugin_ajax_articles()
{
wp_enqueue_script( "your_js_file", get_stylesheet_directory_uri() . '/your_js_file.js', array('jquery'), "1.0.0", true );
wp_localize_script( 'your_js_file', 'url', admin_url( 'admin-ajax.php' ) );
}
add_action("init", "plugin_ajax_articles");
Then in ur js file, URl will work.
Don't forget to add a "die();" at the end of your php function.
If u have time, read this article => Tuto Ajax WordPress
I hope that help u :)

Your code looks mostly correct but here are my findings:
In the end of your hello function add die();
Are you using correct admin ajax url?
add this to your functions.php to output admin ajax url.
function ajaxurl() {
?>
<script type="text/javascript">
var AjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','ajaxurl');
you need to add action parameter into your data
.ajax({
type:"POST",
URL:AjaxUrl, // is this url correct? it should be admin ajax url
data:{
action:'hello',
data:'azam'
},

Related

wordpress: AJAX: 400 bad request with admin-ajax.php

I have searched and red a lot of this issue.
However, I do not know, why this few simple lines produce a
"POST http://example.com/wp-admin/admin-ajax.php 400 (Bad Request)"
What I basically want (later on) is: If you press a button, a counter will be updated and write a value into my mySQL. But before I can think about a mySQL query, I stumble over this 400 Error.
What I have (really basic, no validations, etc.):
html
<button id="vote" type="button">Click Me</button>
jQuery
<script type="text/javascript">
//var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; // get ajaxurl
jQuery('#vote').click(function() {
jQuery.ajax({
url: 'http://example.com/wp-admin/admin-ajax.php', //just hard coded to see if I have a problem with my ajaxurl
type : 'post',
data: {
'action' : 'ibvote'
},
success: function( data) {
alert( data);}
});
});
</script>
php
add_action("wp_ajax_ibvote", "ibvote");
add_action("wp_ajax_nopriv_ibvote", "ibvote");
function ibvote(){
echo "DONE";
wp_die();
}
Any help would be great.
Thank you.
Thank you #all.
I use the "Code Snippets" plugin and I activated "only run on site frontend". Today with more coffee I switched to run snippet everywhere and: voila! Working like a charm.
#Bhautik: Again thank you for your time and answer :)

Loading php file with AJAX in Wordpress frontend

Trying out AJAX request for the first time and facing problem. I want to load a php file on button click in Wordpress site. So far after researching, I got this code:
index.php file:
<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>
ajax.php file (the file i want to be loaded):
<?php echo "Hello!" ?>
functions.php file:
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script('menu_toggle', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
// Grab php file output from server
ob_start();
include(get_template_directory_uri() . '/ajax.php');
$result['content'] = ob_get_contents();
$result = json_encode($result); // use wp_send_json instead to make this shorter
echo $result;
die();
}
menu_toggle.js file (js file with ajax code):
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(response.content);
}
});
});
I can actually get alert('Load was performed.'); and $('#ajax').append("hello"); displaying, so that means that ajax was connected right way and ajax request is working correctly. But $('#ajax').load(response.content); loading whole same index page in #ajax div instead of loading the content of ajax.php file i actually want. I probably got the wrong code either in function tablo() of functions.php file, or in ajax code of menu_toggle.js file. Can someone please help with this one?
You need to convert/parse the json data in JS coming from PHP. Like :
var res = JSON.parse(response);
The full code look like :
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
var res = JSON.parse(response);
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(res.content);
}
});
});
Chetan Vaghela just helped with this problem on wordpress.stackexchange.com. If someone encounters with same problem as i had, please check Chetan Vaghela's answer below:
Solution provided by Chetan Vaghela on wordpress.stackexchange.com

Admin ajax in wordpress is not working

I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.

redirect after process php

well after reading all the related topics still no success,
I have 4 files index.php with a simple form, after submit I use process.php to send back (ajax) errors to index.php using external script.js file and also send mail to the owner of this site,all i need is that the user will also be redirected to a thank-you.html page (if there are no errors of course) but no luck ,I have tried all the combinations suggested:
header("Location: http://www.mywebsite.com/thank-you.html");
header("Location:thank-you.html");
if (success).....
echo
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>
I have tried to put it in the bottom of the process,php ,also in the top of the page also tried to put in the script.js-inside $ajax function but nothing:(((
Can anyone tell me what to do?
solved:
thank you all so much:))))) it should be inside the ajax function in the script , right after success: function(data){ I have placed it in the bottom of the script and it didnt work before but now its perfect!
If you're doing this inside of a jQuery $.ajax() call, use the "success" method instead.
$.ajax({
type: "post",
//etc...
success: function(){
window.location.href="thank-you.html"
}
});
The correct usage in JS is "window.location.href".
Also, a PHP file with "header" being set during an AJAX call won't redirect the client browser.
If I understand correctly you will need to handle the redirect once you get the response from process.php IE: in the success callback.
$.ajax({
success: function () {
window.location.href = 'thank-you.html';
}
});
echo '
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>';
assuming that is from php you were missing quotes.
I handled it a little differently as I handled something similar recently. I have the PHP page echo back "true" (this could also just be an INT) and then run if/else statements in the ajax.
$.ajax({
url : "process.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
if (data == "true")
{
window.location = "http://www.website.com/thank-you.html";}
}

codeigniter ajax firebug shows 200 but display no results

I need a quick help. please help me to figure out the problem.
I have a client's project, that is in codeigniter framework.
my client need an auto complete on their site. i tried best to make it working. everything is ok i write the MVC according to the tutorial.
but my script returns nothing
my view for auto complete
<link rel="stylesheet" href="<?php echo $this->config->item('view_path');?>autocomplete/ui.theme.css" type="text/ css" media="all" />
<script src="<?php echo $this->config->item('view_path');?>autocomplete/1.4.3.jquery.min.js" type="text/javascript"></script>
<script src="<?php echo $this->config->item('view_path');?>autocomplete/1.8.6.jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(this).ready( function() {
$("#postcode").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>home/lookup",
dataType: 'json',
type: 'POST',
data: req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select:
function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
});
</script>
My autocomplete controller is
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Autocomplete extends CI_Controller {
function index()
{
$this->load->view('autocomplete');
}
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->PC_POST_CODE,
'value' => $row->PC_TOWN.' '.$row->PC_POST_CODE,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('autocomplete/index',$data); //Load html view of search results
}
}
}
/* End of file autocomplete.php /
/ Location: ./application/controllers/autocomplete.php */
and Model is also same in example.
when i see in the console of fire bug i see this message but no result.
http://yaashinii.com/maxsurge/tyrechangr/index.php/home/lookup 200 OK 3.28s
site link is you can visit.
http://yaashinii.com/maxsurge/tyrechangr/
I also checks that when i use only a simpe ajax call then the same result as well. and even when i change the controller method to show only the result let say i change the
function lookup(){
echo 'waheed'; exit;
}
even then the same result
http://yaashinii.com/maxsurge/tyrechangr/index.php/home/lookup 200 OK 3.28s
Please help me it is a new kind of issue i didn't understand why it is happend.
I got the solution.
I am visiting this addrss http://www.yaashinii.com/maxsurge/tyrechangr/ but i have define base url in config file of codeigniter as http://yaashinii.com/maxsurge/tyrechangr/index.php/ therefor it becomes a cross domain. and ajax not allow a cross domain access. you can see that i am accessing with www and base url without www.

Resources