Ajax implementation in Codeigniter - ajax

Why i am not getting any value in my controller. Please help .
Here is my controller : welcome.php
class Welcome extends CI_Controller {
public function index()
{
$this->load->view('welcome_message');
}
public function ajax_process(){
$data = array(
'email' =>$this->input->post('email'),
'password'=>$this->input->post('password')
);
echo json_encode($data);
}
}
**this is my view file : welcome_mesage.php
$(document).ready(function(){
$('#sbtn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
var datas = $('#myform').serialize();
$.ajax({
type: "POST",
url: "http://localhost/codeigniter_testing/index.php/welcome/ajax_process",
data: {email : email, password : password},
success:function(data){
echo data;
}
});
});
});
my base url:
$config['base_url'] = 'http://localhost/codeigniter_testing/';

In your code their are code error
success:function(data){
echo data;
}
you have add alert instead of echo.
EX:
success:function(data){
alert(data.email);
}

Try it....
<script type="text/javascript">
$(document).ready(function(){
$('#sbtn').click(function(){
var email = $('#email').val();
var password = $('#password').val();
var datas = $('#myform').serialize();
$.ajax({
type: "POST",
url: "http://localhost/codeigniter_testing/index.php/welcome/ajax_process",
data: {email : email, password : password},
success:function(data){
var result=eval(data);
alert(result.email);
}
});
});
});
</script>

Related

ajax is not sending data to controller

