Save button with Ajax - ajax

I'm making an online form for customers and now adding a submit button which saves the record in database. Is there any way i can submit data using AJAX ?

Take a look at jQuery. It will do the job for you.

Here is some sample jQuery code which may help:
$('.submitter').click(function() {
$.ajax({
'url' : 'url.php',
'type' : 'POST',
'data' : $('.myForm').serialize(), //Gets all of the values from a form
'success' : function(data) {
if (data == 'saved') {
alert('Form was saved!');
}
}
});
});
Hope that helps,
spryno724

Related

How Can I Prevent AJAX From Destroying My Session?

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

Making simultaneous AJAX calls to separate Django views

I have a Django view that runs a particular function when a POST request is received.
Snippet:
def run_function(request):
if request.method == 'POST':
run_some_function()
This is called via AJAX as follows:
$.ajax({
'type' : 'POST',
'url' : '/run_function/',
'data' : data,
'success' : function(json) {
// Display results to user
}
});
This works as expected. However, this particular function can take a while to run, so I want to display progress information to the user.
Luckily, I have another function that can return the progress (an integer between 0-100) of the task.
Snippet:
def get_progress(request):
progress = calculate_progress()
return HttpResponse(json.dumps(progress), content_type="application/json")
I can then make an AJAX call every X seconds to get the progress and update my progress bar:
function check_progress() {
$.ajax({
'type' : 'POST',
'url' : '/get_progress/',
'success' : function(response) {
if (response >= 100) {
// Update progress bar to 100% and clearInterval
} else {
// Update the progress bar based on the value returned by get_progress
}
}
});
}
var check = setInterval(check_progress, 500);
The problem is...how can I do both simultaneously? I need to be able to make the AJAX call to run the function and make the AJAX calls to monitor progress, at the same time.
Are there any suggestions for how to accomplish this? Or perhaps a better design than making two AJAX calls?
Thanks for any help!
The A in AJAX stands for Asynchronous. You don't need to do anything special. If you have your views and progress sorted out, all you need to do is:
$.ajax({
'type' : 'POST',
'url' : '/run_function/',
'data' : data,
'success' : function(json) {
// Display results to user
}
});
var check = setInterval(check_progress, 500);

How to pass multi rows edited in jqgrid to server controller?

I'm new in jqgrid.
I want to pass multi rows edited in jqgrid to pass MVC server controller.
controller expects json string type of data.
how my jsp pass all rows to controller?
jQuery("#save").click( function(){
alert("enter save fn");
var gridData=jQuery("#gridList").jqGrid('getGridParam','data');
jQuery.ajax({
url : '/uip/web/p2/saveEmployeeList.dev'
,type : 'POST'
,cache : false
,data : JSON.stringify(gridData)
,contentType : 'application/json; charset=utf-8'
,dataType : 'json'
})
});
I print out HttpServletRequest in controller. there is one row exist.
even little clue would be helpful.
If I understand you correctly you want to save all edited rows by one Ajax action instead of a Ajax request after any row is edited?
If so, this might be the solution. Instead of Ajax you use the 'clientArray' option in your configuration as your URL parameter. This causes jqGrid to save every edited row internally in JavaScript and post nothing to your server.
With a onclick on a save button you could do something as follows:
var changedRows = [];
//changedRows is a global array
if($('#save-rows').length) {
$('#save-rows').click(function() {
var postData = {}
$.each(changedRows, function(key) {
postData[key] = $('#paymentsgrid').jqGrid('getRowData', this);
});
$.post(baseUrl + '/controller/action', {
'data' : postData
}, function(response) {
$('<div></div>').html(response.content).dialog({
'title' : 'Message',
'modal' : true,
'width' : 800,
'height' : 400,
'buttons' : {
'OK' : function() {
$(this).dialog('close');
}
}
});
if(response.reload) {
$('#grid').trigger('reloadGrid');
}
}, 'json');
});
}
Also important is to specify a save event in your grid:
$('#paymentsgrid').jqGrid('saveRow', paymentController.lastsel, null, 'clientArray', null, function(rowId) {
changedRows.push(rowId);
});
You might should modify or optimize some things but in the basic, this should work or give you an idea how to accomplish what you want.

How do I perform a jQuery ajax request in CakePHP?

