How to get post value through ajax in view in Codeigniter - javascript

I tried to receive Ajax response but the response is null.
My HTML Looks like this
<form method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<select class="form-control" class="form-control" id="choose_country">
<option value="">Select a prefered language</option>
<option value="en">EN</option>
<option value="fr">FR</option>
<option value="de">DE</option>
<option value="nl">NL</option>
</select>
</form>
<div id="table_load"></div> <!-- loads search table -->
My Javascript looks like this
<script>
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
$("#choose_country").change(function(){
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {choose_country: choose_country},
dataType: 'json',
async: false,
success: function (response) {
if(response.success == true){
alert('success');
$('#table_load').load('<?php echo base_url(); ?>admin/manage_article/search');
}else{
alert('fail');
}
},
});
});
</script>
My controller looks like this
public function search(){
$choose_language = $this->input->post('choose_country');
$this->load->view('admin/manage_article/search');
}
}
I want to pass the value of select box to the controller and return back the selected value in the page $this->load->view('admin/manage_article/search');
I have tried the above code but the response alerts "fail".
I am new to ajax so pardon me if there are any mistakes in coding.

Try this, in your controller
public function search() {
$choose_language = $this->input->post('choose_country');
$result = ($choose_language) ? true : false;
$this->output->set_content_type('application/json')->set_output(json_encode(array('choose_country' => $choose_language, 'result' => $result)));
}
your jquery will be as below
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url(); ?>admin/manage_article/search",
type: "post",
data: {
choose_country: choose_country
},
dataType: 'json',
async: false,
success: function(response) {
if (response.result) {
alert('success');
$('#table_load').html(response.choose_country);
} else {
alert('fail');
}
},
});
});
});
</script>
I dont know why you are using the ajax, you might have business logic in controller, which you have not shown. If not then you can simply load the value of choose_country in table_load, as below.
<script type="text/javascript">
$(document).ready(function() {
$("#choose_country").change(function() {
var choose_country = $("#choose_country").val();
$('#table_load').text(choose_country);
});
});
</script>

