Learning how to use AJAX with CodeIgniter - php

It's kind of embarassing that I find it so difficult to learn JavaScript, but ..
Let's say I have a really simple controller like this:
class front extends Controller {
public function __construct()
{
parent::Controller();
}
public function index()
{
//nothing!
}
public function test () {
$someNumber = $this->input->post('someNumber');
if ($someNumber == 12) { return TRUE; }
}
}
Yes, that could probably be written better, haha.
What I want to know is - how could I use JavaScript to submit a number in a form (I'll worry about validation and models later), how should I write my test() function so that it returns something readable by the JavaScript (I'm assuming return TRUE probably wouldn't work, perhaps XML or JSON or something like that?), and how do I access the data with the JavaScript?
I know there are frameworks like jQuery that will help with this, but right now I'd just like to understand it at the simplest level and all the tutorials and guides I've found so far are way too in depth for me. An example in jQuery or whatever would be good too.
Thanks a lot :)

you would just print it out basically, and re-capture that information via javascript:
public function test() {
$somenumber = $this->input->post('someNumber');
if ($somenumber == 12) {
print "Number is 12";
} else {
print "Number is not 12";
}
}
your javascript might look something like this:
var xhr;
xhr = new XMLHTTPRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// this is where the return information is
alert('Status: '+xhr.status+' Response: '+xhr.responseText);
}
}
xhr.open('POST', '/front/test');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('someNumber=12');
the code above doesn't take into account browser specific issues, but should run on firefox/ie7 at least i believe.
here's a jQuery example of all the above:
var options = {
'someNumber' : 12
}
$.post('/front/test', options, function(data) {
alert(data); // should print "Number is 12"
});

I've also found in CodeIgniter that 'XMLHTTPRequest' isn't returned in the response headers, when using the standard Javascript AJAX call as mentioned above.
$this->input->is_ajax_request();
The input helper doesn't ever return true unless you use jQuery to handle the AJAX POST request.
I also tried the method in this article which didn't work: http://developer.practicalecommerce.com/articles/1810-The-Benefit-of-Putting-AJAX-and-CodeIgniter-PHP-Together
This is what I used in the end:
var query_params = $('#data-form').serialize();
$.ajax({
type: 'POST',
url: 'process_this.php",
data: queryParams,
context: document.body,
success: function(){
alert('complete'); // or whatever here
}
Possibly caused by a config issue to do with my CI install, haven't had time to investigate yet.

Related

call php function with arguments using Jquery

I have a php file func.php where I defined many functions let's say :
<? php
function func1($data){
return $data+1;
}
?>
I want to call the function func1 using ajax. thank you for your help
You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});
You should call your php script through an ajax request, using jQuery like:
Javascript:
$.ajax({
url: "script.php",
data: { param1: "value1", param2: "value2" },
type: "GET",
context: document.body
}).done(function() {
// your code goes here
});
You could give your parameters through data property of ajax object.
Php
// you can do isset check before
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// validate // sanitize // save to db // blah blah // do something with params
More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/
It's a bit more complicated, but I will try to shrink it down to the basics.
You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:
The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.
The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.
Add the following code along with your functions:
if(isset($_GET['func']))
{
$func=$_GET['func'];
if(function_exists($func))
{
$args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
$result=call_user_func_array($func,$args);
}
else
$result=array('error'=>"Unknown Function $func!");
}
else
$result=array('error'=>"No function name provided!");
echo json_encode($result);
However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.
Your example function, for instance, should look something like this:
function func1(){
$data=func_get_args();
if(count($data)) // at least one -- rest will be ignored
return $data[0]+1;
else
return array('error'=>__FUNCTION__."() expects an argument!");
}
Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.
Yes you can !
here my code :
$.ajax({
type: "POST",
url: "ajax.php",
data: { kode: $(this).val(), func: 'my_func' },
success: function(response) {
//any success method here
}
});
and here the code in php to receive what function to call.
$post = (object) $_POST;
if(!$post)
return false;
$func = $post->func;
return $func($post);
function my_func($post) {
$json['any_data'] = false;
if($post->kode == 'ND'){
$json['any_data'] = 'ND-'.date('Y');
}
echo json_encode($json);
}
Hope it help you out bro... :D

javascript to post to url and

