JQuery Ajax POST in Codeigniter - codeigniter

I have searched a lot of tutorials with POST methods and saw answered questions here too but my POST still doesn't work...I thought i should post it here if you guys see something that i don't!
My js - messages.js:
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: base_url + "chat/post_action",
data: {textbox: $("#textbox").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
return false;
});
});
My view - chat.php:
<?php $this->load->js(base_url().'themes/chat/js/messages.js');?> //i use mainframe framework which loading script this way is valid
<form method="post">
<input id="textbox" type="text" name="textbox">
<input id="send" type="submit" name="send" value="Send">
</form>
Last My controller - chat.php
//more functions here
function post_action()
{
if($_POST['textbox'] == "")
{
$message = "You can't send empty text";
}
else
{
$message = $_POST['textbox'];
}
echo $message;
}

$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: base_url + "chat/post_action",
data: {textbox: $("#textbox").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have missed this bracket
return false;
});
});

In codeigniter there is no need to sennd "data" in ajax post method..
here is the example .
searchThis = 'This text will be search';
$.ajax({
type: "POST",
url: "<?php echo site_url();?>/software/search/"+searchThis,
dataType: "html",
success:function(data){
alert(data);
},
});
Note : in url , software is the controller name , search is the function name and searchThis is the variable that i m sending.
Here is the controller.
public function search(){
$search = $this->uri->segment(3);
echo '<p>'.$search.'</p>';
}
I hope you can get idea for your work .

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class UserController extends CI_Controller {
public function verifyUser() {
$userName = $_POST['userName'];
$userPassword = $_POST['userPassword'];
$status = array("STATUS"=>"false");
if($userName=='admin' && $userPassword=='admin'){
$status = array("STATUS"=>"true");
}
echo json_encode ($status) ;
}
}
function makeAjaxCall(){
$.ajax({
type: "post",
url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
cache: false,
data: $('#userForm').serialize(),
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}

The question has already been answered but I thought I would also let you know that rather than using the native PHP $_POST I reccomend you use the CodeIgniter input class so your controller code would be
function post_action()
{
if($this->input->post('textbox') == "")
{
$message = "You can't send empty text";
}
else
{
$message = $this->input->post('textbox');
}
echo $message;
}

<script>
$("#editTest23").click(function () {
var test_date = $(this).data('id');
// alert(status_id);
$.ajax({
type: "POST",
url: base_url+"Doctor/getTestData",
data: {
test_data: test_date,
},
dataType: "text",
success: function (data) {
$('#prepend_here_test1').html(data);
}
});
// you have missed this bracket
return false;
});
</script>

Related

Cannot insert ajax data into database codeigniter

I want to insert some ajax post data into database. But when I'm clicking submit, no data is being inserted.
view(header.php)
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
}
});
});
});
Controller (User.php)
public function add_transaction()
{
$columns_and_fields = array('transaction_id','transaction_particular_name','transaction_student_id');
foreach ($columns_and_fields as $key)
$data[$key]=$this->input->post($key);
$query=$this->Mdl_data->insert_transaction($data);
if($query)
redirect('User','refresh');
}
Model (Mdl_data.php)
public function insert_transaction($data=array())
{
$tablename='transaction';
$query=$this->db->insert($tablename,$data);
return $query;
}
First of all, declare the variable in JavaScript with keyword var
var transaction_student_id=$(".student_id").val();
Before starting the Ajax use console.log() to know if the variables have data or not
The second thing is you are not getting the data with right way in the controller
Try like this
public function add_transaction()
{
$columns_and_fields = array('transaction_id' = $this->input->post('transaction_id'),
'transaction_particular_name' => $this->input->post('transaction_particular_name'),
'transaction_student_id' => $this->input->post('transaction_student_id'));
$query=$this->Mdl_data->insert_transaction($columns_and_fields);
if($query){
redirect('User','refresh');
}
}
Don't use the extra line of code without any reason
public function insert_transaction($data = array())
{
return $this->db->insert('transaction', $data);
}
Try debugging your code first.
Do you get all the data in controller? Try to dump POST values var_dump($_POST) in controller if ajax is successfully sending the data.
From there, you can see if the data in successfully sent from the front end.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>user/add_transaction",
dataType: 'json',
data: {
transaction_student_id: transaction_student_id,
transaction_particular_name: transaction_particular_name,
transaction_id: transaction_id
},
success: function( data ) {
console.log( data );
},
error: function( xhr, status ) {
/** Open developer tools and go to the Console tab */
console.log( xhr );
}
});
change it
$(function(){
$(".submit").click(function(){
transaction_student_id=$(".student_id").val();
transaction_particular_name=$(".particular_name").val();
transaction_id=$(".transaction_id").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url().'user/add_transaction'; ?>",
dataType: 'json',
data: {transaction_student_id: transaction_student_id,transaction_particular_name:transaction_particular_name,transaction_id:transaction_id},
success: function(data) {
alert(data + ' id added' );
window.location.reload(); // force to reload page
}
});
});
});
at controller
public function add_transaction()
{ // use it only for ajax call or create another one
$columns_and_fields = array();
// 'transaction_id','transaction_particular_name','transaction_student_id'
foreach ($_POST as $key)
{
array_push($columns_and_fields , array(
'transaction_student_id' => $key['transaction_student_id'],
'transaction_particular_name'=>$key['transaction_particular_name'],
'transaction_id'=>$key['transaction_id']
)
);
}
$this->Mdl_data->insert_transaction_array($columns_and_fields);
}
and at model create new method
public function insert_transaction_array($data=array())
{
$tablename='transaction';
$this->db->insert_batch($tablename,$data);
}

