ajax jquery with codeigniter. url doesnt access controller - php

I am new to codeigniter and cannot get my ajax to work.
I am trying to make links load content into the main document on click.
I looked for instructions but could not figure it out. All works except the ajax returns alert('ERROR') message. nothing is loadded into <div id='load_here'></div>
Maybe I am missing something in config.php? Do i have to load some library for this to work?
Any ideas would be helpfull
//main document link
<span id='reg_link_rules'>Link</span>
<div id='load_here'></div>
// controller
class Register extends CI_Controller {
public function hello()
{
echo 'hello';
}
}
// jQuery
$(document).ready(function() {
$('#reg_link_rules').click(function(eve){
$.ajax({
type: "GET",
url: "register/hello",
complete: function(data){
$('#load_here').html(data);
},
error: function(){alert('error');}
});
});
});
I think the problem is that the ajax url does not access the controller.
Z:/home/codeigniter/www/register/test this is where i think it takes me
problem solved, the url needed to be http://codeigniter/index.php/register/hello

Try with url: "/register/hello".
Might do the trick.
Usually I do a
<script type="text/javascript">
base_url = '<?=base_url()?>';
</script>
At the beginning of my page and simply
base_url+"register/hello"
instead
That makes my ajax more reliable, even when / is incorrect.

complete: function(data){
$('#load_here').html(data);
},
should be
Just referencing another SO question ... Use success() or complete() in AJAX call
success: function(data){
$('#load_here').html(data);
},
AND
$.ajax({
type: "GET",
Should be
unless you want your form vars to be submitted along in the URL.
$.ajax({
type: "POST",

Hello You should add the base url to the URL Ajax.
$.ajax({
type: "GET",
url: <?php echo base_url();?>"register/hello",
complete: function(data){
$('#load_here').html(data);
},
Remember enable the helper URL in the Controller!
Cheers

you need to pass the bas_url to ajax file
<script type="text/javascript">
$(document).ready(function(e) {
var baseurl = <?php echo base_url();?>
$('#reg_link_rules').click(function(){
$.ajax({
url : baseurl+'index.php/register/hello',
data : '',
type: "POST",
success : function(){
}
})
return false;
})
});
</script>

Sometimes you have do add index.php to the string. Like so:
$.ajax({
type: "GET",
url: <?php echo base_url();?>"index.php/register/hello",
complete: function(data){
$('#load_here').html(data);
},
But it's all about your config file however. It was the mistake in my case.
Hope it helps.

You need to ensure two matter
please put your ajax part as url: ?php echo base_url();?>"register/hello", and type: "GET", and also need to check wheter it is routed the url on config/routes.php.

Related

Ajax submit not working

I'll make it easy, I want to submit data without using a form, etc, etc, etc...
I have this code:
HTML
<span class="categ-edit">Edit</span>
<span class="categ-add">Add</span>
<span class="categ-delete">Delete</span>
JQUERY
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
});
window.location.href = "categoryactions.php";
});
$('.categ-add').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'add'},
});
window.location.href = "categoryactions.php";
});
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
});
window.location.href = "categoryactions.php";
});
And in categoryactions.php I have this:
PHP
<?php
$action = $_POST['action'];
echo $action;
?>
But when it redirects me to categoryactions.php I get nothing. I'm not sure if that's the way to submit data with AJAX but at least I tried. If someone knows how to fix this, I'll be grateful!
You click handler is making two separate requests. First, you are sending a request with AJAX, then you are going to the page. When you look at the page, you won't see the result because the result was given to the AJAX request.
The point of AJAX is to avoid changing the page.
Try this:
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
success: function(data) {
alert(data);
}
});
});
You are actually calling "categoryactions.php" twice. First as an asynchronous call (ajax) and the second time as a redirect: window.location.href = "categoryactions.php";
In the 2nd call, nothing is being posted so your output is empty. This line does not serve any purpose - you should remove it.
The ajax call happens in the background so you won't see the output from the echo in the browser. if you really want to verify it is working, replace the echo with a file call to write it to a file. Then check the file contents.
Using redirection with Ajax doesn't make sense. You need to use the success method.
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
success: function(data){
alert(data);
//or, put response in a div
$('#someDivId').html(data);
}
});
});
The point of Ajax is to retrieve the response from a request to another page without changing the URL in the address bar. It retrieves the response for you in the variable that is the input to your success method, and then you do something with that.
Example AJAX with PHP
I can't exactly answer your question, but I will help you understand ajax requests to http server and how to handle responses accordingly.
Sample jQuery
$('.categ-edit').click(function() {
$.get('/path/to/file.php', function(data) {
console.log(data);
});
});
Sample file.php
<?php
echo json_encode('HELLO');

