Ajax select list - javascript

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

Related

Laravel & Ajax - Insert data into table without refreshing

First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.

How to get post value through ajax in view in Codeigniter

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

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 display message while php processing

I'm using jQuery ajax call to post process a form.
I want to display a loading message or image while the form is processed and when the action is completed to display a complete message.
How can I do it?
This is my jQuery code.
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
Before ajax function display your loader and inside the success function from your ajax hide it.
As you can see in my example i inserted $('.loader').show(); and $('.loader').hide();
$('.loader').show();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
success: function(data) {
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
$('.loader').hide();
}
});
According to the PHP docs:
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
You should take a look at : https://github.com/blueimp/jQuery-File-Upload/wiki/PHP-Session-Upload-Progress
I think this will definitely help you out!
Display your message just before launching $.ajax();
And close it in the success (and error) callback functions.
example :
$s('body').on('click', '#group-update', function() {
var formInputs = $s('input').serializeArray();
var groupId = $s(this).data('group');
var error = $s('#modal .info');
var tr = $s('#dataT-attrgroup').find('tr.on_update');
formInputs.push({
name: 'id',
value: groupId
});
var dlg = $s('<div/>').text('your message').dialog();
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
error:function() {
dlg.dialog('close');
},
success: function(data) {
dlg.dialog('close');
if(data.response === false){
error.addClass('info-error');
error.html(data.message);
}else{
oTable.row(tr).data(data).draw();
$s('#modal').modal('hide');
tr.removeClass('on_update');
$s.growl.notice({
title: 'Success',
message: 'Grupul de atribute a fost actualizat'
});
}
}
});
});
If you go through ajax section of jquery documentation you will notice some more method like success ie error, beforesend, complete etc. Here is the code snippet.
$s.ajax({
type: 'post',
url: 'index.php?controller=attribute&method=updateGroup',
data: formInputs,
dataType: 'JSON',
beforeSend : function(){
// load message or image
},
success: function(data) {
// write code as per requirement
},
complete : function(){
// load complete message where you previously added the message or image, as a result previous one will be overwritten
}
});

Categories