codeigniter form validation with anchor tag click

I want to validate some form fields without submitting the form.
Here is my code if someone can help.
View:
<form>
<input type="text" name="first_name" placeholder="First Name..." class="textfield">
<a href="javascript:void();" onClick="validateName();">
</form>
Script:
function validateName(){
var first_name = $('.textfield').val();
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: first_name,
dataType:"json",
success: function(response){
var obj = eval(response);
if(obj.error==0){
console.log('Success');
}
else{
console.log('Failed');
}
}
});
}
Controller:
public function contAjax(){
// loading form validation library //
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'required');
if($this->form_validation->run()== TRUE){
echo json_encode(array('error' => 0));
}
else{
echo json_encode(array('error' => 1));
}
}
It always returns error=1 and form validation is not working...
This is untested code... but should work ( he said with a grin )
function validateName() {
var first_name = $('.textfield').val();
console.log('first_name is ' + first_name); // Check it's getting this far
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: {first_name: first_name},
dataType: "json",
success: function (response) {
if (response.error == 0) {
console.log('Success');
}
else {
console.log('Failed');
}
}
});
}
So with the addition of the console.log you can easily inspect your value...
I am not a big fan of using capitals in urls ( only works on windows and can lead to tears on a linux / apache server ) so best to use lowercase.
Just to add some more debug to this the simplish way you could inspect what the server side sees you posting...
This is just a way to check your posted values ( using something like firebug or similar is far better...)
function contAjax() {
// loading form validation library //
$this->load->library('form_validation');
$this->form_validation->set_rules('first_name', 'First name', 'required');
$first_name = $this->input->post('first_name');
if ($this->form_validation->run() == TRUE) {
echo json_encode(array('error' => 0, 'first_name' => $first_name));
} else {
echo json_encode(array('error' => 1, 'first_name' => $first_name));
}
}
And your JS would become...
function validateName() {
var first_name = $('.textfield').val();
console.log('first_name is ' + first_name); // Check it's getting this far
$.ajax({
url: "Eligibility/contAjax",
type: "POST",
data: {first_name: first_name},
dataType: "json",
success: function (response) {
if (response.error == 0) {
console.log('Success - First Name = ' + response.first_name);
}
else {
console.log('Failed - First Name = ' + response.first_name);
}
}
});
}
The trick is to know how to "see" what is happening which makes debugging these kinds of things of lot easier...
Hope that helps. Again this code is untested but shows the principal...

How to get a value from ajax call in laravel

