Posting Ajax data to Controller function?
In my PHP/jQuery application, I have a javascript file, in which I can call an external PHP file (post_data.php) like th开发者_运维问答is:
$.ajax({
type: "POST",
data: "some data",
url: "post_data.php",
Now, instead of calling php file, i would like to call a CodeIgniter contoller function Data/post_data
, so how can I call that function instead of post_data.php
?
The javascript file in which i would like to call is located:
root/js/test.js
while the function is located here:
root/application/controllers/data/post_data
The ajax need to have a full url:
$.ajax({
type: "POST",
data: "some data",
url: "http://www.yourdomain.com/urpath/post_data"});
The reason is the Javascript file that call the Ajax is not aware of the server location of the .php file. So, by using the absolute path you make sure that your call will be done. Also, to test it before using the Javascript file, copy and paste the url into your browser. If no 404 error is displayed, than you have your good path.
To add to Doaks response, you can also do it like this
$.ajax({
url: "<?php echo site_url('data/post_data'); ?>",
type: "POST",
data: data,
You can use $.post() JQuery function it's more simple and optimized for POST request. Also for routing, you can set just controller and method. It's enought.
$.post("admin/newphone", {
phone: $('input[name="phone"]').val()
},
And link to JQuery docs http://docs.jquery.com/Post
精彩评论