I'm having problem how to solve ajax post in codeigniter. GET method is working well but when I changed it to post, it is no longer working. I observed that when I disabled my csrf_protection in config file, it is working, but when I enabled it, it is NOT WORKING. I want to use csrf_protection enabled while post method is working. Can anybody help me? Thanks..
<script>
$(document).ready(function(){
$('#submit').click(function(event) {
$.ajax({
type: 'POST',
url: '/common/test',
data: {
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>'
<?php endif ?>
},
success: function(response) {
alert(response);
}
});
return false;
});
});
</script>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
On my Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Common extends CI_Controller {
function test(){
echo 'test';
}
}
jQuery expects the headers to not be default HTTP headers. you need to change the headers of content-type i believe to match your output. See the attached documentation for how to use codeigniters output class to do this. http://ellislab.com/codeigniter/user-guide/libraries/output.html
Related
I have OOP php file and I would like to call one of the function by AJAX, i have read a lot about this (mostly stackoverflow), but for some reason, it just doesnt work.
I know that ajax function is called (I tried to add some alert into success function and that alert appeared after clicking the button), but somehow it ignores everything from file ajax.php (i even tried to add some echo at the top of ajax.php file, but nothing happened)
also note that I need button, not input (although that would be much easier)
this is my button:
<button class='formular-button' type='button' onclick='prihlasPA()'> vypiš přihlaš </button>
this is my script for button:
<script>
function prihlasPA() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {action: 'prihlasP'},
success: function(){},
error: function(){
alert("chyba");
}
});
}
</script>
and this is inside ajax.php, which is called by AJAX:
include( 'navstevnik.php' );
echo "aaa";
if(isset($_POST['action']) ) {
$navstevnik = new navstevnik; //navstevnik is name of my class btw
$navstevnik->vypisPrihlas();
}
I dont think it matters, but in my function vypisPrihlas() is this code:
public function vypisPrihlas(){
$this->index=1;
echo '
<fieldset class="formular">
<div class="pure-control-group stred" >
<input id="nick" type="text" name="nickP" placeholder="Nickname">
</div>
<div class="pure-control-group stred">
<input id="password" type="password" name="hesloP" placeholder="Heslo">
</div>
<input class="pure-button pure-button-primary stred" style=width:188px; type="submit" name="buttonP" value="přihlásit" />
</fieldset>';
}
I don't see any issues with the above code.
When the function vypisPrihlas echos the HTML, you won't see it on your main page. Instead, you need to load it in from your success function and append the HTML somewhere on your page.
$.ajax({
type: "POST",
url: "ajax.php",
data: {action: 'prihlasP'},
success: function(data){
$( ".your_favorite_div" ).append(data);
},
error: function(){
alert("chyba");
}
});
By what you said, the ajax function is fine, right?
I think your problem is the path for PHP, since it is not called. try change this line
url: "ajax.php",
for the complete path, like \var\www\path_to_code\ajax.php. Maybe it helps.
I am submiting a form to a php page using ajax in order to make a query.
The problem is that the $_POST is empty.
What am I doing wrong here?
Any ideas?
FORM
<div id="button_left">
<form>
<label>
<input type="text" class="search" size="30" style="margin-left:20px;" name="epitheto" id="epitheto" placeholder="Επίθετο" />
</label>
<label>
<input type="submit" value="Αναζήτηση" />
</label>
</form>
</div
FUNCTION
$(function () {
$('#button_left').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'people_name_query_final.php',
data: $('form').serialize(),
success: function () {
$("#pelates_last_name_query").slideDown("slow");
$("#pelates_last_name_query").load( "people_name_query_final.php");
}
});
});
});
PHP
if(isset($_POST['epitheto'])){
//some code
}
Add one argument to your success function:
success: function (response) {
$("#pelates_last_name_query").slideDown("slow");
$("#pelates_last_name_query").html( response);
}
and you will get response from php page....
P.S. Test php page should look like this (or whatever you want for response - you should ECHO something, send some output):
<?php
if(isset($_POST['epitheto'])){
print_r($_POST);
}
?>
so, vars are sent properly.... (i've tested it right now).
If your php page looks like code you atached/showed us - there is no any output, you didn't printed anything....
<form> element has submit event, <div> doesn't.
Change the first line to this:
$('form').on('submit', function (e) { // <-- change '#button_left' to 'form'
// (...) Code
}
I believe Amit might be correct. You are specifying the incorrect data to submit.
Change <form> to <form id="content">
Then change your JQuery code accordingly.
$('#content').on('submit', function (e) {//rest of your code//}
Another possible issue is that the scope on your URL is incorrect.
url: 'people_name_query_final.php', will work assuming the PHP script and JQuery are in the same directory.
Also, if you do print_r($_POST); exit; in your PHP script you see nothing?
Check the network tab on your browser developer tools to make sure the data is sent properly.
I got some problem about receive value from server , and show the value in input .
Sometimes, if I want to show the value in page, I will use the POST method, then set the input'ID in controller and model, and use foreach() in page you want to show , therefore the work is done.
But, if I want to show the value in input'field, how I need to do for it ?
I write some code for this and try to use AJAX receive and show in input, it's not working,can everybody help me to solve this problem , please....... Σ(  ̄□ ̄;)
I try to create a new model and a new page for it, there is a very simple form, the code is below:
view:kungfu.php
<div style="width:250px;float:left;">
<form id="pr_form" action="<?php echo site_url();?>/static_data/kungfu_act" method="post">
NUM:<input id="num" name="num" type="text" class="field_set"><br>
NAME:<input id="name" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" name="kungfu" type="text" class="field_set"><br>
</div>
<div style="float:left;">
<span id="loading" style="display:none">Loading!!</span><br>
<span id="complete" style="display:none">Complete!!</span>
</div>
<div style="clear:both;height:50px;padding-top:10px">
<input id="query" name="query" class="btn" type="button" value="QUERY">
</div>
</form>
</div>
model:pr_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pr_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
}
function pr_query()
{
$query=$this->db->get("kungfu_table");
return $query->result();
}
}
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_query()
{
$this->load->model("pr_model");
$data = array(
"kungfu" =>$this->pr_model->pr_query()
);
echo json_encode($data);
}
}
if I want to show the value in normal page , I will use foreach() but I don't know how to show in input, I try to use getjson() , but no working . can somebody teach me ?
// 2013/11/30 re-edit
dear Suleman:
I try to write some code about .ajax() , but I still got problem , the other section was the same , but the controller had be change :
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_maxquery()
{
$this->load->model("pr_model");
$data = $this->pr_model->pr_maxquery();
$max=json_encode($data);
echo $max;
}
}
model:pr_model.php
function pr_maxquery()
{
$this->db->select_max("num");
$maxquery=$this->db->get("kungfu_table");
return $maxquery->result();
}
and I try to edit a js file for .ajax(),but the Chrome console tell me "Uncaught ReferenceError: maxnum is not defined " , can you tell me how to edit it ?
$("#newone").click(function(){
$("#num").val(function(){
max_response = $.ajax({
type:"POST",
url:"<?php echo base_url()?>/static_data/kungfu_maxquery",
cache:false,
data: "num:"+maxnum
});
max_response.done(function(){
return maxnum;
});
});
});
Make sure your model data is available in view, If available then need to alter your inpup fields:
NUM:<input id="num" value="<?php echo $data_for_first_input_filed; ?>" name="num" type="text" class="field_set"><br>
NAME:<input id="name" value="<?php echo $data_for_second_input_filed; ?>" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" value="<?php echo $data_for_third_input_filed; ?>" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" value="<?php echo $data_for_forth_input_filed; ?>" name="kungfu" type="text" class="field_set"><br>
If you want to append data through AJAX, then here is sample code:
$("#newone").click(function(){
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
data: {
'num':maxnum
},
cache: false,
success: function(data) {
console.log(data);
$("#num").val(data['filed_name_returned']);
$("#name").val(data['filed_name_returned']);
$("#local").val(data['filed_name_returned']);
$("#kungfu").val(data['filed_name_returned']);
}
});
});
AJAX request is not a cheap call, we can get all the data in one request and can set that available data in success function. I do't know your table structure that' why I have appended one line extra console.log(data); that will show your returned data in console.
sorry for this repeated & repeated question , but I really don't know how to solve.
there was one button and two text_input , when I click this button,if it's work,I will see a alert and show "success" to me , but unfortunately , I just can see nothing.
nothing !!
I don't know why :(
please help me , please ...... I read many tutorials in stackoverflow or other website about codeigniter , but I don't find anything can solve my problem , please teach me guys.
here is a very simple form below
file name: test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test </title>
<link rel="stylesheet" href="<?=base_url("/css/bootstrap.css")?>">
<link rel="stylesheet" href="<?=base_url("/css/basic.css")?>">
<script src="<?=base_url("/js/jquery-1.10.2.min.js")?>"></script>
<script src="<?=base_url("/js/bootstrap.js")?>"></script>
<script src="<?=base_url("/js/practice.js")?>"></script>
</head>
<body>
<div style="margin:19px">
<form id="test_form" method="post">
USER:<input id="num" name="num" type="text" ><br>
NAME:<input id="name" name="name" type="text" ><br>
<input id="submit" name="submit" class="btn" type="submit" value="save">
</form>
</div>
</body>
</html>
I want to submit data in this form by jQuery Ajax() , the JS file is below
file name: practice.js
$(document).ready(function(){
$("#test_form").submit(function(e){
e.preventDefault();
var tdata= $("#test_form").serializeArray();
$.ajax({
type: "POST",
url: "http://localhost/index.php/static_data/test_add",
dataType: json,
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
}
});
});
});
and below was my controller
file name:static_data
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function test()
{
$this->load->view('test');
}
public function test_add()
{
$this->load->model("paper");
$this->paper->test_add();
}
}
and this file below was my model set
file name:paper.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paper extends CI_Model {
function __construct()
{
parent::__construct();
}
function test_add()
{
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
$tdata = array(
'num' => $this->input->post('num'),
'name' => $this->input->post('name'),
);
$this->db->insert('test_table',$tdata);
}
}
Try this -> In your test.php file, give the action attribute as
action="<?php echo site_url();?>/static_data/test_add"
Then, in your practice.js file:
$('#test_form').submit(function() {
var tdata= $("#test_form").serializeArray();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = tdata;
Now, for testing, in your success function in practice.js, just write the following:
success: function(response) {
console.log(response);
}
Here, the response you get is what your controller returns to you, now to test that, just type echo "hello"; or anything, just echo out something. (This is because you said teach me :) )
Now to see if this is working, open deveoper tools (if you are in google chrome), go to the console tab and then from bottom, select log, if everything is fine, it will return your echoed message written in your controller.
Also, to see if the form is submitted correctly, select the network tab, when you hit the submit button, the network tab will show you if the data has been submitted correctly or not.
Try this, if doesn't work, leave a comment.
I think you can easily solve this problem by this simple ajax request given below:
$(document).ready(function(){
$("#test_form").on("submit", function(event){
event.preventDefault();
$.ajax({
url : base_url+"static_data/test_add",
type : "post",
data : $("#test_form").serialize(),
dataType : "json",
success(data)
{
alert('SUCCESS!!');
}
});
});
});
Before doing that, in your view file (test.php) on the head setion please write this
<script>
var base_url = "<?php echo base_url(); ?>";
</script>
Try this :
Practice.js
$(document).ready(function(){
$("#test_form").submit(function(e){
e.preventDefault();
var tdata= $("#test_form").serializeArray();
$.ajax({
type: "POST",
url: 'http://localhost/[CodeIgniterDirectory]/index.php/static_data/test_add',
data: tdata,
success:function(tdata)
{
alert('SUCCESS!!');
},
error: function (XHR, status, response) {
alert('fail');
}
});
});
});
My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});