I have a problem with ajax post to codeigniter controller. It is get in to function but not post the data. Why ajax is not successfully post data ?
Here is my controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller{
public function index(){
$this->load->helper('url');
$this->load->view('index');
}
public function login(){
if ($_POST) {
$kAdi = $this->input->post('kAdi');
echo json_encode("done!");
}
}
}?>
my Ajax code :
function girisYap(){
var kAdi = $("#username").val();
var parola = $("#password").val();
$.ajax({
type:"POST",
url: "<?php echo base_url(); ?>" + "/main/login",
data: "kAdi="+kAdi,
dataType: 'json',
success : function(cevap){
alert("successfull");
}
});
}
Am I missing something ?
I solve the porblem, thank you guys. Here is the works code :
The controller
public function login(){
if ($_POST) {
$kAdi = $this->input->post('kAdi');
echo json_encode("done!");
}
Ajax function :
function girisYap(){
var $_base_url = '<?=base_url()?>';
var kAdi = $("#username").val();
var parola = $("#password").val();
alert($_base_url+"main/login");
$.ajax({
type:"POST",
url: $_base_url + "main/login",
data: {kAdi: kAdi},
dataType: 'json',
success : function(cevap){
alert(cevap);
}
});
}
Don't put the / before main/login because base url = localhost/codeigniter/ has a slash in the end. If you put slash it become codeigniter//main....
So, thanks for all the answers.
Try with this one
function girisYap(){
var kAdi = $("#username").val();
var parola = $("#password").val();
$.ajax({
type:"POST",
url: "<?php echo base_url(); ?>/main/login",
data:{kAdi: kAdi},
dataType: 'json',
success : function(cevap){
alert("successfull");
}
});
}
Post data should be like below one
data: { name: "John", location: "Boston" }
Not like
data: "kAdi="+kAdi,
Also Print the URl and check it access or not
Use this
$.post("<?php echo base_url() ?>main/login",
{
kAdi: kAdi
},
function(cevap){
console.log(cevap.trim());
if(cevap){
alert(cevap);
alert("sucessful");
}
});
On the other hand in controller,use this
$this->input->post('kAdi');
Related
I did some research on this topic but i cant run this id is not send to page.
listdata.php
<td class="text-center" style="min-width:130px;">
<button style="width:100%" class="btn btn-primary detail-customer" data-id="<?php echo $m->id; ?>">Bilgi</button>
</td>
ajax.php
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: "id=" + id
})
.done(function(data) {
window.location = "customers/info";
})
})
controller:
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
print $id;
//$this->template->views('customers/info', $data);
}
Are you naming your ajax file as Ajax.php? is that a PHP file? It definitely should be a js file.
From what I know from Jquery and Ajax, url key takes the location of the PHP file, and the data key should be passed as an object. Take these two files as an example:
Ajax.js
$(document).on("click", ".detail-customer", function() {
var id = $(this).attr("data-id");
$.ajax({
type: "POST",
url: "/absolute_path/to/php_file.php",
data: {my_id:id, my_custom_key: "my_custom_value"},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function(response){
console.log(response);
}
})
.done(function(data) {
window.location = "customers/info";
})
})
Php_file.php
<?php
$id = $POST["my_id"];
$customValue = $POST["my_custom_value"];
$response = ["message"=> "We took your id which is $id and your custom value which is $customValue"];
echo json_encode($response);
?>
This is a very basic example of how to use ajax.
Please try it
$(document).on("click", ".detail-customer", function() {
var id = $(this).data("id");
$.ajax({
method: "POST",
url: "<?php echo base_url('customers/info'); ?>",
data: {"id":id},
Content-Type:"json"
});
.done(function(data) {
window.location = "customers/info";
})
});
"we do not read your complete controller code
if your code is correct total then please
first convert data in json then
return it.
"
public function info()
{
$data['page'] = "customer_information";
$data['userdata'] = $this->userdata;
$id= trim($_POST['id']);
echo json_encode($id);
//$this->template->views('customers/info', $data);
}
When I call ajax in codeigniter 3.1.7 than it can take automatically base url in ajax url
AJAX CALLING CODE :
$(document).on("click",".btn_edit",function(){
var id = $(this).attr("id");
$("#btnsave").attr("mode","update");
$("#myModal").modal("show");
console.log(id);
$.ajax({
type :"post",
url :"Home/get_emp",
data :{"id":id},
dataType : "json",
success : function(edit_feed){
$("#txtempid").val(edit_feed.e_id);
$("#txtempname").val(edit_feed.e_name);
$("#selempskill option:contains('"+edit_feed.e_skill+"')").prop('selected',true);
$("#prev_img").attr("src",base_url+edit_feed.e_img);
var lbl = edit_feed.e_img.split("/");
$("#pic_label").html(lbl[3]);
}
});
});
Controller :
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('Emp_model');
}
public function index(){
//$this->load->view('index');
$this->load->view('home');
}
public function get_emp(){
$id=$_POST['id'];
$data = $this->Emp_model->get_emp($id);
echo json_encode($data);
}
ERROR :
jquery.3.2.1.js:3049 POST http://localhost/cod_std/Home/get_emp 404 (Not Found)
Here I want call only Controllers Home and its function get_emp please give me some solution I use codeigniter3.1.7
You can try:
url:"<?php echo site_url("Home" . '/get_emp'); ?>",
You have to use:
url:"<?php echo base_url(); ?>index.php/Home/get_emp",
Use like below code may solve your problem it work for me
$(document).on("click",".btn_edit",function(){
var id = $(this).attr("id");
$("#btnsave").attr("mode","update");
$("#myModal").modal("show");
console.log(id);
$.ajax({
type :"post",
url:"<?php echo base_url(); ?>index.php/Home/get_emp",
data :{"id":id},
dataType : "json",
success : function(edit_feed){
$("#txtempid").val(edit_feed.e_id);
$("#txtempname").val(edit_feed.e_name);
$("#selempskill option:contains('"+edit_feed.e_skill+"')").prop('selected',true);
$("#prev_img").attr("src",base_url+edit_feed.e_img);
var lbl = edit_feed.e_img.split("/");
$("#pic_label").html(lbl[3]);
}
});
});
I have tried a lot and search a lot and i did the same as i see but i do not know where i am going wrong i am new to codeigniter. Can you please tell me where i am going wrong on the code ? I want to set the product name in my input field according to the barcode selected. I am trying to fetch the product name and try to set it using AJAX but it is not working. Please you tell where is the bug in my code?
Here is my Controller Function in Main.php
public function get_product()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
echo $barcode;
exit;
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
print_r($data);
exit;
}
My Ajax Code in js file :
$("#brcode").each(function(){
$("#brcode").change(function(){
let value = $("#brcode").val();
$.ajax({
url: '<?php echo site_url("main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
dataType: 'json',
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
Model Function :-
public function get_product_using_barcode($barcode){
$query = $this->db->get_where('items',array('barcode' => $barcode));
$result = $query->row();
return $result;
}
Please tell me where i am going wrong in my code?
Try this code Its works for me. Hope this will help you.
JQuery:
$(document).ready(function() {
$("#brcode").change(function(){
let value = $("#brcode").val();
$.ajax({
// URL should be include index.php
url: '<?php echo site_url("index.php/main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
dataType: 'json',
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
Controller:
public function get_product()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
return json_encode $data;
}
Model:
public function get_product_using_barcode($barcode){
$query = $this->db->get_where('items',array('barcode' => $barcode));
$result = $query->row();
return $result;
}
Greetings!
Can you change js code as like this. and try to see on console.
$(document).ready(function() {
$("#brcode").change(function(){
var value = $("#brcode").val();
$.ajax({
url: '<?php echo site_url("main/get_product"); ?>',
type: 'POST',
data: {'barcode': $('#brcode option:selected').val() },
success: function(data) {
//console.log(data);
alert(data);
}
})
});
});
You are going wrong in this section as you are using dataType: 'json', Your ajax should return a json object.
PHP Tag won't work in js file, so you should put your ajax request either in footer of the page or hardcode your url. For example : url:"http://localhost/retail/main/get_product"
Also i think let value = $("#brcode").val(); should be var value = $("#brcode").val();
So your controller code should be
public function get_product()
{
$data = array();
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$barcode = $_POST['barcode'];
$data['result'] = $this->Item_model->get_product_using_barcode($barcode);
echo json_encode(array("posted_data"=>$_POST,"database_data"=>$data['result']));
exit;
}
And in success of ajax use this
success: function(data) {
console.log("Posted data");
console.log(data.posted_data);
console.log("Database data");
console.log(data.database_data);
}
I am new to using ajax and I am having trouble with posting variables and accessing those variables in my controllers.
Here is the Controller Code
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
/* $this->load->model('product_model');
$q = 'SELECT quantity FROM products WHERE productName = "BC20BA"';
$data = $this->product_model->get_record_specific($q);
echo json_encode($data[0]->quantity);
*/
echo $product;
}
function index()
{
$this->load->view('autocomplete_view');
}
}
If I change the echo to a string inside single quotes like this 'Hello World', it will return the hello world back to the view correctly. But it will not do the same if I try it as it currently is. Also if I use echo json_encode($product); it then returns false.
Here is view code with ajax.
$( document ).ready(function () {
// set an on click on the button
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: 'productName',
success: function(msg){
alert(msg);
}
});
});
});
</script>
</head>
<body>
<h1> Get Data from Server over Ajax </h1>
<br/>
<button id="button">
Get posted varialbe
</button>
class autocomplete extends CI_Controller {
// just returns time
function workdammit()
{
$product = $this->input->post('productName');
//echo $product;
//in ajax dataType is json -here You have to return json data
echo json_encode($product);
}
...
}
//javascript file
var productName = $('#productName).val();//get value of product name from form
$('#button').click(function () {
$.ajax({
type: "POST",
url: "<?php echo site_url('autocomplete/workdammit'); ?>",
dataType: "json",
data: {productName:productName},//You have to send some data from form
success: function(msg){
alert(msg);
}
});
In CI, I have setup a controller with a method of logsig(). Then in my index() method I'm calling a view called startpage. In my view I'm using JSON to make an asynchronous call between my view and my controller. How would I code the call. Below is the code I have:
Contoller:
function logsig() {
$this->load->view('startpage', $sync);
header('Content-type:application/json'); .............
View:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// blink script
$('#notice').blink();
$("#action_button").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "processing/logsig.php",
data: dataString,
json: {session_state: true},
success: function(data){
if(data.session_state == true) { // true means user is logged in.
$("#main1").hide();
$('#main1').load('<?=$sync?>').fadeIn();
} else if(data.session_state == false) { // false means user is being registered.
$("#action_button").remove();
$('#success').load('<?=$sync?>');
// onLoad fadeIn
}
}
});
}
});
});
</script>
You can't have your controller load a view and return JSON at the same time. Break out the JSON portion to a separate function.
An oversimplified example could look like this:
// Your existing function, but only displaying the view
function logsig() {
$this->load->view('startpage', $sync);
}
// A new function whose sole purpose is to return JSON
// Also notice we're using CI's Output class, a handy way to return JSON.
// More info here: codeigniter.com/user_guide/libraries/output.html
function get_json() {
$this->output->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
}
Then, in your JavaScript, call get_json:
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url('processing/get_json.php'); ?>",
// ... truncated for brevity ...
});
If I read your question correctly, your JS postback code isn't working:
url: "processing/logsig.php",
Your CI url should be something like:
url: <?php echo site_url("processing/logsig"); ?>,
The site_url() function requires the URL helper. Load that in the beginning of your loadsig() function:
$this->load->helper('url');
Try This
Controller ---------
public function AjaxTest() {
$rollNumber = $this->input->post('rollNumber');
$query = $this->welcome_model->get_students_informationByRoll($rollNumber);
$array = array($query);
header('Content-Type: application/json', true);
echo json_encode($array);
}
View-----
<?php echo validation_errors(); ?>
<?php echo form_open('welcome/SearchStudents'); ?>
<input type="text" id="txtSearchRoll" name="roll" value="" />
<input type="submit" name="btnSubmit" value="Search Students" onclick="return CheckAjaxCall();"/>
<?php echo '</form>'; ?>
Scripts ----------
function CheckAjaxCall()
{
$.ajax({
type:'POST',
url:'<?php echo base_url(); ?>welcome/AjaxTest',
dataType:'json',
data:{rollNumber: $('#txtSearchRoll').val()},
cache:false,
success:function(aData){
//var a = aData[0];
//alert(a[0].roll);
$.map(aData, function (item) {
var stData = "<td>"+ item[0].roll +"</td>" +
" <td>"+item[0].Name+"</td>" +
"<td>"+item[0].Phone+"</td>" +
"<td> Edit </td>"+
"<td> Delete </td>";
$('#tblStudent').text("");
$('#tblStudent').append(stData);
//alert (item[0].roll + " " + item[0].Name);
});
//alert(aData);
},
error:function(){alert("Connection Is Not Available");}
});
return false;
}