how to give data messages successfully deleted, on select box? - javascript

I am making a delete choice using javascript, but I have a few problems when the data is deleted, the website does not load so the data is still on the display. to eliminate it I need to press F5, then the data disappears
function deleteAll() {
if ($('input:checked').length < 1) {
alert('Pilih data yang akan di hapus!')
} else if (confirm("Apakah yakin akan menghapus semua data terpilih?")) {
$.ajax({
url: "zakatfitrah/hapus",
type: "POST",
data: $('#form-zfitrah').serialize(),
success: function(data) {
table.ajax.reload();
},
error: function(data) {
alert("Tidak Dapat Menghapus Data!");
}
});
}

First of all, can you specify how you are displaying messages from ajax response if you are using the following method
<div id="myDiv">test</div>
ajax response:
$('#message').html(result.message);
setTimeout(function()
{
$('#message').html("");
}, 3000);

It's not clear what data you would like to delete. What you'll probably need to do is delete the element that holds the data.
Element:
<div id="myDiv">test</div>
Delete:
$('#myDiv').remove();

Related

reloading a function in javascript

I'm initializing three functions on loading the page and then performing some events on click so I want that when a click event is pressed I just reload those functions completely in the given code it loads the function again but the previous one remains there so I want that when I load the function again it should remove the previously loaded one.
$('#locationdeleteconfirm').click(function(e) {
e.preventDefault();
$.ajax({
url: "php/deleteLocationByID.php",
type: 'POST',
dataType: 'json',
data: {
name: $('#dname').val(),
locationID: $('#dlocation').val(),
id: $('#editlocationid').val(),
},
//if user enters correct data and api gives back the data then we run success funtion
success: function(result) {
console.log(result);
//if status of data is ok we fetch the data from fields and put them in results table in html
if (result.status.name == "ok") {
//fetching fields from api and showing them in html table
Swal.fire({
title: "Deleted",
text: "Deleted",
type: "success"
}).then(function() {
$("#locdeleteconfirm").modal("hide");
$("#editlocationmodal2").modal("hide");
$('.modal-backdrop').removeClass('modal-backdrop');
$('#locationtable').load(location.href + " #locationtable>*")
getlocations();
getdepartments();
getallemployees();
});
} else {
//if the upper condition fails
console.log("error");
}
},
//if there is no success in retrieving data from api
error: function(jqXHR, textStatus, errorThrown) {
console.log("error");
$('#txterror').html("Enter Valid Id");
}
});
})
getloactions();
getdepartments();
getallemployees();
these are the three functions that are loading on the page load event I want them to reload once the click event is performed

Third parameter of $.post() is not working

I am sending a post request to the REST web service using the following code:
<script type="application/javascript">
$(document).ready(function() {
$("#logbutton").click(function(event){
$.post(
"http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
{
ephone: $("#mobile").val(),
epassword: $("#password").val()
},
function(data) {
data = $.parseJSON( data );
$(".ray").html("$" + data.tag);
console.log( "You clicked a paragraph!" );
}
);
});
});
The web service gives a JSON response in format below:
{"tag":"login","status":true}
The call from the jquery code is running i.e. the web service is running fine, but the function that I have created to parse JSON is not working.
NOTE:
I tried to run this code without providing any value in the text field. The console displayed the json response and also console.log line. But when I again entered the values into the fields, then it didn't. I am unable to understand this thing.
Anyone having any idea?
Thanks in advance.
You could try the more verbose and detailed form using $.ajax:
$(document).ready(function() {
$("#logbutton").click(function(event) {
var req = {
ephone: $("#mobile").val(),
epassword: $("#password").val()
};
$.ajax({
url: "http://localhost:8080/CredentialsOnDemand/loginexpert/dologin",
data: req,
dataType: 'json',
type: 'POST'
}).done(function(data) {
console.log(data);
$(".ray").html("$" + data.tag);
console.log("You clicked a paragraph!");
}).fail(function(err) {
console.error(err);
});
});
});
This will be easier for you to pinpoint where the error is coming from

Handle different type of PHP responses with AJAX

I am designing some PHP pages to process forms. In these pages I want to redirect if result is successful or print a message if there was an error. Structure of pages is like this:
$arg = $_POST["arg"];
if (isset($arg)) {
if (function($arg)) {
header ("Location: page2.php");
}
else {
echo "Response was not successfully";
}
}
else {
echo "$arg parameter was not defined";
}
When I need to print messages I use cftoast for JQuery (http://www.jqueryscript.net/other/Android-Style-jQuery-Toaster-Messages-Plugin-cftoaster.html)
To handle all forms I am using this Javascript function:
$(document).ready(function() {
$("#asynchronousForm").submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$("body").cftoaster({content: data});
window.location.href = ""; //Refresh page to clear possible errors
}
})
return false;
});
My problem is, when form redirects, sometimes appears problems like no redirection and shows empty toast, refreshing page with duplicated input fields... How can I solve this problem? I am using JQueryMobile as skeleton of my webpage.
A good way to handle AJAX responses is to use JSON.
It will allow you to send multiples data and do a redirect or show message depending of AJAX result.
In PHP you can use json_encode() to convert and array to JSON.
$arg = $_POST["arg"];
if (isset($arg)) {
if (function($arg)) {
exit(json_encode(array('redirect' => 'page2.php')));
}
else {
exit(json_encode(array('message' => 'Response was not successfully')));
}
}
else {
exit(json_encode(array('message' => $arg.' parameter was not defined')));
}
AJAX:
You just have to add dataType: 'json'.
You can also use $.getJSON()
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(json) {
if ( json.redirect )
window.location.href = json.redirect;
else
$("body").cftoaster({content: json.message});
}
})

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

How to compare, then update in AJAX if necessary

I have a list containing news articles in the backend of a site which is then displayed on a homepage. I'd like the homepage to always display the most recent news.
I've never used AJAX before but in pseudo it would need to do the following:
call the homepage using an AJAX-get
Compare the article div with the same div from the AJAX-get.
If the AJAX-get has different content inside the div, display that
Can I do this with Jquery load, or do I need to go into AJAX for this functionality. and if so, could anyone give me a hand with the AJAX itself
trying to use AJAX, i have started using the following code, to no avail
$.ajax({
url: ctx.HttpRoot,
data: { "id": $("newsSliderWrapper").attr("id") },
success: function (data) {
data = $(data).find('div#newsSliderWrapper')
alert(data)
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
AJAX in your case will do the following:
Ajax call will send the recent article ID to the server.
The server will compare the article ID. If the article ID is different, then the server will return the new article content. If the id is same, return different status message.
Ajax call will simply render the content
So
$.ajax({
url : "backendurl",
data : {"id" : $("recentarticleDivId").attr("id")},
// id must be the article ID which you need to match
success : function(data) {
$("#articleDivId").html(data);
},
error : function() {
// your error logic
}
})
$.ajax({
url: "homepage.php",
type: "GET",
data: { id : article_id },
success:function(data){
console.log(data);
// your logic
},
error:function(){
}
});

Categories