codeigniter ajax firebug shows 200 but display no results - ajax

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.

Related

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.

Having Trouble using AJAX with jquery in Wordpress FrontEnd

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'
},

Wordpress - Admin-AJAX is not saving meta data

Trying to use the built in AJAX functions with the Wordpress Admin. I've been following this tutorial, but when I run the jQuery script, the data isn't being saved to the user meta.
<?php
add_action( 'admin_footer', 'ring_jquery' );
function ring_jquery() {
?>
<script type="text/javascript">
jQuery('.ring-submit').on('click', function(){
var u = jQuery(this).attr('user'),
c = jQuery('.agt_ringc[user="'+u+'"]').val(),
x = jQuery('.agt_ringx[user="'+u+'"]').val(),
formData = 'ringu='+u+'&ringc='+c+'&ringx='+x;
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: formData,
success: function(e){
jQuery('.success[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
},
error: function(){
jQuery('.fail[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
}
});
});
</script>
<?php
} //End ring_jquery()
add_action('wp_ajax_my_action', 'ring_callback');
function ring_callback() {
global $wpdb; // this is how you get access to the database
$ringu = $_POST['ringu'];
$ringc = $_POST['ringc'];
$ringx = $_POST['ringx'];
update_user_meta($ringu,'agt_ringc',$ringc);
update_user_meta($ringu,'agt_ringx',$ringx);
die(); // this is required to return a proper result
}
?>
You will need to have action : my_action in the data string , or as per codex :
var data = {
action: 'my_action',
whatever: 1234
};
Issue was, as #ObmerkKronen pointed out was that I was missing an action definition in the data string (which tells the AJAX page which function to run).
formData = 'action=ring_callback&ringu='+u+'&ringc='+c+'&ringx='+x;
I also changed the name of the action hook to match the name of the function. I don't know if this was necessary, but some other things I found did it and I wanted to fit in.
add_action('wp_ajax_ring_callback', 'ring_callback');

if .get() data same on setInterval do nothing if different reload data

I have a DIV which is populated from $.get data on doc ready, I then call setInterval every 5 seconds. What im trying to do is on success of the setInterval $.get if the html data for #are_friends is the same as before do nothing but if its different then load the data to #are_friends again.
Does anybody have any idea how I would do this or a better way than Im trying to implement.
<div id="are_friends"></div>
<script type="text/javascript">
$(document).ready(function() {
$.get('<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>', function(data) {
$("#are_friends").html(data);
});
var auto_refresh = setInterval(
function ()
{
$.ajax({
url: "<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>",
success: function(newdata){
var oldcontent = $("#are_friends").html();
if(oldcontent != newdata) {
$("#are_friends").html(newdata);
}
}
});
}, 5000); // refresh every 5000 milliseconds
});
</script>
At least, you could reuse the function getting the data like this:
function getData(callback)
{
$.ajax({
url: "<?php echo $siteUrl ?>are_friends.php?userid=<?php echo $userid; ?>",
success: function(newdata){
callback(newdata);
}
});
}
$(document).ready(function()
{
getData(function(data)
{
$("#are_friends").html(data);
});
var auto_refresh = setInterval(function ()
{
getData(function(newdata)
{
if($("#are_friends").html() != newdata) {
$("#are_friends").html(newdata);
}
});
}, 5000);
});
Practically, the initial call and the subsequent call is the same, so why don't reuse it?
That is related a lot to data you are workign with. Right now you are just producing a lot of useless trafic. I would recommend to send also some marker of current state when you are requesting are_friends.php. PHP will check if something changed using that marker and return "no changes" or updated HTML. Here you should lower server load during if nothing is changed and less trafic(suppose most request will return "no changes"). But again. It depends on what you are doing in are_friends.php, what data do you need etc.

Resources