Post variable not passing

Any idea why this doesn't work? I have tried to see if the button clicked actually works with alerts, had alerts as well as before and after the ajax code and they both worked.
var selectedCheckboxes = "12421";
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: "selectedCheckboxes" },
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
the link:
Edit
test.php
<?php
echo $_POST["selectedCheckboxes"];
?>
Try this instead:
Edit
If you want the output of the php in your page you have to do something like this in your javascsript
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: selectedCheckboxes },
success: function(response){
$("body").html(response);
},
error: function(){
// do action
}
});
});
You may need to change the "body" tag.. or not
depends on what the teste.php returns
Well, if you don't want the output to be placed inside your current page html, maybe a different aproach would be better.
Maybe there are better answers but you could try something like:
<form method="post" action="test.php" onsubmit="javascript:$('#selectedCheckboxes').val(selectedCheckboxes);">
<input type="hidden" value="" name="selectedCheckboxes" id="selectedCheckboxes">
<input type="submit" value="Edit">
</form>
You would have to style the submit input
Does the idea help? No ajax though.
The reason you're not seeing the AJAX reqeust go through is because when the you click on the anchor tag, the browser is performing the default action of navigating to 'test.php', which cancels the AJAX call. Since you are simply GET'ing that page, and not POST'ing to it, there is nothing in $_POST. In order to prevent this default action, either use a span instead of an a tag (recommended), or prevent the default action, doing something like this:
Edit
If I get you right, you want to pass selectedCheckboxes as JSON to the Server. In this case you need to actually pass your selectedCheckboxes variable to the Server.
Like this:
$.ajax({
url: "test.php",
type: "POST",
data: selectedCheckboxes,
success: function(response){
//do action
},
error: function(){
// do action
}
});
The problem with your code is that you passed a new JSONObject containing a String that contains "selectedCheckboxes". You did not pass the actual variable.
Put a return false; after ajax call
You try to pass a variable selectedCheckboxes but unfortunately with double ("") quotes you passing a string as selectedCheckboxes
Use below code
var selectedCheckboxes = "12421";
var dataObject = {};
data[selectedCheckboxes] = 1;
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: dataObject ,
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
Hope this helps...

ajax load an external file by passing parameters

Am trying to load an external file to a div using this function
$(document).ready(function(){
$("#postdiv").load('posts.php');
});
This is working alright.
The problem is, I need to pass parameters/variables to posts.php from the caller page and use them to do some filtering.
How can i do this ?
You can pass parameters with jquery load
This method will pass parameter as POST
$("#postdiv").load('posts.php',{'name' : 'Test','age' : 25});
if you want pass it as GET you can do like this
$("#postdiv").load('posts.php?name=Test&age=25');
you can read more here
Use ajax
ajax is better option,best practice.
var value = "value of the data here";
$.ajax({
url: "posts.php",
data: "key="+value,
type: "post",
success: function(data){
$('#postdiv').html(data);
}
});
you can make an ajax call
$.ajax({
url: "posts.php",
data: data,
type: "post",
success: function(data){
$('#postdiv').html(data);
}
});
or you want to go for load then try below code
$( "#postdiv" ).load( "posts.php", { "test[]": [ "test1", "test2" ] } );

PHP AJAX call not retrieving anything

