Can somebody please explain to me what is the right way to call a php function with jquery / ajax in Codeigniter. Right now, this code isn't working and i cant figure out whay. Note that admin.php controler is inside admin map. Thanks in advance
html code
<form action="#" method="POST" id="change">
<input type="hidden" value="<?php echo $row->id_product; ?>" id="prod" >
<input type="submit" value="switch" >
</form>
<div class="resultdiv">
<?php echo $data; ?>
</div>
my function inside admin.php controller
public function do_search(){
$id = $this->input->post('id');
return $id;
}
Jquery AJAX script
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'admin321/do_search',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Config / routes.php
$route['admin/do_search'] = "admin_controller/admin/do_search";
I know that this is old post, but maybe someone will find this usefull.
I solve this problem by adding index.php in url. Even if the index.php is hidden using rewrite.
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("index.php/admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
Maybe like this:
$( "#change" ).submit(function() {
alert( "Change" );
var id = $('#prod').val();
$.ajax({
type:'POST',
url:'<?php echo base_url("admin/do_search"); ?>',
data:{'id':id},
success:function(data){
$('#resultdiv').html(data);
}
});
});
You have to load this helper:
$this->load->helper('url');
#edit
$route['admin/do_search'] = "admin_controller/admin/do_search";
This code is unnecessary.
In the past, I have set up a route for the ajax request. Something like this:
$route['admin/search/(:any)'] = 'admin_controller/admin/do_search/$1';
Then my ajax request would look like this:
var prod = $('#prod').val();
$.ajax({
type: 'post',
url:'admin/search/'+prod
...
});
Or, you can grab the form action via jQuery and use that as your url.
<form action="admin/search/123" method="post">
$.ajax({
type: 'post',
url: $('form').attr('action')
...
});
I know this works. My routes file is the default.
I loaded CI URL helper in my controller __construct() function
$this->load->helper('url');
Here's my ajax:
/*
*Ajax function to load confirmation page
*/
var formID=$("div form");
formID.submit(function(event){ //activated on submit event
event.preventDefault(); //stops page from reloading
$.ajax({
type:"POST",
url:'<?php echo site_url("plan/process")?>',
data:formID.serialize(),
success:function(data){
$("div #msg_area").html(data);
window.setTimeout(function(){parent.location.reload()},3000);
}
});
});
I have multiple controllers so it calls the specific one call plan and the \n the function process. The process function one looks like this:
function process (){
$json_data = strtolower(json_encode($this->input->post()));
$res = array();
//Simple Error/success display...
$res = json_decode($this->plan->process_plan($json_data ),true);
if(array_key_exists('error',$res)){
$window = "warning";
$error=explode(":",$res['error']);
$result['message']="<h2><span class='color-dark'>Submission error:</span> ".$error[0]." </h2><p>".$error[1]."</p>";
}
else{
$window = "success";
$result['message'] = "<h2>Submission was a success</h2>";
}
echo $this->load->view("common/components/".$window,$result);
}
This works great for me. Hopefully it helps.
in your routes file you have: admin321/do_search NOT: admin/do_search
You can also try using the absolute path:
`http://www.website.com/admin/do_search` or `http://localhost/admin/do_search`
in the ajax url parameter
Related
View File product_grid
<div data_id="<?php echo $ro['category_id']; ?>" name="id" class="cbp-filter-item">
<?php echo $ro['category_name']; ?></div>
// try to post data using ajax
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>.index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
Hear i can pass the id to view but not work properly please help me to solved this problem
Controller ::
public function product_grid()
{
$id= $this->input->post('id');
}
You must have to use print or echo otherwise there will be no response sent to client side so use echo like,
public function product_grid(){
$id= $this->input->post('id');
echo 'Data-Id is: '.$id;
}
And use the URL like,
url:"<?=base_url()?>index.php/Home/product_grid", // let there is / in the end of base_url()
AJAX Code,
jQuery.ajax({
url:"<?=base_url()?>index.php/Home/product_grid",
type:'POST',
data: {id:id}, // no need of quotes to JSON Object keys
success:function(data) {
alert(data);
}
});
<script type="text/javascript">
$(document).ready(function() {
$('.cbp-filter-item').click(function(){
var id=$(this).attr('data_id');
// alert(data_id);
jQuery.ajax({
url:"<?=base_url()?>+index.php/Home/product_grid",
type:'POST',
data: {"id":id},
success:function(data) {
alert(data);
}
});
});
});
</script>
url:"<?=base_url()?>+index.php/Home/product_grid"
Use + for concatination instead of .
I am a ajax beginner, Here I am trying to show a text box value in same page using Ajax.
My Controller code:
<?php
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
$this->load->view('ajaxtest');
$fullname = $this->input->post("fullname");
echo $fullname;
}
}
?>
Here is my view code:
<head>
<script src="<?php echo base_url();?>assets/js/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" id="fullname"/>
<input type="button" value="getinfo" id="getinfo"/>
<span id="mytext"></span>
</form>
</body>
When I click on the button getinfo, I want to show the text inside the text box as span text. But now it shows nothing..
Updated:
After experts' opinion, I edited some text(see my edit note), Now When i click on the button, it shows again a textbox and a button.. !!
Did you set the base_url variable with a link on the Javascript?
Because your post url contains this variable and you need set this to make it work. So initialize the variable with the base_url link.
See the corrected example below . Set your domain instead of the yourbaseurl.com
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Your base_url variable seems to be undefined in your JavaScript.
One simple approach to get the base URL is to echo it out in a hidden input, and then grab the value of that input in your JS code:
HTML
<input type='hidden' id="baseUrl" value="<?php echo base_url(); ?>" />
JS
var base_url = $('#baseUrl').val();
$.ajax({
type: "POST",
url: base_url + "/merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
// ...
you are passing in textbox as parameter from your ajax to controller and trying to get POST data with name fullname. That wont work, since you passed in the name of parameter as textbox, access that in your post, as :
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
//you dont need to load view so comment it
//$this->load->view('ajaxtest');
$fullname = $this->input->post("textbox"); //not fullname
echo $fullname;
}
}
js
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function() {
var fullname = $("#fullname").val();
alert("Fullname:" + fullname); //do you get this alert
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: fullname},
cache:false,
success:function(data){
alert("Response:" + data); //do you get this alert
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Try using this:
<base href="<?=base_url();?>">
<script src="assets/js/jquery-latest.min.js"></script>
And this in ajaxtest:
$this->load->helper('url');
And also Comment out this:
// $this->load->view('ajaxtest');
Might be a little late with this response - but someone might find this while searching for a solution.
I was having the same issues with Codeigniter and JQuery ajax/post response. I could not get this to work no matter what I tried.
In the end, it turned out to be php_error that was causing the problem. Once I removed it, everything worked fine with my post/response.
I don't understand javascript,AJAX very well and need to do this code fast, so if you guys can help, it would be great !
I have a like button on my webpage that allows users to like content:
The html code is as follows:
<form action=\"\" method=\"post\" enctype=\"multipart/form-data\"><button name=\"like$i\">like</button></form>
And the php code:
for ($i = 100; $i >= 0; $i-=1) {
$primid = latest1($i);
$id = $user_data['id'];
if(isset($_POST["like" . $i]) && already_liked($id, $primid)===false) {
add_like($id,$primid);
}
if(isset($_POST["like" . $i]) && already_liked($id, $primid)===true){
echo "you have already liked this art";
}
}
All of the code works fine, but when I click the like button; the page refreshes wich is not ideal ...
I know you can use AJAX to fix this problem; i have looked for answers but they all seem to be for forms with content to insert ect ...
I'm sorry if i seem lazy but i have to finish this fast and don't have time to learn ajax properly for the moment :S
Thanks in advance =)
Observe the following code:
jQuery.ajax({
url: '/some/file.php', //link to your php
method: 'POST', // Method, you can use GET too
data: $('#the-form').serialize() //get form values
}).done(function (response) { //works if response is success
// Do something with the response
}).fail(function () { //works if response is fail
// Whoops; show an error.
});
You can do something like this:
HTML
<form action="" method="post" id="likeForm" onsubmit="return false;">
<input type="submit" name="like<?php echo $id; ?>" value="Like" />
</form>
Sidenote: onsubmit="return false;" is used to prevent uncaught exception: out of memory error in ajax.
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#likeForm').submit(function(){
var value = $(this).children().attr('name');
var param = {value: value};
$.ajax({
type: 'POST',
url: 'yourpage.php', // change this yourpage.php to point to a page where you want to process your ajax request
cache: 'false',
data: param,
beforeSend: function(){
// before send
},
success: function(data){
// success
},
error: function(){
// error
}
});
});
});
</script>
yourpage.php
<?php
for($i = 100; $i >= 0; $i-=1) {
$primid = latest1($i);
$id = $user_data['id'];
if(isset($_POST['value']) && $_POST['value'] == "like" . $i && already_liked($id, $primid)===false) {
add_like($id,$primid);
}
if(isset($_POST['value']) && $_POST['value'] == "like" . $i && already_liked($id, $primid)===true){
echo "you have already liked this art";
}
}
?>
Just to compile the all things that you need:
JavaScript code:
function submitFormData(inputForm) {
jQuery.ajax({
url: '/some/file.php', //link to your php
method: 'POST', // Method, you can use GET too
data: $(inputForm).serialize() //get form values
}).done(function (response) { //works if response is success
// Do something with the response
}).fail(function () { //works if response is fail
// Whoops; show an error.
});
}
Html code:
<form action="" method="post" enctype="multipart/form-data">
<button type="button" onclick="submitFormData(this.form);" name="like$i">like</button>
</form>
Good luck with task implementation.
I'm currently doing an ajax add,update and delete. And I think I'll just start with the delete since it is the easiest and hope that it might help me in the others.
In jquery (this is inside $doc.ready and the event is triggered properly)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
in html
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
In controller
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
This is already working but then I am planning on making the crud to ajax. I'm trying to pass the postid from ajax to controller to delete this post. The fadeout already works but only the ajax does not. I'm very new to ajax so I do not know where I am going wrong and I might also ask questions again regarding the other parts of crud.
Fixed!
The problem was the url inside the $.ajax. It returns a garbage.
So I added a script in the header
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
And just use BASE_URL in the url: like so url: BASE_URL+'classes/deletepost',
Please Try to follow this:
In Codeigniters View:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
in controller:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
EDIT:
This is what i managed to build...but it still dont work..
$(document).ready(function(){
$("tr").click(function(){
txt=$("input[name=path]").val();
$.ajax({
type: "POST",
url: contract.php, // the same page where i have the table
data: txt, // the variable containing the dynamic id from the clicked row
success: success, // i have no idea what is this parameter for....
dataType: dataType // i have no idea what is this parameter for....
});
});
});
PHP:
$row=mysql_fetch_array($query){
echo '<tr id="'.$row['id'].'">';
echo '<td></td>';
echo '</tr>';
}
What i want,is when the user click on a row , the row id(which is dynamic), must be taken , and returned with ajax post , so i can use it in another query.I have to do this without reloading the page, thats why i try to do it with ajax.
If it's ok to use jQuery i would use something like this to build my table (beside the mysql_*):
<?php
$row=mysql_fetch_array($query){
echo '<tr class="listContractRow" data-path="'.$row['id'].'">';
echo '</tr>';
}
?>
Then catch the click event with a jQuery listener:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).on('click','tr.listContractRow', function(e){
var path = $(this).data('path');
//Use the variable path here in your AJAX call
//Assuming you want a GET request, you can also use $.ajax or $.post here
$.get('YOUR_AJAX_URL_HERE?path='+path, function(){
//Do something after the ajax call
});
});
</script>
EDIT
In your PHP you can do something like:
<?php
if(isset($_GET['path']))
{
//Query here with the variable $_GET['path'];
//Echo the results you want
//Perform an exit here, since it's an AJAX call. You probably don't want to echo the code below (if there is)
exit();
}
?>
jquery ajax get example
$.ajax({
type: "POST",
url: "index.php",
data: "{param: "param"}",
success: function(msg) {
},
error: function(err) {
}
});