There is no reason to make two calls to the server - once for the ajax call and then again to load html.
To return and load html into the browser via AJAX do this in your javascript.
$("#choose_country").change(function () {
var choose_country = $("#choose_country").val();
$.ajax({
url: "<?php echo base_url('admin/manage_article/search'); ?>",
type: "post",
data: {choose_country: choose_country},
dataType: 'html',
// Forcing synchronous strongly discouraged,
// as it can cause the browser to become unresponsive.
//async: false,
success: function (response) {
$('#table_load').html(response);
},
error: function(xhr, textStatus, errorThrown){
console.log(textStatus, errorThrown);
}
});
});
Your controller will work the way you show it in the question except I don't see where the posted var is used, so you may not receive the language specific html what you want (If that is what you're trying to do).
If you really feel the need to have the return contain a property called result that you can check using if (response.result) {... then you will need a variation on parth's answer to your question. You can add the html to the returned json with this in your controller.
public function search()
{
//What do you do with this?
//You don't show how this is used so I'm mostly going to ignore it.
$choose_language = $this->input->post('choose_country');
$result = !empty($choose_language) ? true : false;
///get the view file as a string of html markup
$html = $this->load->view('admin/manage_article/search', NULL, TRUE);
$out = array('result' => $result, 'html' => $html);
$this->output
->set_content_type('application/json')
->set_status_header('200')
->set_output(json_encode($out));
}
Then your success function would be like this
success: function(response) {
if (response.result === true) {
alert('success');
$('#table_load').html(response.html);
} else {
alert('fail');

Related

Ajax select list

I want to retrive the result of this kind of data list with CakePHP 3
<?= $this->Form->select('notif_message',
[ 'oui' => 'oui', 'non' => 'non'], array('id' => 'notifmess')); ?>
<?= $this->Form->hidden('notifmessage', ['value' => $notif_message]) ;?>
The goal is when a user chosse a value, an Ajax call to this controller be done
public function notifmessage() // mise à jour des paramètres de notifications 0 = non, 1 = oui
{
if ($this->request->is('ajax')) {
$notifmessage = $this->request->data('notifmessage');
if($notifmessage == 'oui')
{
$new_notif_message = 'non';
}
else
{
$new_notif_message = 'oui';
}
$query = $this->Settings->query()
->update()
->set(['notif_message' => $new_notif_message])
->where(['user_id' => $this->Auth->user('username') ])
->execute();
$this->response->body($new_notif_message);
return $this->response;
}
}
And i would like to do this call in Ajax without reloading , i have this script
<script type="text/javascript">
$(document).ready(function() {
$('.notif_message').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: 'select.notif_message' + val,
success: function(data) {
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
});
</script>
he doesn't work, nothing happend but i don't know why, i don't have any message in log, i can't debug without indication what doesn't not work
Thanks
In yout javascript you should use $('#notifmess').change(… or $('[notif_message]').change(… instead of $('.notif_message').change(….
In CakePHP the first argument of the select method will be used as the name attribute of the select tag.
Update:
In your controller you are retrieving the value of $_POST['notifmessage'], which is the name of the hidden input field.
To get the user's choice you either should use $this->request->data('notif_message'); in the controller, or setting up the ajax request to send the data with notifmessage like so:
$('[name="notif_message"]').change(function(){
$.ajax({
type: 'POST',
url: '/settings-notif_message',
data: {'notifmessage' : this.value},
success: function(data) {
// To change selected value to the one got from the server
$('#notifmess').val(data);
alert('ok');
},
error: function(data) {
alert('fail');
}
});
});
(Where in this case this is referring to <select> tag.)
i'm close to success: my ajax call is working, database update is working , i juste need to put the 'selected' to the other , i'm trying with this jquery code
<script type="text/javascript">
$(document).ready(function() {
$('#notifmess').change(function(){
var id = $('#notifmess').val();
$.ajax({
type: 'POST',
url: '/instatux/settings-notif_message',
data: {'id' : id},
success: function(data){
$('#notifmess option[value="'+data.id+'"]').prop('selected', true);
},
error: function(data)
{
alert('fail');
}
});
});
});

unable to get value in controller from jquery, ajax in php code igniter

AJAX:
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
//alert(BASE_URL);
$.ajax({
type: "POST",
ContentType: 'application/json',
data: data,
url: BASE_URL + 'index.php?deo/dashboard',
error: function () {
alert("An error occoured!");
},
success: function (msg) {
alert('result from controller');
}
});
alert(data);
});
});
CONTROLLER:
public function dashboard() {
$data = $this->input->post('data');
$data = json_decode($data);
echo "<script>alert('count ".$data."');</script>";
}
Am trying to send value from my jquery, ajax to controller, am able to get value from my view page to jquery page and able to print that. But unable to send the value from ajax page to controller page, after sending the data i got the success data. but unable to get and print the data in my controller page. Thanks in advance
If your using firefox a good thing to use is firebug add on and then you can use the console to check for errors on there. To see if the ajax has any errors while sending.
Remove question mark after index.php? and I think your base url is not working correct try just.
Url
// With index.php
url: 'index.php/deo/dashboard',
// Or without index.php
url: 'deo/dashboard',
Or
// With index.php
url: <?php echo site_url('index.php/deo/dashboard');?>,
// Or without index.php
url: <?php echo site_url('deo/dashboard');?>,
Script
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
$.ajax({
type: "POST",
data: data,
url: 'index.php/deo/dashboard',
// url: <?php echo site_url('index.php/deo/dashboard');?>,
success: function (msg) {
alert('result from controller');
},
error: function () {
alert("An error occoured!");
}
});
alert(data);
});
});
Controller
public function dashboard() {
$data = $this->input->post('data');
echo "<script>alert('count ".$data."');</script>";
}

AJAX not sending data

I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }

Jquery AJAX with codeigniter, always returns error

I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.

Ajax search - Laravel

I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.

Categories