I am trying to retrieve HTML and display it on the page, it doesn't seem to retrieve anything...
My Controller script:
function index()
{
$this->load->view('ajax_post');
}
public function ajaxify()
{
$message = "<b>hello</b>";
echo $message;
}
My javascript code:
$(document).ready(function(){
$("#click").click(
function(){
$.ajax({
type: "POST",
url: "/index.php/ajax_post/ajaxify",
dataType: "html",
cache:false,
success:
function(data){
$("#content").append(html);
}
});
return false;
});
});
any help would be appreciated, as I'm an absolute beginner with jQuery/AJAX
Thanks
Your URL is built wrong; if you see the NET console in Firebug it would show 404 (or 500). Use the helper function in CI (url helper):
$.ajax({
type: "POST",
url: "<?php echo site_url('ajax_post/ajaxify');?>",
dataType: "html",
or build it manually including the domain name:
$.ajax({
type: "POST",
url: "http://www.yourdomain.com/index.php/ajax_post/ajaxify",
dataType: "html",
Be sure the url maps to the correct controller/method (ajax_post.php controller, ajaxify method if no custom route is assigned)
Sidenote, append() appends to the end of the selected element, if you want to insert inside an element use $(selector).html(data); instead
Your Ajax success handler function:
function(data){
$("#content").append(html);
}
Has a parameter named data but then you try to append a nonexistent variable html Try changing it to:
$("#content").append(data);

CodeIgniter/jQuery - Ajax call returns full html page instead of my echo

In my view I have an ajax call:
$(".previous").click(function() {
$.ajax({
type: "POST",
url: "planner/get_cal",
data: {current_month: current_month},
success: function(msg){
alert(msg);
}
});
the get_cal function in my Planner controller:
function get_cal()
{
echo "dinosaurs";
}
However, instead of returning "dinosaurs", it returns a full HTML page. I can't figure out why. Thoughts? Thanks a lot.
I solved this by using a leading slash as suggested in the comments to my question.
$.ajax({
type: "POST",
url: "/planner/get_cal",
dataType: "text",
data: {current_month: current_month},
success: function(msg){
alert(msg);
}
});
You can also get it by adding exit after echo in your php file like below:
function get_cal()
{
echo "dinosaurs";exit;
}
It will work. :)
Try setting the dataType to "text"
$.ajax({
type: "POST",
url: "planner/get_cal",
data: {current_month: current_month},
dataType: "text",
success: function(msg){
alert(msg);
}
});
When using the CodeIgniter structure of Controler/Method uri segments I've found it much easier to use ../../controller/method as my URL's in jquery ajax requests. I also recommend specifying a dataType so that the string is parsed and returned as an object.
Here is an example;
$.ajax({
type: "POST",
dataType: "json",
url: "../../controller/method",
success: mySuccessFunction
});
These type of problem come when your php file and html file are not on proper path so that apache server could parse php files.
Without mentioning type:'text' and any other format also, ajax will work.
But be sure that your server is reaching to php file. Otherwise whole file will be treated as text and returned.
For anyone that is using the Zend Framework, I was experiencing the same issues where the AJAX response was returning the full HTML instead of the json_encode() response. This was resolved by adding the following to my controller:
if ($this->getRequest()->isXmlHttpRequest())
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
Just wanted to mention:
the url will really depend on how you have your .htaccess and folder structure set-up.
So the best way is to try several urls, i.e.:
../../controller/method
../controller/method
server_folder/index.php/controller/method
http://example.com/server_folder/index.php/controller/method
and then choose the one that works best in a given situation.
// Main Page view
$("#button").click(function(e)
{
value=$("#input_value").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>path",
data: "type=get_path_details&mobile="+value,
cache: true,
dataType:"html",
async: false,
success: function(data)
{
$('.apend_new_div').empty().append(data);
$('.scroll_card').css('overflow-x','scroll');
}
});
});
// Controller
public function path()
{
$id = $this->input->post("mobile");
// Some function goes here
// $template[''] = ;
$this->load->view('ajax_page',$template);
}
// ajax view page
<?php if($_POST['type']=='get_path_details'){if(!empty($template)){ ?>
// Html code
<?php }} ?>

Categories