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;
}
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);
}
Windows 10, Codeigniter 3, Wamp3.
Ajax post throws a Bad Request error. This is an old chestnut but online research shows the problem usually to be CSRF. However I emphasize at the outset that I have csrf disabled for this test:
config['csrf_protection'] = FALSE;
I have set up some deliberately very simple test code. The controller looks like this:
class Ajax extends CI_Controller {
public function index() {
$this->load->view('pages/index');
}
public function hello($name) {
$fullname = $this->input->post('fullname');
echo 'Hello '.$fullname;
}
}//EOF
and the view looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:'<?php echo base_url('ajax/hello'); ?> + fullname',
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
</head>
<body>
Name <input type="text" id="fullname">
<input type="button" value="Hello" id="bttHello">
<br>
<span id="result1"></span>
</body>
</html>
The console shows a Bad Request
POST XHR http://localhost/faith/ajax/hello%20+%20fullname [HTTP/1.1 400 Bad Request 9ms]
So if csrf is not the culprit, is it a Wamp issue? Everything else seems to work fine. I have spent so much time on this!
What is going on?
Data are already sent through POST. No need to pass it through URL
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:"<?php echo base_url('ajax/hello'); ?>",
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
And, remove parameter $name from controller action hello().
public function hello() {
$fullname = $this->input->post('fullname');
echo 'Hello '.$fullname;
}
write url like this
"url": "<?php echo base_url().'ajax/hello';?>/" + fullname
after /fullname its a argument of function hello()
Try this..
<?php echo form_open('ajax/hello', [
'method' => 'post',
'class' => 'create_form'
]); ?>
<input type="text" name="fullname" value="Full Name"/>
<button type="submit">Create</button>
<?php echo form_close(); ?>
and ajax
$(document).on('submit', 'form.create_form', function (e) {
var self = this;
var formData = new FormData($(this)[0]);
$.ajax({
url: $(self).attr('action'),
type: 'POST',
data: formData,
async: false,
dataType: 'json',
success: function (res) {
console.log(res)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The CodeIgniter Controller:
<?php
class Ajax extends CI_Controller
{
public function index()
{
$this->load->view('pages/index');
}
/**
* #param $name
*/
public function hello($name)
{
// if no $name params value pass and post exist
if ( ! isset($name) && $this->input->post('fullname')) {
// get value from post params
$fullname = $this->input->post('fullname', true);
} elseif (isset($name) && ! $this->input->post('fullname')) {
// get value from pass param method
$fullname = $name;
} else {
// default value
$fullname = 'No Name found';
}
// show ajax response
echo $fullname;
}
/**
* Another way if we using GET params
* e.g. http://wwww.site.com/ajax/hello/my-name-value
* #param $name
*/
public function hello_another($name)
{
// if url has param as name value
// remember codeigniter will map all url params as method params as they provided
// no need to use get input, it will take from url string directly
if (isset($name)) {
// get value from get params
$fullname = $name;
} else {
// default value
$fullname = 'No Name found';
}
// show ajax response
echo $fullname;
}
/**
* Another way if we using GET params and security is on top
* e.g. http://wwww.site.com/ajax/hello/my-name-value
* #param $name
*/
public function hello_another_secure($name)
{
// if url has param as name value
// remember codeigniter will map all url params as method params as they provided
// no need to use get input, it will take from url string directly
if (isset($name) && preg_match("/^[a-zA-Z'-]+$/", $name)) {
// get value from method params
$fullname = $name;
} else {
// default value
$fullname = 'No Name or invalid name found';
}
// show ajax response
echo $fullname;
}
}
//EOF
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:'<?php echo base_url('ajax/hello'); ?>',
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'GET',
url:'<?php echo base_url('ajax/hello_another/'); ?> + fullname',
success: function(result) {
$('#result1').html(result);
}
});
});
});
</script>
The CodeIgniter is fully capable to fulfil your needs, Just look their AWESOME Document first..
use this way
you should concate fullname variable after quatation.
like this
url:'<?php echo base_url('ajax/hello'); ?>' + fullname
<script>
$(function() {
$('#bttHello').click(function(){
var fullname = $('#fullname').val();
$.ajax({
type:'POST',
data: {fullname: fullname},
url:'<?php echo base_url('ajax/hello'); ?>' + fullname,
success: function(result) {
$('#result1').html(result);
}
});
});
});
I want to call the codeigniter controller with ajax after the login. But when I execute it, the login page is only refreshed and ajax url isn't calling controller function of codeigniter.
I don't understand what happened. Please help?
Below is my code
function ValidateReg() {
var username = document.getElementById("inputName").value;
var password = document.getElementById("inputPassword").value;
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1)) {
$.ajax({
url: "<?php echo site_url('Dashboard/state'); ?>",
type: 'POST',
complete: function (done) {
console.log("Finished.")
}
});
}
});
}
Here Panel and Dashboard are my two different Controllers
It gets refreshed because it's a submit button and it must be inside form. So it submits the form on click event.
What you need to do is make your function to return false on click of the button so that page doesn't get refreshed.
Update your HTML like this,
<button type="submit" class="btn button text-uppercase" onclick="return ValidateReg();">Login </button>
And your JS function would look something like this:
function ValidateReg() {
var username = document.getElementById("inputName").value;
var password = document.getElementById("inputPassword").value;
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1)) {
$.ajax({
url: "<?php echo site_url('Dashboard/state'); ?>",
type: 'POST',
complete: function (done) {
console.log("Finished.")
}
});
}
});
return false;
}
If what you want to do is go to the page Dashboard/state then using ajax is the wrong approach. You need to redirect to that page instead.
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1))
{
console.log("Finished.");
window.location = "<?php echo site_url('Dashboard/state'); ?>";
}
}
);
The other way to redirect with javascript would be done like this
window.location.replace("<?php echo site_url('Dashboard/state'); ?>");
which is probably better because it does not keep the originating page in the session history.
function ValidateReg() {
var username = document.getElementById("inputName").value;
var password = document.getElementById("inputPassword").value;
$.post("<?php echo site_url('Panel/login') ?>", {checkUser: username, checkPassword: password, action: "validateUser"},
function (data) {
var result = data + "";
if (result.lastIndexOf("Success" > -1)) {
$.ajax({
url: "<?php echo site_url('Dashboard/state'); ?>",
type: 'POST',
success: function (done) {
console.log("Finished.")
}
});
}
});
return false;
}
I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(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);
}
});