I want to get a value from the ajax call in controller function. How can i do it?
My code is here:
<i class="fa fa-pencil-square-o"></i>
My script:
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
My route:
Route::post('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
my controller function:
public function amount_to_pay($id)
{
echo $id;
}
easly return the value:
public function amount_to_pay($id)
{
return $id;
}
Use
var url = '{{ route('amount_popup', ['id' => #id]) }}';
url = url.replace('#id', id);
instead of
'amount_popup/'+ id
You are trying to get the value from a GET request, but you are sending the form as a POST request.
You should change your script code to:
<script>
function amount_pay(id)
{
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
THEN CHANGE YOUR ROUTE TO:
Route::get('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
OR IF YOU WANT TO USE POST... DO THIS...
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup',
data: "id=" + id + "&_token={{ csrf_token() }}", //laravel checks for the CSRF token in post requests
success: function (data) {
alert(1);
}
});
}
</script>
THEN YOUR ROUTE:
Route::post('/amount_popup', 'AdminController\AmountController#amount_to_pay');
THEN YOUR CONTROLLER:
public function amount_to_pay(Request $request)
{
return $request->input('id');
}
For more info:
Laravel 5 Routing

Symfony ajax form need reload page to show results

I have a product page where users can write comments, this works fine but i would like to implement ajax form with no page refresh.
The code call ajax and persist, but need press f5 to show new comment.
what am I doing wrong?
Thanks, and sorry for my english.
In product view, render a controller that call the form:
<div class="comments">
{{ render(controller('AppBundle:Comment:newComment',{'media': selected.id})) }}
</div>
Controller:
class CommentController extends Controller
{
/**
* #Route("/media/{media}/", name="create_comment", options={"expose"=true})
* #Method("POST")
* #ParamConverter("media", class="AppBundle:Media")
*/
public function newCommentAction(Request $request, $media)
{
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$data = $form->getData();
$data->setUser($this->getUser());
$data->setMedia($media);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return new JsonResponse('Success!');
}
return $this->render('comment/newComment.html.twig', array(
'media' => $media,
'form' => $form->createView()
));
}
}
newComment.html.twig
<form method="POST" id="commentForm" action="{{path('create_comment', {'media': media.id})}}">
{{ form_row(form.comment) }}
<button type="submit" id="submitButton" class="btn btn-xs btn-danger">{{ 'btn.send' |trans }}</button>
app.js
$('body').on('click','#submitButton', function(e){
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function(response){
$(".ajaxResponse").html(response);
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
This should work for you to reload the element with class="comments" after your POST:
$('#submitButton').on('click', function (e) {
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function (response) {
$('.comments').load(window.location + ' .comments > *');
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
Edit:
As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests?

filtering column table using select box ajax in codeigniter

i want to filtering data on the table using select box. When user choose value from select box then column on the table will filtered. I mean the table just show data that contain value on select box that user choose. Can anyone help me
this is my ajax :
<script>
$("#inputJenis").on('change',function(){
if($("#inputJenis").val() != 'Ganjil'){
$.ajax({
type: "POST",
url:'<?php echo base_url()?>search/filter',
data:'selectvalue='+$('#inputJenis').val(),
cache: false,
success: function(data){
$(#tableData).html(data);
},
error: function(data){
//return false;
}
});
});
});
</script>
this is my controller :
public function filter()
{
$this->load->helper('url');
$this->load->model('filter_model');
$this->filter_model->getData();
$data = $this->filter_model->getData();
echo json_encode($data);
}
this is my model :
public function getData($type)
{
$this->db->select('jenis');
$query = $this->db->get('tahunajaran');
return $query->result();
echo json_encode($query);
}
This code didn't work. help me please
Try this:
AJAX:
<script type="text/javascript">
var base_url='<?php echo base_url(); ?>';
</script>
<script>
$("#inputJenis").change(function(e){
if($("#inputJenis").val() != 'Ganjil'){
$.ajax({
type: "POST",
url:base_url+'search/filter',
data:'selectvalue='+$('#inputJenis').val(),
cache: false,
success: function(data){
$(#tableData).html(data);
},
error: function(data){
//return false;
}
});
});
});
</script>
Controller
public function filter()
{
$this->load->helper('url');
$this->load->model('filter_model');
$this->filter_model->getData();
$selectValue=$this->input->post('selectvalue')
$data = $this->filter_model->getData($selectValue);
echo json_encode($data);
}
Model
public function getData($selectValue)
{
$this->db->select('jenis');
//Change it with your Field Name
$query = $this->db->where('SomeField',$selectValue)->get('tahunajaran');
return $query->result_array();
}

Resources