ajax is not sending data to controller
var url = "<?php echo base_url(); ?>";
function allowip() {
var url = "<?php echo base_url(); ?>"
var id = $('#path').attr('value');
$.ajax({
type: "POST",
url: url+"client/home/get_ip",
//dataType: 'text',
data: {'id': id},
//cache: false,
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
alert is showing with data but not sending data to controller
controller is empty
public function get_ip($id)
{
$day = $this->input->post('id');
echo $day;
}
As your get_ip function have argument $id so it must need to pass on it, url keyword might be conflicting so use different variable name and get the value from #path with val() function.
It might help:
function allowip() {
var id = $('#path').val();
var request_url = "<?php echo base_url(); ?>"+"client/home/get_ip/"+id;
$.ajax({
type: "POST",
url: request_url,
data: {'id': id},
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
public function get_ip($id)
{
echo $id;
}
or you can do is to post $id in data as you're already doing it but only have to change some lines:
function allowip() {
var id = $('#path').val();
var request_url = "<?php echo base_url(); ?>"+"client/home/get_ip/";
$.ajax({
type: "POST",
url: request_url,
data: {'id': id},
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
public function get_ip()
{
$day = $this->input->post('id');
echo $day;
}
You are sending a parameter to a function so you can change your code like this
function allowip() {
var id = $('#path').attr('value');
var url = "<?php echo base_url(); ?>"+"client/home/get_ip/"+id
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(abc) {
alert(abc);
},
error:function(data) {
alert('no working');
}
});
}
and your action will be
public function get_ip($id)
{
echo $id;
}
I think it is probably the way you are getting the value. It's hard to tell without seeing the view code, but I will assume that $('#path') is an <input...> element of some sort. If that is correct then try getting the value like this
var id = $('#path').val();
Forget about using an argument with the get_ip() function. You are posting to the controller not creating a URL with argument values. Try this.
public function get_ip()
{
$day = $this->input->post('id');
echo !empty($day) ? $day : "No Input"; //or, an empty string instead?
}

Q: how to make form validation codeigniter with ajax?

Hello guys i try to make form validation codeigniter with ajax server side but it still not working, i want to make error message 'required' display under form input. what is it wrong in my code.
this is my controller
function ajax_submit_kategori() {
$this->load->library('form_validation');
$data['nama'] = $this->input->post('kategori');
$data['id_legislator'] = $this->input->post('legislator');
$this->db->insert('galangsuara_has_categories',$data);
$return['status'] = '0';
echo json_encode($return);
}
this is my ajax
<script type="text/javascript">
$('#input').submit(function(event){
event.preventDefault();
Pace.track(function(){
var cate = $('#tim').val();
var dapi = $('#dapil').val();
var legi = $('#legislatif').val();
$.ajax({
url: "<?= site_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
$("#modal_tambah").modal('hide');
document.getElementById("input").reset();
var table = $('#table').DataTable();
table.ajax.reload();
window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});
});
return false;
});
anyone can help me? :(
Try This
Controller code:
function ajax_submit_kategori() {
$status = 1;
$error = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('kategori', 'Kategori', 'required');
$this->form_validation->set_rules('dapil', 'Dapil', 'required');
$this->form_validation->set_rules('id_legislator', 'Id_legislator', 'required');
if ($this->form_validation->run() == FALSE) {
$status = 0;
$error = validation_errors();
} else {
$data['kategori'] = $this->input->post('kategori');
$data['dapil'] = $this->input->post('dapil');
$data['id_legislator'] = $this->input->post('id_legislator');
$this->db->insert('galangsuara_has_categories', $data);
}
$return['status'] = $status;
$return['$error'] = jsone_encode($error);
echo json_encode($return);
exit();
}
ajax code :
$.ajax({
url: "<?= base_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
//here, first you need to check your data is perfect for error then do according to your wish
//$("#modal_tambah").modal('hide');
//document.getElementById("input").reset();
//var table = $('#table').DataTable();
//table.ajax.reload();
//window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});

error in image while uploading through ajax

I am trying to upload image through ajax. at theclient side i am using this code.
$(document).on('change','.image_upload',function(){
readURL(this);
});
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = encodeURIComponent(image_data);
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
while at the client side i am using codeigniter to save this as image. Image file is created but it won't display because it contains errors.Here is my CI function where this ajax request is being sent.
public function new_valet_picture(){
$user = $this->session->user_id;
$image_data = $this->input->post('valet_image');
$name= "valet_".$user.time().".png";
$profile_image = str_replace('data:image/png;base64,', '', $image_data);
$profile_image = str_replace(' ', '+',$profile_image);
$unencodedData=base64_decode($profile_image);
$pth = './uploads/valet_images/'.$name;
file_put_contents($pth, $unencodedData);
echo $name;
}
can anybody figure out where i am wrong.
you just wrong to pass parameter in ajax request :
this is your code
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
data:'valet_image='+image_code, is wrong pass and change that to data : {vallet_image : image_code}.
just changing the position of encodeURIComponent() helped me
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(encodeURIComponent(e.target.result));
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = image_data;
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}

how to use ajax in magento backend

why ajax call from magento backend(from .phtml) redirects to magento dashboard despite of sending form key properly with form? please help.
in ajax call :
var dataRecord = j('#newForm').serialize();
var url = "<?php echo $this->getUrl('*/*/addNewColumn') ?>";
j.ajax({
type: "POST",
url: url,
data: {data1: dataRecord}
})
.done(function( msg ) {
alert(msg);
});
It worked when i sent the form_key in 'data' of ajax call.
var dataRecord = jQuery('#newForm').serialize();
var url = "<?php echo $this->getUrl('*/*/addNewColumn') ?>";
<?php $k = Mage::getSingleton('core/session')->getFormKey(); ?>
jQuery.ajax({
type: "POST",
url: url,
data: {data1: dataRecord,form_key:'<?php echo $k ?>'}
})
.done(function( msg ) {
alert(msg);
});
Below are the code for ajax in admin panel.
jQuery(".btn_save_email").click(function(){
var data1val = jQuery('.data1val').val();
var data2val = jQuery('.data2val').val();
url = '<?php echo $this->getUrl('moduleName/adminhtml_controllerName/functionName') ?>';
new Ajax.Request(url, {
parameters: {isAjax: 1, method: 'POST',data1:data1val,data2:data2val},
onSuccess: function(transport) {
jQuery('.class').html(transport['responseText']);
}
});
});
var aurl = '<?php echo $this->getBaseurl(); ?>/films/test/ajax';
var data = {};
data['lsize'] = jQuery('#mySlider').slider("values", 0);
data['rsize'] = jQuery('#mySlider').slider("values", 1);
jQuery.ajax({
type: "POST",
url:aurl,
dataType :'json',
data:{ Data },
success:function(response){
jQuery('#output').html(response);
}
});

laravel 4 upvote via ajax post

I can't seem to get my voting system to work in ajax. I'm trying to establish the 'upvote' and have my onclick function call my route and insert a vote accordingly, except nothing happens. I can't see why or where I'm going wrong.
JAVASCRIPT
$( document ).ready(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='up')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-up-on.png" />');
$.ajax({
type: "POST",
url: "http://domain.com/knowledgebase/upvote",
dataType: "json",
data: {id : id},
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
if (name=='down')
{
alert(dataString);
$(this).fadeIn(200).html('<img src="/img/vote-down-on.png" />');
$.ajax({
type: "POST",
url: "downvote",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
</script>
ROUTE.PHP
Route::get('knowledgebase/upvote/{id}', 'PostController#upvote');
POSTCONTROLLER.PHP
public function upvote($id)
{
if (Auth::user()) {
if (Request::ajax()) {
$vote = "1";
$user = Auth::user()->id;
$post = Post::find($id);
$checkvotes = Vote::where('post_id', $post->id)
->where('user_id', $user)
->first();
if (empty($checkvotes))
{
$entry = new Vote;
$entry->user_id = $user;
$entry->post_id = $post->id;
$entry->vote ="1";
$entry->save();
}
}
}
else
{
return "Not an AJAX request.";
}
}
You are using post in your jquery, but you are waiting for a GET route.
Use...
Route::post('knowledgebase/upvote/{id}', 'PostController#upvote');
Additionally, the way you are handling your route may not work correctly with the id. It would be expecting the id in the URL so what you can do is append your id to the url when setting up the ajax.
url: "http://domain.com/knowledgebase/upvote/"+id,
Or not use it at all, take the {id} portion out of your route, and grab it using Input::get('id');

Resources