ajax is not sending data to controller - codeigniter

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?
}

Related

How can we check data in controller sent by ajax (not in response) in codeigniter?

I want to send array data from javascript to a view page..But the array isn't getting passed to the view page. The codes are described below:
//array getting passed from this page
<input type="button" name="b">
<script src="<?php echo base_url().'assets/js/' ?>jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("input[type='button']").click(function(){
question_array=[];
question_array['what is our nationality?']='Bangladeshi';
question_array['what is our national fish?']='Ilish';
number=10;
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "admin/test",
dataType: 'json',
data: {question_array: question_array,number:number},
success: function(result) {
if (result) {
window.location="<?php echo base_url().'admin/test_page'; ?>";
}
}
});
});
});
</script>
`
In my controller::
public function test()
{
$question_array = $this->input->post('question_array');
$number = $this->input->post('number');
$this->session->set_flashdata('number', $number);
$this->session->set_flashdata('question_array', $question_array);
echo json_encode($number, $question_array);
}
function test_page()
{
$this->load->view('admin/test_page');
}
//The page where I'm sending the array(Question_array not found)
$number = $this->session->flashdata('number');
$question_array = $this->session->flashdata('question_array');
echo $number;
print_r($question_array);
Hope this will help you :
Convert array to object and remove spaces between array keys, like this :
<script type="text/javascript">
$(function(){
$("input[type='button']").click(function(){
var question_array = [];
question_array['what-is-our-nationality'] = 'Bangladeshi';
question_array['what-is-our-national-fish'] = 'Ilish';
var number = 10;
var obj = $.extend({}, question_array);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('admin/test'); ?>",
dataType: 'json',
data: {question_array : obj, number : number},
success: function(result) {
if (result)
{
window.location="<?php echo base_url().'admin/test_page';?>";
}
}
});
});
});
</script>
You may better try JSON.stringify to solve this,
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "admin/test",
dataType: 'json',
data: JSON.stringify({question_array: question_array,number:number}),
success: function(result) {
if (result){
window.location="<?php echo base_url().'admin/test_page'; ?>";
}
}
});
I hope the code below can help you. You need post the string i correct JSON format by using stringify. The server will receive the json and decode it to object.
function send(){
var url = "http://localhost/some_url_here";
var data = JSON.stringify({
Bangladeshi: 'what is our nationality?',
Ilish: 'what is our national fish?'
});
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: data,
}).done(function(output){
alert('output is '+ JSON.stringify(output));
});
}
function receive()
{
$result = '';
$stream_clean = $this->security->xss_clean($this->input->raw_input_stream);
$request = json_decode($stream_clean);
$Bangladeshi = $request->Bangladeshi;
$Ilish = $request->Ilish;
$result = array("status" => 200, "id" => $Bangladeshi+$Ilish);
header('Content-Type: application/json');
echo json_encode($result);
}

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');

Yii: get result for ajax request

I have a anchor;
When I click on it, the following code executes:
<script>
$('.viewcnp').click(function() {
event.preventDefault();
var r = prompt("Enter your password:");
if (r) {
$.ajax({
type: "POST",
url: '<?php echo Yii::app()->baseUrl; ?>' + '/index.php/admin/user/viewCnp/id/' + '<?php echo $model->id; ?>',
data: {'password': r},
success: function(data) {
$('.cnpdecrypted').text(data);
},
dataType: 'text'
});
}
});
</script>
this code makes a request to this action:
public function actionViewCnp($id) {
$model = User::model()->findByPk($id);
if ($model) {
return '{"data":"' . Utils::decrypt_cnp($model->cnp) . '"}';
}
else
return false;
}
If in the action I echo the cnp decripted, its there, but i can't set the value because I don't receive it on success.
You should simply use echo instead of return :
if ($model) {
echo Utils::decrypt_cnp($model->cnp);
}

Zend Framework: Ajax post data

That is my function:
function deleteAutoAd(id, title) {
alert(title);
$.ajax({
dataType: 'json',
url: '/ajax/deleteautoad',
type: 'POST',
data: {
id : id,
title : title
},
success: function(data) {
alert(data);
}
});
}
In this function when I try alert(title) and popup 'This is title'(because title = 'This is title'). But in ajax/deleteautoad I try this:
public function deleteautoadAction() {
if ($this->getRequest()->isPost()) {
echo $param1 = $this->_request->getParam('id');
echo $param2 = $this->_request->getParam('title');
}
}
Echo param1 show 5, but echo param2 don't show nothing.
i think you should try :
function deleteAutoAd(id, title) {
alert(title);
$.ajax({
dataType: 'json',
url: '/ajax/deleteautoad',
type: 'POST',
data: {
'id' : id, // Note the quotes
'title' : title // Note the quotes
},
success: function(data) {
alert(data);
}
});
}
regards
mimiz
I agree with the above answer
Also, For my application, I also have to post the full url. So you might want to try
var root = location.protocol + '//' + location.host;
and then on your url
url: root+'/ajax/deleteautoad',
You should return from controller a valid JSON with Success status.
public function deleteautoadAction() {
if ($this->getRequest()->isPost()) {
$x->Status = 'Success';
$x->Message = $this->_getParam('id') . $this->_getParam('title');
$this->_helper->json($x);
}
}
And also you should change your alert statement
function deleteAutoAd(id, title) {
$.ajax({
dataType: 'json',
url: '/ajax/deleteautoad',
type: 'POST',
data: {
id : id,
title : title
},
success: function(data) {
alert(data.Message);
}
});
}
Moved from the OP question to a CW answer:
I fixed the problem by removing: dataType: 'json'.

Resources