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);
Related
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');
I want to alert the return value from a php method, but nothing happens. Here is the ajax and php methods. Can anyone see what I am doing wrong?
--------------------------------------…
Ajax script
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data');
}
});
--------------------------------------…
php method
function junk($id)
{
return "works11";
}
in PHP, you can't simply return your value and have it show up in the ajax response. you need to print or echo your final values. (there are other ways too, but that's getting off topic).
also, you have a trailing apostrophe in your alert() call that will cause an error and should be removed.
Fixed:
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
PHP:
function junk($id)
{
print "works11";
}
You have an extra ' in there on the alert(data') line
This should work
$.ajax({
type: 'get',
url: '/donation/junk/4',
data: datastring,
success: function(data) {
alert(data);
}
});
And your PHP code should call the method also and echo the value
function junk($id) {
return 'works11';
}
exit(junk(4));
All you're doing currently is creating the method
ajax returns text, it does not communicate with php via methods. It requests a php page and the return of the ajax request is whatever the we babe would have showed if opened in a browser.
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.
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 }} ?>
For some reason this jQuery function is not working properly. Here's my code... the response div is not updating with my response.
WHEN AJAX FUNCTION IS CALLED
if ($action == 'sort') {
echo 'getting a response';
return 0;
}
JQuery FUNCTION
function sort() {
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data:"sort_by=" + document.getElementById("sort_by").value +
"&view_batch=" + document.getElementById("view_batch").value,
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
}
DIV TO REPLACE
<div id="ajaxPhotographSortResponse"></div>
Move the action=sort into the data property of the $.ajax function. You're making a POST request, but appending data onto your query string like a GET request. Data only appends to the query string if it's a GET request.
Example:
$.ajax({
type: "POST",
url: "contributor_panel.php",
data: {action:'sort', sort_by: $('#sort_by').val(), view_batch: $('#view_batch').val()},
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
http://api.jquery.com/jQuery.ajax/
Instead of concatenating the arguments you are passing to your server side script I would recommend you using the following syntax. Also if you already use jQuery you no longer need the document.getElementById function:
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data: { sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() },
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
or even shorter using the .load() function:
$('#ajaxPhotographSortResponse').load('contributor_panel.php?action=sort',
{ sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() });