I have a system implemented in CodeIgniter, I am trying to send some data in a text area of Rsform component via POST to the url referring to my CodeIgniter system, I have tried usign AJAX request to send the post data using the following code
<script>
alert("jsc");
var data;
data='test from joomla!';
$.ajax({
type: "POST",
url : 'http://localhost/cii/index.php/login/getNews/',
data: {news:data},
cache: false,
success: function(html){
alert(html);
}
});
getNews controller:
function getNews() {
//print_r($this->session->userdata);
header('Access-Control-Allow-Origin: *');
echo "news is ".$news=$_POST['news'];
$data = array ( 'username' => "null", 'is_logged_in' => false, 'news'=>$news);
$this->session->set_userdata($data); //var_dump($_POST); //
print_r($this->session->userdata); session_start(); echo session_id();
}
but it failed, is there any other options ?
Use something like Firebug in mozilla firefox to observe what data is being posted to the app to check if your ajax call is working.
Then in your codeigniter controller method, simply put this code to see if the data is getting to it.
function getNews()
{
foreach($_POST as $key => $val)
{
$options[$key] = $this->input->post($key);
}
var_dump($options);
}
Related
I'm currently building a web application using CodeIgniter 4. In one of my forms, I need ajax to send a post request and get the data result to modify the form base on item selected on a combo box.
The first requests were always okay, but it won't work for the next one. When I refresh the page, it redirects me to login page, due to my filter. It turns out that the AJAX request either destroy all my sessions, or update it to the new ones.
this is my ajax :
`
$('#penilaian_jenis').on('change', function() {
$.ajax({
OST type: "P",
url: '<?= base_url('guru/penilaian/get_nilai') ?>',
data: {
'kelas_id': '<?= $kelas->kelas_id ?>',
'kd_id': '<?= $kd->kd_id ?>',
'penilaian_jenis': $('#penilaian_jenis').val(),
},
dataType: 'json',
success: function(data) {
var result = JSON.parse(data);
alert(result);
}
})
})
`
This is my Controller :
`
public function get_nilaii()
{
echo json_encode('success');
}
`
This is how I stored my session at the auth controller:
$data = [
'user' => $user,
'guru' => $model->where('user_id', $user->user_id)->first(),
'guru_logged_in' => 1,
];
session()->set($data);
My Ajax codes I user are the simplest one. Can Anyone help give me the solutions to this problem, or recommend me another way to do HTML request without losing all my sessions?
Sorry for bad grammar, and thank you in advance
i am typing text in text area
<input placeholder="DISCOUNT COUPON" type="text" id="coupon">
Sending that text to controller using ajax;
$.ajax({
type: "POST",
url: "applyCoupon",
data:{
coupon: $('#coupon').val(),
course_id: {{$course->id}},
_token: {{ csrf_token() }},
},
success: function(dataResult){
alert("success");} // why i am not GETTING this alert?
Controller:
public function applyCoupon(Request $request)
{
$result=new \stdClass();
$coupons = Coupons::select('discount_percentage')->where('coupon_code',$request->get('coupon'))
->where('course_id',$request->get('course_id'))
->get();
$course = Course::findOrFail($request->get('course_id'));
$discounted_price= ($course->price) - (($course->price)*($coupons[0]->discount_percentage)/100);
$result->val = $discounted_price;
$result->statusCode = 200;
return json_encode($result);
}
Web.php:
Route::post('course/applyCoupon', ['uses' => 'CoursesController#applyCoupon', 'as' => 'courses.applyCoupon']);
everything seems fine, but why success function is not running?
You should be using routes/api.php instead of routes/web.phpin the first place.
Also, log error by adding
...
error: function (request, error) {
console.log(error);
alert("Error");
},
That should give you a clue. Could be anything depending on your setup.
You're not using the full URL you setup in your routes/web.php
Change
url: "applyCoupon",
to
url: "course/applyCoupon",
or even better would be to use the route name you provided
url: "{{route('courses.applyCoupon')}}",
Give correct route to your ajax call
Pass this in your ajax url.
url: "{{ route('courses.applyCoupon' }}"
if still not working, then Check your network tab in inspect tool
Click on the ajax call and it will show you the detail on your right side.
post here what you are getting there.
You need to give the response in return of ajax call:-
use Response;
return response()->json(['message' => 'error', 'data' => $data]);
I'm trying to send some data from my view to my controller via ajax. How do I retrieve this data in my action?
I've tried jQuery's $.ajax and $.post methods, providing the url and data, but using $this->data, $this->request->data, $_POST, $_GET or $_REQUEST doesn't work (all return as empty arrays).
$.ajax({
url: "<?php echo Router::url( array("controller" => "Progression", "action" => "submit", $user['User']['id']) ); ?>",
type: 'post',
data: { name: "John" }
}).done( function(data) {
console.log(data);
});
function submit() {
$this->request->allowMethod('ajax');
$this->autoRender = false;
$data = array();
$data['answer'] = $this->request->data; // or any of $_POST, $_GET, etc.
return json_encode($data);
}
My console always keeps printing {"answer":[]}. I checked the network tab of my devtools and the data is successfully listed under Form data, yet I can't seem to get hold of the data in the action.
EDIT:
Thanks to Greg Schmidt I found out that my request indeed got redirected: first it gives me a 302, then it makes a new request without the post data and returns a 200. I just can't find what the critical difference is between the two requests (URLs look the same, no case difference or anything). Can anybody help me with that?
First request:
Second request:
I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories.
So far, I have the client-side code that works when not calling a WP function (this code is in a theme page):
jQuery('#cat-location-main').change(function () {
var optionSelected = jQuery(this).find('option:selected');
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
console.log(valueSelected);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'myajax-get-subcat',
category: valueSelected,
// send the nonce along with the request
categoryNonce: '<?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?>'
},
success: function(data, textStatus, jjqXHR) {
console.log(data);
},
dataType: 'json'
});
});
And I have this in the functions.php:
add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat');
function myajax_get_subcat() {
$nonce = $_POST['categoryNonce'];
$main_category = $_POST['category'];
if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce'))
die ( 'Busted!');
if(function_exists('wp_dropdown_categories')==true) {
echo 'true';
} else {
echo 'false';
}
wp_dropdown_categories('taxonomy=category&selected=1&echo=1&orderby=NAME&order=ASC&hide_empty=0&hide_empty=0&hierarchical=1&depth=1&id=cat-location-secondary&child_of='.$main_category);
exit;
}
Now I get a "true" on the client side when commenting wp_dropdown_categories line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup).
Also, not working even if I add require_once(__DIR__.'/../../../wp-load.php'); but it works if I use GET in browser (for the functions.php).
Any help would be greatly appreciated!
My problem was because I do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't.
I try to send a datetime ( 2013-03-12 09:43:09 ) string from a form via ajax to the db. I used follwoing JS
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {
end: $('#endtime').val()
},
url: 'index.php?option=com_sprojectfree&view=checkin&task=saveSlot&format=raw',
success: function(data) {
console.log(data);
}
});
The url points to the method saveSlot in my controller.php
public function saveSlot ()
{
$input = JFactory::getApplication()->input;
$data = new stdClass();
$data->end = $input->get('end');
db = JFactory::getDBO();
$result = $db->insertObject( '#__spf_chunks', $data, 'id' );
...
}
The data objects look like this:
stdClass Object
(
[end] => 2013-03-12095730
)
and the POST source like this:
end=2013-03-12+09%3A57%3A30
I tried all combinations of charactersets, urldecode() and encodeURIComponent() in JS but nothing gives me the correct string with : back to save it in the db. What could I do? Thanks in advance.
Try this
echo urldecode("2013-03-12+09%3A57%3A30");
the decoding in php side.
Also normally when you call ajax the content type is no need mention.
Instead of passing data as object you can pass like this
var data = "end="+$('#endtime').val();
data: encodeURIComponent (data)
In controller you can access via JRequest::getVar('end');
Hope it helps