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);
}
});
});
});
Related
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 need to send id and get database values according to the id without page refresh.and display data in my view,
here is my view,
<div>
Click on me
</div>
<script type="text/javascript">
function getSummary(id)
{
$.ajax({
type: "POST",
url: '<?php echo site_url('ajax_controller/getBranchDetails'); ?>',
cache:false,
data: "id=" + id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
controller
public function getBranchDetails(){
$b_id = $this->input->post('branch_id');
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
//echo json_encode(array('data'=>$data));
}
I need to display $data['results'] in my view
model
<?php
class Ajax_model extends CI_model{
function getRecords($id)
{
$this->load->database();
$query = $this->db->query("SELECT * FROM companydetails WHERE id='$id'");
return $query->result();
}
}
Try this code ,It is working .
<script type="text/javascript">
function getSummary(id)
{
$.post("<?php echo site_url('ajax_controller/getBranchDetails'); ?>",
{branch_id:id},function(data,status){
$('#summary').html(data);
});
}
</script>
Note : Check whether you have included jquery.min.js . If not mention the below code in view part header
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
Try this instead:
<script type="text/javascript">
function getSummary(id) {
$.ajax({
type: 'POST',
url: "<?php echo site_url('ajax_controller/getBranchDetails'); ?>", // <-- properly quote this line
cache: false,
data: {branch_id: id}, // <-- provide the branch_id so it will be used as $_POST['branch_id']
dataType: 'JSON', // <-- add json datatype
success: function(data) {
// if you need to present this in a html table,
// likely, you need to use $.each() and build the markup using the json response
$('#summary').html(data);
}
});
}
</script>
Model: (Don't directly use variables inside the query string)
$sql = 'SELECT * FROM companydetails WHERE id = ?';
$query = $this->db->query($sql, array($id));
Controller:
public function getBranchDetails()
{
$b_id = $this->input->post('branch_id', true);
$this->load->model('ajax_model');
$data['results'] = $this->ajax_model->getRecords($b_id);
echo json_encode($data); // <-- uncomment
}
I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.
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;
}