codeigniter sending a variable from ajax to controller - javascript

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');
}

Related

Ajax - send button value to php

I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
</script>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
PHP:
<?php
$name = $_POST['data'];
echo $name;
?>
It doesn't working...
try this out, i just did and worked fine
here's my js file
<html>
<head>
</head>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
<footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function() {
var val = $(this).val();
$.ajax({
// your uri, pay attention if the post is going to the right place
url: "try.php",
type: "POST",
// myVar = name of the var that you will be able to call in php
// val = your data
data: {'myVar': val}
});
});
});
</script>
</footer>
</html>
and here's my php
<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses
Make proper json string to send data. You are having extra ; there.
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
And get it with data key in php.
<?php
$name = $_POST['data'];
echo $name;
?>
Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.
<button id="example" name="name_example" value="some_value">
1</button>
$(document).ready(function () {
$('#example').click(function() {
var buttonValue = $(this).val();
$.ajax({
url: "try.php", //assuming that your html file is in the same folder as
//your php script.
type: "POST",
data: {'example': buttonValue}
});
});
});
look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/
In your .php file, which should be in the same folder as your html file doing the request you will have:
<?php
echo '<pre>'; print_r($_POST); die; // see if you now have those vars.
?>

Post data to current php page with ajax

i want to post data to current page with ajax.But i couldnt do that.
I have doctor panel and i wanna get patient's data from 'hastalar' table in my db by using patient's national id:'tc'.Session is using by doctor so i guess i cant use $_SESSION for patient at same time.And i wanna use only one php page.So i cant see my patient's datas in current page.Pls help me guys.
dokyon.php
textbox
<a href="#" id="ara" class="ara" ><br/>SEARCH PATIENT</a>
<input type ="text" id="tc" name="tc" />
JQUERY
<script type="text/javascript" >
$(function() {
$(".ara").click(function(){
var tc = $('#tc').val();
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
success: function(){
alert(data);
}
});
});
});
</script>
php codes
<?php
$tc=$_POST['tc'];
echo $tc;
$query = mysqli_query($connection,"select * from hastalar where tc_no=$tc");
while($hasta = mysqli_fetch_array($query)){
echo $hasta['name'];}
?>
For your ajax code, you need to add dataType parameter and add the parameter of success: function(data), so like this:
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
dataType:"html",
success: function(data){
alert(data);
}
});
For additional: always do debuging for sending data with inspect element of browser.
Hopefully it will be success for you :)

Jquery Ajax is not working with Codeigniter

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.

Post variables to php file and load result on same page with ajax

I have tried searching quite a bit but can't seem to make anything work.
I am trying to make a form that sends info to a PHP file and displays the output of the PHP file on the same page.
What I have so far:
HTML:
<html>
<form id="form">
<input id="info" type="text" />
<input id="submit" type="submit" value="Check" />
</form>
<div id="result"></div>
</html>
JS:
<script type="text/javascript">
var info= $('#info').val();
var dataString = "info="+info;
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
});
</script>
PHP:
<?php
$url = '/api.php?&info='.$_POST['info'];
$reply = file_get_contents($url);
echo $reply;
?>
When I set the form action to api.php, I get the result I am looking for. Basically what I want is to see the same thing in the "result" div as I would see when the api.php is loaded.
I cannot get any solutions to work.
Your click event is not stopping the actual transaction of the page request to the server. To do so, simply add "return false;" to the end of your click function:
$('#submit').click(function (){
$.ajax({
type: "POST",
url: "/api.php",
data: dataString,
success: function(res) {
$('#result').html(res);
}
});
return false;
});
Additionally, you should update the type="submit" from the submit button to type="button" or (but not both) change .click( to .submit(
Thanks everyone for your help, I have it working now.
I was doing a few things wrong:
I was using single quotes in my php file for the URL and also for the $_POST[''] variables.
I needed to add return false; as Steve pointed out.
I did not have a "name" for the input elements, only an ID.
I think Your code evaluate dataString before it is filled with anything. Try to put this into function of $.ajax. The code below.
/* ... */
$('#submit').click(function (){
$.ajax({
var info= $('#info').val();
var dataString = "info="+info;
/* ... */

Call function inside CodeIgniter's controller using jquery / ajax

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

Categories

Resources