I am writing a javascript which will post hostname of the site to a php page and get back response from it, but I don't know how to assign the hostname to adrs in url and not sure that code is correct or not.And this needs to done across server
javascript:
function ursl()
{
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
success: function (response)
if (response)=='yes';
{
alert("yes");
}
});
}
track.php
$url=$_GET['adrs'];
$sql="SELECT * FROM website_ad where site='$url'";
$res=mysqli_query($link,$sql);
if(mysqli_num_rows($res)==0)
{
echo"no";
}
else
{
echo"yes";
}
Your ajax function should be written thusly:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=' + window.location.hostname,
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
window.location.hostname will give you the host name. You are passing it to the ajax url by concatenating it. Alternatively, as katana314 points out, you could pass the data in a separate parameter. Your ajax call would then look like this:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
data: {adrs: window.location.hostname},
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
I'm not sure what you intend response to be, but this code assumes it is a string and will match true if the string is 'yes'. If response is meant to be something else, you need to set your test accordingly.
$.getScript() will load your external script, but since it's asynchronous you'll have to put any code that is dependent on that in the callback.
In this type of GET request, the variable simply comes after the equals sign in the URL. The most basic way is to write this:
url: 'http://example.com/en/member/track.php?adrs=' + valueToAdd,
Alternatively, JQuery has a more intuitive way of including it.
$.ajax({
url: 'http://example.com/en/member/track.php',
data: { adrs: valueToAdd }
// the rest of the parameters as you had them.
Also note that you can't put a script tag inside a script. You will need some other way to run the Javascript function mentioned; for instance, wrap its contents in a function, load that function first (with a script tag earlier in the HTML), and then call it on success.
And for the final puzzle piece, you can retrieve the current host with window.location.host
You'll need to change this line to look like so:
url: 'http://example.com/en/member/track.php?adrs='+encodeURIComponent(document.URL)
The full success function should look like so:
success: function (response){
if (response==="yes"){
//do your thing here
}
}
That should solve it...

Accessing a PHP class function through AJAX

Does anyone know how I can directly access a function from a PHP class through AJAX (using jQuery).
PHP:
class Blah
{
function __construct()
{
}
function doSomething(data)
{
echo "I am not an animal";
}
}
jQuery:
$.ajax({
url: myClass.php,
data: Blah.doSomething(); "or" Blah->doSomething() "or whatever"
});
I know this is a crude example, i'm just trying to illustrate a point, I hope you can get the gist of my question.
At the moment i'm doing something along these lines:
$.ajax({
url: myClass.php,
data: data : { 'type':'doSomething' }
});
||
if(POST['data']['type'] == 'doSomething')
{
$this->doSomething();
}
And I don't like it...
You need to create an object of that class and then invoke the methods you need.
The class declaration doesn't not execute any code.
For example, you can add this below the class:
class Blah { ... }
$b = new Blah();
$b->doSomething();
UPDATE:
If you want to invoke the method sent in POST, you can use the function call_user_function:
$method_name = $_POST['method'];
$b->{$method_name}();
See here more details: http://php.net/manual/en/function.call-user-func.php
i don't know why do you like to do so.
its not a good programming practice.
but you can try something like this
$.ajax({
url: myClass.php,
data: {'call':'Blah.doSomething', 'args':5}
});
and in server side you can do like
$fun = explode('.', $call);
$function = array($fun[0], $fun[1]);
if (is_callable($function)) {
$response = call_user_func_array($function, $args);
}
echo $response;
Right now I can't think of any better way than PHP outputting results in json and you get the result via getJSON
I concur with mazzucci's answer. I hope this is a bit more complete.
PHP:
class SomeClass{
//definintion
}
$obj = new SomeClass();
$obj->doStuff();
HTML:
<input type="button" onclick="<?php $obj->doStuff(); ?>" id="btnAdd" value="Click Me" />
Also, you can look into xajax, a nice little framework that simplifies php<->javascript interaction. It can call js functions from php as well. Here's the link: http://www.xajax-project.org/en/home/
**Your class**
class Blah {
function doSomething(data) {
echo "I am not an animal, I'm a ".data;
}
}
**Ajax call in other document**
$.ajax({
url: example.php,
data: info='beast'
success: data () { ...
});
**in example.php**
include (class.blah.php);
$obj = new SomeClass();
$obj ->doStuff($_GET['info']);
It's not possible. What you currently have is probably the best way.

Reverse Ajax implementation using php

I am looking to implement reverse ajax in my application which is using PHP and jquery. I have googled a bit about it and found XAJA but that seems to be a paid application. Is there an open source application available for the same or has someone implemented it?
Some pointers or hints would be very helpful.
Thanks in advance.
I know of two types of reverse AJAX:
1- Polling
2- Pushing
I think polling is rather easier to implement, you just have your javascript make a regular request to the server every time interval, and when the server have some data for it it will respond. Its like a ping and some call it heartbeat, but its the very obvious solution for this problem. However it may easily overload the server.
EDIT Simple polling Example code:
Server-Side:
<?php
//pong.php php isn't my main thing but tried my best!
$obj = new WhatsNew();
$out = "";
if ($obj->getGotNew()){
$types = new array();
foreach ($obj->newStuff() as $type)
{
$new = array('type' => $type);
$types[] = $new;
}
$out = json_encode($types);
}
else{
$out = json_encode(array('nothingNew' => true));
}
Client-Side:
function ping(){
$.ajax(
{
url : "pong.php",
success : function (data){
data = JSON.parse(data),
if (data['nothingNew'])
return;
for(var i in data){
var type = data[i]['type'];
if (type && incomingDataHandlers[type]){
incomingDataHandlers[type]();
}
}
});
}
incomingDataHandlers = {
comments: function () {
$.ajax({
url: "getComments.php",
method: "GET",
data: getNewCommentRequsetData() // pass data to the server;
success : function (data){
//do something with your new comments
}
});
},
message: function (){
$.ajax({
url: "getMessages.php",
method: "GET",
data: getNewMessageRequestData() // pass data to the server;
success : function (data){
//do something with your new messages
}
});
}
}
$(docment).ready(function () {
setInterval(ping, 1000);
})
You are looking for what they call "long poll" - I did a "long poll php" and I got this thread on stack overflow:
How do I implement basic "Long Polling"?
you could websockets in conjuction with "flash" websockets because almost all browser have flash on board(average around 96%? => http://www.statowl.com/flash.php) => https://github.com/gimite/web-socket-js. You could use this together with http://code.google.com/p/phpwebsocket/. Still I am wondering if the performance is going to be any good. If it all possible I would use node.js to do reverse ajax. http://socket.io is a really cool project to do this!
Have you checked APE ?
Its a push based real-time data streaming technology over a single low volume ajax connection. The concept is useful, you may be able to replicate the same thing with your server-side implementation

Load PHP function with jQuery Ajax

I have a file which is loaded at the top of my document, which is called Videos.php. Inside that file are several functions, such as getYoutubeVideos. On some pages, I need to call upon that function several times (up to 50), and it of course creates major lag on load times. So I have been trying to figure out how to call that function in, only when it is need (when someone clicks the show videos button). I have very little experience with jQuery's ajax abilities. I would like the ajax call to be made inside of something like this:
jQuery('a[rel=VideoPreview1).click(function(){
jQuery ("a[rel=VideoPreview1]").hide();
jQuery ("a[rel=HideVideoPreview1]").show();
jQuery ("#VideoPreview1").show();
//AJAX STUFF HERE
preventDefault();
});
Ok I have created this based on the responses, but it is still not working:
jQuery Code:
jQuery(document).ready(function(){
jQuery("a[rel=VideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").hide();
jQuery("a[rel=HideVideoPreview5]").show();
jQuery.post("/Classes/Video.php", {action: "getYoutubeVideos",
artist: "Train", track: "Hey, Soul Sister"},
function(data){
jQuery("#VideoPreview5").html(data);
}, 'json');
jQuery("#VideoPreview5").show();
preventDefault();
});
jQuery("a[rel=HideVideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").show();
jQuery("a[rel=HideVideoPreview5]").hide();
jQuery("#VideoPreview5").hide();
preventDefault();
});
});
And the PHP code:
$Action = isset($_POST['action']);
$Artist = isset($_POST['artist']);
$Track = isset($_POST['track']);
if($Action == 'getYoutubeVideos')
{
echo 'where are the videos';
echo json_encode(getYoutubeVideos($Artist.' '.$Track, 1, 5, 'relevance'));
}
$.post('Videos.php', {
'action': 'getYoutubeVideos'
}, function(data) {
// do your stuff
}, 'json');
In your php code, do something like this:
$action = isset($_POST['action'])? $_POST['action'] : '';
if($action == 'getYoutubeVideos')
{
echo json_encode(getYoutubeVideos());
}
Then data in your JavaScript function will be the array/object/value returned by getYoutubeVideos().
I would do the JS part like ThiefMaster describes, but the php part would i handle a little bit different.
I would do something like this:
if(isset($_POST['action'], $_POST['par1'], $_POST['par2'])
{
$action = $_POST['action'];
$result = $this->$action($_POST['par1'], $_POST['par2]);
echo json_encode(result);
}
But be careful, if you have some methods in the class which shouldn't be called by the user, trough manipulating POST data, then you need some way to whitelist the methods the JavaScript may call. You can do it by prefixing the methods i.e:
$this->jsMethod.$action(....);
or by simple if/switch condition.
Ok here is what ended up working:
PHP CODE
$Action = isset($_POST['action']);
if($Action == 'getYoutubeVideos')
{
getYoutubeVideos($_POST['artist'].' '.$_POST['track'], 1, 5, 'relevance');
}
JQUERY
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist=artist&track=track",
success: function(data){
jQuery("#VideoPreview1").html(data);
}
});
json encoding was annoying, not sure if json is hte better way of doing it, I could actually use the jQuery.post function as well, because the real problem was with the PHP. If anyone knows about any security problems with the method I am doing, please let me know. Seems fine though.

Categories