0

Hey guys I am building an application in which I send input value from a text box via AJAX to a controller function and then return what I send back to the user (I am developing an instant search, this is a first step).

The AJAX links to the method fine however I am having problems returning the information. I receive no error messages, the problem is that the return string is BLANK. I receive [you wrote ] rather than [you wrote WHATEVER I IN PUTTED ]

Any help greatly appreciated.

view_index.php

function search(){

var term = document.getElementById("mainsearch").value;

$.ajax({
        type: "POST",
        url: "<?php echo base_url('index.php/site/search/')?>",
        data: term,
        cache: false,
        success: function(html){
            alert("you wrote " + html);
        }
    });

controller_site.php

function search(){
    $gotcha = $this->input->post('term');
    return $gotcha;
}
Blunderfest
  • 1,854
  • 1
  • 28
  • 46
user3760639
  • 73
  • 1
  • 4
  • thanks guys I have made the changes you both suggested, I can now get the variable to print out in the alert box via an echo from the PHP controller but not via a 'return'. – user3760639 Jun 20 '14 at 17:12

4 Answers4

0

The data: parameter accept a key : value json to pass to the POST, as the json array key will be your $_POST key

Try with this:

$.ajax({
    type: "POST",
    url: "<?php echo base_url('index.php/site/search/')?>",
    data: {'term': term }
    cache: false,
    success: function(html){
        alert("you wrote " + html);
    }
});
lracicot
  • 364
  • 2
  • 15
0

You didn't send your data correctly, so PHP has nothing to process, and you end up sending back nothing:

    data: term,

POST/GET requests MUST be in key=value format, and you're sending only the value portion. Try

 data: {foo: term},

and then

 $gotcha = $this->input->post('foo');
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

You need to change return to echo as AJAX response works on whatever echo from called function.

So, you can code like :

function search(){ $gotcha = $this->input->post('term'); echo $gotcha; }

or

function search(){ echo = $this->input->post('term'); }

The responseText property returns the response as a string, and you can use it accordingly

AkshayP
  • 2,141
  • 2
  • 18
  • 27
0

It is generally a bad idea to return HTML from your controllers. Instead try to just manage data server-side wise and do all the frontend on the client side.

Now, for the error:

  1. The success callback takes 3 parameters
  2. You need to pass key-value pair in the data argument of the .ajax call
  3. Make sure you handle errors on your controller appropriately because if something goes wrong you'll get an html document as a response from CodeIgniter and you'll spend a lot of time debugging javascript to find out that the error was actually server-side

1 the callback:

Your success callback function should look like this:

function (data, status, response) {

}

Where:

  • data is whatever you are echoing from your controller's method. You'll probably want JSON.
  • status Will tell you if the HTTP response message (e.g. "Not Found" is the status for a 404 code, "success" for a 200 code)
  • response is the jquery wrapped XmlHttpRequest object that gives you a handful information of the transaction, for example response.responseText would give you whatever you outputed from PHP, response.responseJSON would give you a JSON object if you echoed a json encoded object, etc.

Why should you care? Because those extra parameters will let you decide if something went wrong on your backend so you can handle the situation client-side not leaving the user wondering if you app just don't work. Worse, giving the infamous red cross on the status bar of the browser.

If you set the dataType parameter of the jQuery.ajax function then you can explicitly tell jQuery what kind of data you are expecting to be retrieved from the server on data parameter from your callback.

2 the sent data

As said, you need to either pass value-pairs or a URL encoded string. If you intend to use GET then you can pass the URL encoded string, but that means you have to have arguments on your CI function like:

function search($term)

And then CI automatically routes the incoming parameters. But since you want to do POST then you'll want to effectively get the values with $this->input->post("name")

If you have your input inside a form, or several fields that you need to send, then its easier to just serialize the form:

$.ajax("url", {
    type : 'POST',
    data : $('#form').serialize(),
    dataType : 'json',
    success : function(data, status, response) {}   error : function(response, status error) {}});

3 handle errors

If you are relying on AJAX then make sure that you return some sort of error or warning so you can catch it client side:

function search() {
    $term = $this->input->post("term")
    if($term == FALSE) {
        //return a 404 so that you can catch .error on jquery 
    } else  {
        echo $term;
    }
}

Do a research on RESTFul apps. It'll help you a lot understanding that. this is a good starting point and although your question was not exactly related to this, it is a good practice to have separate layers on your application so that you just consume data from your backend, handle situations and then just react accordingly on the frontend, that is, you just use javascript to either send, receive and list data. If you are using CI or any other MVC framework then you should not really be generating HTML on your controllers, thats what the views are for.

Community
  • 1
  • 1
Gustavo Rubio
  • 10,209
  • 8
  • 39
  • 57