I'm trying to use Ajax in CakePHP, and not really getting anywhere!
I have a page with a series of buttons - clicking one of these should show specific content on the current page. It's important that the page doesn't reload, because it'll be displaying a movie, and I don't want the movie to reset.
There are a few different buttons with different content for each; this content is potentially quite large, so I don't want to have to load it in until it's needed.
Normally I would do this via jQuery, but I can't get it to work in CakePHP.
So far I have:
In the view, the button control is like this:
$this->Html->link($this->Html->image('FilmViewer/notes_link.png', array('alt' => __('LinkNotes', true), 'onclick' => 'showNotebook("filmNotebook");')), array(), array('escape' => false));
Below this there is a div called "filmNotebook" which is where I'd like the new content to show.
In my functions.js file (in webroot/scripts) I have this function:
function showNotebook(divId) {
// Find div to load content to
var bookDiv = document.getElementById(divId);
if(!bookDiv) return false;
$.ajax({
url: "ajax/getgrammar",
type: "POST",
success: function(data) {
bookDiv.innerHTML = data;
}
});
return true;
}
In order to generate plain content which would get shown in the div, I set the following in routes.php:
Router::connect('/ajax/getgrammar', array('controller' => 'films', 'action' => 'getgrammar'));
In films_controller.php, the function getgrammar is:
function getgrammar() {
$this->layout = 'ajax';
$this->render('ajax');
}
The layout file just has:
and currently the view ajax.ctp is just:
<div id="grammarBook">
Here's the result
</div>
The problem is that when I click the button, I get the default layout (so it's like a page appears within my page), with the films index page in it. It's as if it's not finding the correct action in films_controller.php
I've done everything suggested in the CakePHP manual (http://book.cakephp.org/view/1594/Using-a-specific-Javascript-engine).
What am I doing wrong? I'm open to suggestions of better ways to do this, but I'd also like to know how the Ajax should work, for future reference.
everything you show seems fine. Double check that the ajax layout is there, because if it's not there, the default layout will be used. Use firebug and log function in cake to check if things go as you plan.
A few more suggestions: why do you need to POST to 'ajax/getgrammar' then redirect it to 'films/getgrammar'? And then render ajax.ctp view? It seems redundant to me. You can make the ajax call to 'films/getgrammar', and you don't need the Router rule. You can change ajax.ctp to getgrammar.ctp, and you won't need $this->render('ajax');
this is ajax call
$(function() {
$( "#element", this ).keyup(function( event ) {
if( $(this).val().length >= 4 ) {
$.ajax({
url: '/clients/index/' + escape( $(this).val() ),
cache: false,
type: 'GET',
dataType: 'HTML',
success: function (clients) {
$('#clients').html(clients);
}
});
}
});
});
This the action called by ajax
public function index($searchterm=NULL) {
if ( $this->RequestHandler->isAjax() ) {
$clients=$this->Client->find('list', array(
'conditions'=>array('LOWER(Client.lname) LIKE \''.$searchterm.'%\''),
'limit'=>500
));
$this->set('clients', $clients);
}
}
This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.
$('#myForm').submit(function(e) {
// Catch form submit
e.preventDefault();
$form = $(this);
// console.log($form);
// Get form data
$form_data = $form.serialize();
$form_action = $form.attr('action') + '.json';
// Do ajax post to cake add function instead
$.ajax({
type : "PUT",
url : $form_action,
data : $form_data,
success: function(data) {
swal({
title: "Updated!",
text: "Your entity was updated successfully",
type: "success"
},
function(){
location.reload(true);
});
}
});
});

problem using Jeditable + ajaxUpload

I managed to use jEditable selects, inputs and textareas quite easily, but I have problems with uploading files :
I can't manage to send $_POST values along with the $_FILES values, and no extra data is passed through submitdata...
Here is my code :
$(".photo").editable("class/save.php",
{
indicator : "<img src='img/indicator.gif'>",
type : 'ajaxupload',
submit : 'Envoyer',
cancel : 'Annuler',
tooltip : "Cliquer pour modifier...",
submitdata : {row: "photo"}
});
When I do a print_r($GLOBALS);, $_GET and $_POST arrays are empty...
Did I miss something ?
Thank you
The jeditable.ajaxupload plugin does not submit the 'submitdata' setting's.
I did some modification to the plugin to include submitdata and also the element's id in the submission (through querystring). You have to use $_GET to get the extra data.
Here is the link : https://github.com/tuupola/jquery_jeditable/pull/38/files
or you could just set the
$.ajaxFileUpload({
url: settings.target,
secureuri:false,
/// Add the following line
data : settings.submitdata,
fileElementId: 'upload',
dataType: 'html',
success: function (data, status) {
alert(data);
$(original).html(data);
original.editing = false;
},
error: function (data, status, e) {
alert(e);
}
});

Resources