CodeIgniter Forums
Using controller actions using jQuery AJAX? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Using controller actions using jQuery AJAX? (/showthread.php?tid=15577)



Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]littlejim84[/eluser]
Hello there. I'm currently in the middle of making a web app, and it's going pretty well. I've been dipping in and out of CI for a while now, but concentrating on this app has really made CI shine for me. It's absolutely quality!

I'm using jQuery for all the UI stuff and want to use AJAX (for simplicity) with it too. I don't need anything crazy, just basic AJAX stuff.

At the moment, my app lists different things in different views. So, for example, the latest members to the app. This is a list in the members view that is generated. With this, there is options for each row of the data. Options to mark the item as 'read' and bookmark the item for reading later (for example). The buttons are always there, to the right of the row data, either greyed out (if the option hasn't been clicked) or coloured if it has. At the moment, when I click to bookmark John (for example), it goes to a controller called 'bookmark' and passed 'member' and then the id. So the url looks like this : localhost/bookmark/member/32. It runs that and then redirects back the page list I was on. This works great enough...

But I wonder... Is there anyway using jQuery's AJAX to call that controller link and it pass back the value (either 'true' or 'false' for the bookmark item for example). ?? ... If it can be the case where a user clicks on the bookmark button, it'll AJAX that out to the controller, do the action, and then pass back 'true'. Which I will then update the button with the true state using further jQuery?

I'd love to know what commands and techniques would be needed to get this going. Cheers!!!


Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]TheFuzzy0ne[/eluser]
I'm not sure if I understand what you mean, but if I do, there are two methods that I would suggest.

Firstly, you can add functions to your controller which are designed specifically to deal with Ajax requests. You could prefix them with "ajax_".

Secondly, your controller can tell if the request is an Ajax request, by using the following logic.

Code:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'))
{
    // Do Ajaxy stuff
}
else
{
    // Do normal stuff
}

You could move this to a helper function, for example:
Code:
function is_ajax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
}

Then your controller can do something like:

Code:
if (is_ajax())
{
    // Do Ajaxy stuff
}
else
{
    // Do normal stuff.
}

I hope this helps, and that I haven't misunderstood your question.


Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]littlejim84[/eluser]
Tell you what... though it's not completely what I wanted, it's certainly useful stuff. This will really help me keep this app completely degradable. I'm trying to make this web app completely accessible on every level... Image disabled? check... Javascript disabled? check... Want it to be completely accessible to everyone.

So what you told me there, will be useful for sure.

But... It's not even at that level... It's actually what commands do I need to make the controller link for the option to be called by AJAX, rather than just a normal link through. So... at the moment, I click on the option to bookmark the member in the list. Right now, it'll goto the link called 'bookmark/member/32' (for example) and then return me back to the list. The 'bookmark' controller handles calling the right models to make the bookmark happen.

But... I want this controller to be called by AJAX. So the user doesn't leave the page at all. It'll call the same 'bookmark/member/32' but will pass back a 'true' statement (for example) which I can then use to update the list instead.

Hope that makes more sense?? I'm quite a seasoned PHP programmer, but CI, Ajax and jQuery is relatively new to me. Though, these are the tools I'm using.


Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]Colin Williams[/eluser]
Quote:But… I want this controller to be called by AJAX. So the user doesn’t leave the page at all. It’ll call the same ‘bookmark/member/32’ but will pass back a ‘true’ statement (for example) which I can then use to update the list instead.

That's where checking the HTTP_X_REQUESTED_WITH server variable comes in. You can use this to determine what you output from the method, either a full page (non-ajax) or just a simple string like 'true'

Code:
if ($this->input->server('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest')
{
  print 'true';
}
else
{
  $this->load->view($view, $data);
}



Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]littlejim84[/eluser]
Ok. I think I see what this means now. This is cool, think this will work how I want...

So jQuery... using the 'load' command will be the best AJAX approach? Anyone who uses jQuery AJAX in CI - would love to hear from you! (like I say, AJAX, jQuery and CI is all relatively new to me...)


Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]Colin Williams[/eluser]
$.load() is good if you just need to grab some content. $.ajax() is more robust and is typically what I shoot for.

Code:
$.ajax(
   {
      type: 'get',
      url: '/bookmark/user/32',
      success: processAjax,
      error: showError
   }
);

// ...

function processAjax(data, status)
{
   if (data == 'true')
   {
      // Things went well...
   }
   else {
      // There was an error
   }
}

function showError(XMLHttpRequest, textStatus, errorThrown)
{
   // There was an error with the request
}



Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]littlejim84[/eluser]
That is awesome.

Just what I needed... Seeing the structure like that has made it all clear now. Thank you kindly!


Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]xwero[/eluser]
TheFuzzy0ne showed you the right way but maybe it is a bit too vague.
Code:
// do the bookmarking
if (is_ajax())
{
    // return the output of the bookmarking
}
else
{
    // redirect
}
The base of the method stays the same but the action after the manipulation changes. For the ajax function you only need to output status of the bookmark to alter the state of the bookmark link while in php you have to reload the whole page to alter the state of the bookmark link.
The code part in php that makes a difference in the state needs to be ported to javascript for ajax.
Code:
// view
foreach(members as member)
{
    echo '<a href="bookmark/member/32">'
    echo ($member['is_bookmarked'])? '<img src="bookmarked.png">':'<img src="not_bookmarked.png">';
    echo '</a>'
}
// javascript
$('a').click(function(){
var href = $(this).attr('href');
$.ajax({
   type: "GET",
   url: href,
   success: function(msg){ // i assume plain text output
     if(msg == 'true')
     {
        $('img',this).attr('src','bookmarked.png');
     }
     else
     {
       $('img',this).attr('src','not_bookmarked.png');
     }
   }
});
return false; // prevents link from executing
});



Using controller actions using jQuery AJAX? - El Forum - 02-09-2009

[eluser]littlejim84[/eluser]
Nice! That's a great reply too... Thank you very much.

It looks like all of this can play nicely together... Definitely made the right choice for my web app I reckon... PHP, MySQL, CI, jQuery... GREAT combination!