Welcome Guest, Not a member yet? Register   Sign In
how to use AJAX in CI
#1

[eluser]Sumon[/eluser]
I like to use AJAX to get State using Zipcode.
Here is my controller

Code:
class Test extends Controller
{
  function Test()
  {
    parent::Controller();
  }
  function StateByZip($ZipCode="40011")
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_URL ,"http://www.shopno-dinga.com/WebService/zipinfo/info_by_zip.php?zip=".$ZipCode);
    $ZipDetail=curl_exec($ch);    // Output: State=KY&City=CAMPBELLSBURG&County=HENRY
    curl_close($ch);
    echo $ZipDetail;
   }
   function ZipCity()
   {
      $this->load->view("view_test_zip");
   }
}
Here is my view file view_test_zip.php. In addition, this file also have AJAX XHLHTTP Request object code.
Code:
function CreateNewHttpObject()    //Create an Instance of HTTP request.
{
    var xmlHttp=null;
    try{      // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
    }
    catch (e){          // Internet Explorer
      try{
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e){
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
     }
     return xmlHttp;
  }
  function ZipState(ZipCode,StateTxt)
  {
    var ObjHttp= new CreateNewHttpObject();
    if(ObjHttp)
    {
      var dataSource = "<?=base_url()?>test/StateByZip("+ZipCode+")";
      ObjHttp.open("GET", dataSource);
      ObjHttp.onreadystatechange = function()
      {
        if (ObjHttp.readyState == 4 && ObjHttp.status == 200)
        {
          var returnVal=ObjHttp.responseText;
          document.getElementById(StateTxt).value=returnVal;
        }
        ObjHttp.send(null);
      }
    }
  }

<input name="zip" type="text" id="zip" onblur="return ZipState(this.value,'state')" value="40011" />
<input name="state" type="text" id="state" value="state" />
My code first create HttpObject which works fine in many other projects (not using CI). After that it calls my test controller’s StateByZip($ZipCode) funciton. Upto this point it works fine but after that i feel, my code can’t call and execute StateByZip($ZipCode) funciton and as such can’t display state value in state box.

Please help me resolve it. Or at least send me an example “how to use CI with AJAX”.
Thanks in Advance.
#2

[eluser]Sumon[/eluser]
I am surprised :O. Really surprised... :O

Just few line changes... Now it works absolutely fine....

Here are the changes...
Code:
First change the function StateByZip first three lines as
function StateByZip()
{
  $ZipCode=$this->uri->segment(3);
  //echo $State=substr($ZipDetail,strpos($ZipDetail,"State=")+6,2); //If you like to receive only STATE.

Secondly inside function ZipState(ZipCode,StateTxt)
change
var dataSource = "<?=base_url()?>test/StateByZip("+ZipCode+")";
by
var dataSource = "<?=base_url()?>test/StateByZip/"+ZipCode; //URL doesn't support parenthesis ( or )
That's all. Now i feel this is a good example of simple AJAX with CI.

I have some idea to improve like:

We can copy and paste the JS code into a JS file and include all veiw pages where we like to integrate AJAX. Isn't it?
#3

[eluser]Pascal Kriete[/eluser]
Glad it works, it feels very static though. What if you want a request to a different page? Instead, turn it into something that's easy to (re)use.

Code:
var ajaxPost = function() {
    
    // Get request object
    function getRequest() {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();
        else if (window.ActiveXObject)
            return new ActiveXObject("Microsoft.XMLHTTP");
        else
            alert('Ajax not supported');
        return null;
    }

    // Basic callback - could add error handler if you wanted
    function handleChange(req, callback) {
        if(req.readyState == 4) {
            if (req.status == 200) {
                if (callback)
                    callback(req.responseText);
            }
            else {
                alert("Ajax request failed.");
            }
        }
    }

    // Create query string from json object
    function handleParams(params) {
        if(!params) {
            return null;
        }
        else {
            var encoded = "";
            for (var field in params) {
                fieldval = params[field];
                encoded += field + '=' + fieldval + '&';
            }
            return encoded;
        }
    }

    // Combine it all in one pretty interface
    return function(uri, callback, data) {
        var request = getRequest();
        request.open('POST', uri, true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.onreadystatechange = function() { handleChange(request, callback) };
        request.send(handleParams(data));
        return request;
    };
}();

Put that in a global js file and use it anywhere:
Code:
ajaxPost(url, callbackFunction, jsonData);

Or just use a javascript library, saves you most of the pain.
#4

[eluser]Sumon[/eluser]
Getting another new problem. The above script works fine in my local host. But not working in my server. How to resolve it? I feel, may be it's happen because of
var dataSource = "<?=base_url()?>test/StateByZip("+ZipCode+")";
This is not working.... Sad

How to resolve it?
#5

[eluser]Pascal Kriete[/eluser]
Load it in your browser and view the source code. What does it say for that line?
#6

[eluser]Sumon[/eluser]
HHHHHmmmmmmmmm it now works fine... Thanks.
#7

[eluser]ranjitbd[/eluser]
[quote author="Sumon" date="1211457062"]I like to use AJAX to get State using Zipcode.
Here is my controller

Code:
class Test extends Controller
{
  function Test()
  {
    parent::Controller();
  }
  function StateByZip($ZipCode="40011")
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_URL ,"http://www.shopno-dinga.com/WebService/zipinfo/info_by_zip.php?zip=".$ZipCode);
    $ZipDetail=curl_exec($ch);    // Output: State=KY&City=CAMPBELLSBURG&County=HENRY
    curl_close($ch);
    echo $ZipDetail;
   }
   function ZipCity()
   {
      $this->load->view("view_test_zip");
   }
}
Here is my view file view_test_zip.php. In addition, this file also have AJAX XHLHTTP Request object code.
Code:
function CreateNewHttpObject()    //Create an Instance of HTTP request.
{
    var xmlHttp=null;
    try{      // Firefox, Opera 8.0+, Safari
     xmlHttp=new XMLHttpRequest();
    }
    catch (e){          // Internet Explorer
      try{
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e){
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
     }
     return xmlHttp;
  }
  function ZipState(ZipCode,StateTxt)
  {
    var ObjHttp= new CreateNewHttpObject();
    if(ObjHttp)
    {
      var dataSource = "<?=base_url()?>test/StateByZip("+ZipCode+")";
      ObjHttp.open("GET", dataSource);
      ObjHttp.onreadystatechange = function()
      {
        if (ObjHttp.readyState == 4 && ObjHttp.status == 200)
        {
          var returnVal=ObjHttp.responseText;
          document.getElementById(StateTxt).value=returnVal;
        }
        ObjHttp.send(null);
      }
    }
  }

<input name="zip" type="text" id="zip" onblur="return ZipState(this.value,'state')" value="40011" />
<input name="state" type="text" id="state" value="state" />
My code first create HttpObject which works fine in many other projects (not using CI). After that it calls my test controller’s StateByZip($ZipCode) funciton. Upto this point it works fine but after that i feel, my code can’t call and execute StateByZip($ZipCode) funciton and as such can’t display state value in state box.

Please help me resolve it. Or at least send me an example “how to use CI with AJAX”.
Thanks in Advance.[/quote]
Code:
// please can you explain briefly following lines
$ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    curl_setopt($ch, CURLOPT_URL ,"http://www.shopno-dinga.com/WebService/zipinfo/info_by_zip.php?zip=".$ZipCode);
    $ZipDetail=curl_exec($ch);    // Output: State=KY&City=CAMPBELLSBURG&County=HENRY
    curl_close($ch)

// and what i have to set for the following line
"http://www.shopno-dinga.com/WebService/zipinfo/info_by_zip.php?zip=".$ZipCode);

//instaed can i call a function from model and and set here the return of the model function?

and rest of the code i understood




Theme © iAndrew 2016 - Forum software by © MyBB