简体   繁体   中英

Ajax request in Codeigniter

I have been trying to create an ajax request in codeigniter. I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript . I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed.

So here are my questions:

  1. Is it really possible to use PHP inside Javascript, or am I mistaken?
  2. What's the right way to perform an Ajax request in Codeigniter ? What I've tried is the following:

var param = {name : event_name, date : event_date, time : event_time};

            $.ajax({
                // As seen from the question here at stackoverflow.
                url : "<?php echo base_url('event/new_event'); ?>",
                type : 'POST',
                data : param,
                beforeSend : function(){ },
                success : function(){
                    alert("Event created! Feel free to add as much details as you want.");
                    namebox.val("");
                    $("#new-event-modal").find(".close").trigger('click');
                    window.location.href = "<php echo base_url('user/dashboard'); ?>";
                },
                complete : function(){ },
                error : function(){ }
            });

I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!!

the easiest way for you to accomplish this is by using some jquery:

function getBaseUrl() {
    var l = window.location;
    var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
    return base_url;
}

var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";

$.post(url, postdata, function(result){
  ...alert(result);
});

or call it straight from JS by caching it:

<script> 

    var test = "<?php echo base_url(); ?>"+"event/new_event";
    alert(test);

</script>

Here is a dirty hack that I was going to use:

  1. Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field .
  2. Now when you want to make an ajax request, access that hidden field and grab the base url and use it however you want.

The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it.

This is your controller

<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {

    public function ajax_echo()
    {
        // get the ajax input
        $input = json_decode(file_get_contents('php://input'));

        // $input can be accessed like an object
        $password = $input->password;
        $name = $input->name;

        // you can encode data back to JSON
        $output = json_encode($input);

        // and the response goes back!
        echo($output);
    }
}
?>

This goes into your client

<script>
    // here's the data you will send
    var my_data = {name: "Smith", password: "abc123"};

    // create the request object
    var xhr = new XMLHttpRequest();

    // open the object to the required url
    xhr.open("POST", "example_ctrl/ajax_echo", true);

    // on success, alert the response
    xhr.onreadystatechange = function () {
        if (xhr.readyState != 4 || xhr.status != 200)
            return;
        alert("Success: " + xhr.responseText);
        };

    // encode in JSON and send the string 
    xhr.send(JSON.stringify(my_data));
</script>

There is no better way to do this .

Php codes can't be executed from external javascript files.

Try any of these :-

1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code

2) you can store the same base_url() in local storage , it will be available in your external JavaScript files

Hope it helps you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM