Update Data in Table on Save with No Refresh (Ajax/JavaScript) - javascript

I have the following function that is the event listener function to a button. When the button is clicked, this function is called and it should be updating an HTML table. It is doing so properly, but not until the user refreshes the page. What must I change on the front-end in order to make the table updates occur as soon as this button is clicked rather than forcing the user to refresh the page? Thank you!
function dialogWindowSaveAddressBookEditsButton_Click(addressBookObject) {
$.ajax({
type: "POST",
url: "/Services/AsyncServices.svc/DialogWindowSaveAddressBookEditsButton_Click",
contentType: "application/json",
data: JSON.stringify(addressBookObject),
success: function (result) {
if (result.d == false) {
...
}
else {
...
}
}
});
}

You have the result from your post request - you need to format it and then set the html table (or whatever component is it) to display that data.
You are not providing enough information (as of are you using any framework or just pure javascript), so I would suggest you to look into how data binding works for web development. https://www.wintellect.com/data-binding-pure-javascript/
If you are using a framework (AngularJs, React, Ember etc) look into how to bind data - it is usually very simple

When you call an ajax request then you must handle its response and update DOM accordingly. If the request is returning HTML then you can just render that under any element you want like this:
$(‘#element).html(response)
If it’s returning JSON then you should set values accordingly to your DOM elements by using Jquery:
$(“.your-table or td”).text(resp.value)

I resolved the issue through adding the following to the success property:
location.reload(true);

Related

Limiting AJAX results, and getting different outputs

I have recently started to use AJAX with JQuery. I now know how to limit results in AJAX GET requests. However, I have no idea how to make a client-side button to load more requests. Say I have 100 people on the JSON file and i want to load 3 at the time. If the button is pressed, the next three load and the last three disappear.
I used this to limit:
$.ajax({
type: "GET",
url: "/people",
data: {limit: 3, order: 'desc'},
dataType: "json",
success: function(data) {
// Do some awesome stuff.
}
});
Other than limiting results, I really have no idea how to load more results.
What you need is to determine the manner in which you can execute your ajax request such as using a button that will load more data.
Firstly, you've mentioned you can successfully return the limited data by passing parameters to your ajax request, that's great.
You can wrap your ajax request in a function that will allow you to pass parameters such as limit and order direction. Now, I won't go all out here since there's very little information to work with. But to create a button that you can click that will load more data is something that can be demonstrated here.
Here's your AJAX request. We can wrap it in a function that accepts parameters. For example, limit defaults to 3, order defaults to "desc". The possibilities here are endless. You'll obviously want offsets and such but that you can work with as you go along. The purpose of this is only to demonstrate how you could create a button to fetch more data.
jQuery has a shorthand method called $.getJSON which will load JSON-encoded data using a GET HTTP request.
So here's the function which we can later call from the click of a button.
function fetchPeople(limit = 3, order = "desc") {
$.getJSON(
"/people",
{
limit: limit,
order: order
},
function (data) {
// Do something with your data
}
);
}
The button may be something like this.
<button type="button" id="loadMore">Load more</button>
In jQuery you can bind event listeners that will trigger, e.g. on click, and this listener will trigger your function that will go off to fetch whatever it is you've configured in the wrapper function.
$("#loadMore").on("click", function () {
fetchPeople();
});
There are a plethora of plugins for jQuery and code examples across StackOverflow and the WWW in general.
But I'm hoping this steers you in the right direction.

How to display a hidden field value after calling location.reload() in ajax success

Display a hidden field value after calling location.reload() .
var ajaxRequest = $.ajax({
type: "POST",
url: "my url",//locating to another project action method which is already deployed and running in server
contentType: false,
processData: false,
data: data
});
ajaxRequest.done(function (xhr, textStatus) {
location.reload();//reloading page
$('#imageUploadScs').show();//displaying hidden field after reloading page
});
When you reload, the page reloads. So any changes you've made to the state of the page are lost.
So you have two options:
Don't reload. This is the preferred option. You're already using AJAX, simply update the state of the page as needed. You shouldn't have to reload at all.
Before reloading, persist some flag somewhere (local storage? cookie? something of that nature) which indicates that the field should be shown. In the page's start-up code (you're using jQuery, so I assume a document.ready handler would be standard here) check for that flag and show the field.
The first option is certainly preferred. But the second option might structurally look something like this:
$(function () {
var shouldShowField = getPersistedFlag();
if (shouldShowField) {
$('#imageUploadScs').show();
}
});
// elsewhere...
ajaxRequest.done(function (xhr, textStatus) {
setPersistedFlag();
location.reload();
});
The implementations of getPersistedFlag and setPersistedFlag would be what's described above. They would read and write whatever data you want to persist to whatever storage mechanism you choose. (Any of which have many examples available.)
If it seems like that's over-complicating the effort, you're probably right. Which is why the first option of not reloading the page in the first place is preferred.

setting <input> checked via jquery (selector).prop() function not working for dynamic html

I've got a page that on $(document).ready, calls a javascript function that creates some input controls dynamically based on context of page request via a ajax call to the server.
I need to set one of the dynamically created controls (input checkbox) to be checked by default.
I've tried setting it via $(#id).prop('checked', true); after the call to the server but it does not work. My guess is that the field does not exist yet...
How can I modify a html control dynamically created from an ajax call?
Instead of using prop to have it checked initially, set checked in the HTML.
<input type="checkbox" id="#" value="sample" checked>
This can be done static or dynamically. Simply add checked as part of your dynamic generation. Then you bring in prop to suit your needs.
You can use attr and removeAttr methods to check/uncheck a checkbox/radio input.
// to check a checkbox or radio button
$(selector).attr("checked","checked");
// to uncheck a checkbox (radio button will be cleared on another check)
$(selector).removeAttr("checked");
and if you're creating the input from AJAX, you can put this on the AJAX success or complete function after the DOM is updated. But #Aaron is right, setting the value on generation on the server side is more effective.
The answers provided are good and could work but not with my problem. This is because the javascript that generates these html elements is a abstracted file that generates html input controls for many different applications. I can't modify that file to specifically check a checkbox for one case.
What I did was, inside of this generic javascript file, call a setDefaults() method IF IT EXISTS in the current context. So the callers of this script can choose to implement a setDefaults() that will be called by the generic script, after the html has been generated.
function initReport(reportID) {
//request the data needed to create the dynamic html from the server:
$.ajax({
type: "GET",
url: "/report.aspx/GetReportDetails?reportID=" + reportID,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (result) {
reportFormData = JSON.parse(result.d);
//request our generic html template:
$.ajax({
type: "GET",
url: "/assets/modules/report/Templates/Form.html"
}).done(function (result) {
$("#Form").html(result);
//generate html from server data:
buildViewModel(reportFormData);
buildPage(reportFormData);
kendo.bind($("#Form"), viewModel);
//call "setDefaults" function only if it has been defined (in the current report template)
if (typeof setDefaults === "function")
{
setDefaults();
}
});
}).fail(function (jqXHR, textStatus, err) {
console.log("An error has occurred: " + err);
});
...
}

How to execute a php file into jquery without post and get method?

I'm trying to program a custom contact content manager in HTML/CSS with PHP/mySQL/Jquery to make it dynamic.
I have my login form which send the $_REQUEST to my connection.php, when the auth is correct, I return json to my Jquery and when it is good, I use window.location.replace to redirect the user to the control panel.
When I'm on the index.php of the control panel, I want to check if the user's session_id is into my sql database and if it exceeded the expiration time.
I have my functions which check this and return the good value but I want to execute it and send the result to my jquery without using GET or POST method.
If I remember, you have
$.ajax({
type: "POST", //or GET method
dataType: "json",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function({
}),
error: function({
})
});
But you must specify the element "data" no? can I use it without data and put "file.php" as url without POST or GET method?
I want to get into my success method the result of my php functions :
if the json return false, the user can access the page.
if the json return true, I will logout the user and redirect him to the login.php
I'm doing this system because I don't want anybody can access the control panel by writing the correct url or after 4 days.. I put an expiration time to one hour (for the moment) for anybody who login into the control panel and I check on all page that the expiration time isn't exceeded.
I saw that using 'window.location.replace' doesn't allow to return to the previous page.. has anyone a solution? I don't want to have an event to redirect the user, only redirect him to another url (my file.php) after a condition.
Currently, I use it to execute php without POST, GET method with $.ajax..
$(document).ready(function(){
$(function(){
var ticket = '<? echo $tickets; ?>';
console.log(ticket);
if ( ticket === '' )
$(".new_ticket h2").after('<p>Aucun nouveau ticket.</p>');
else
{
console.log('else');
$(".new_ticket h2").after('<p>Il y a un ticket.</p>');
}
});
});
I have a last question, when I write :
$(document).ready(function(){
$(function(){
}
Is it directly executed by jquery when the DOM is ready? can I write mutliple '$(function(){}' in a file ?
Thanks for the help!
What is the problem with using POST or GET? It works perfectly fine.
Here foobar.php returns a json object with status in it. Change it to whatever your script return.
$.post('foobar.php', function(data) {
if( data.status === false) {
//All good
}else {
//Redirect
window.location.href = "http://newpagehere.com/file.php";
}
});
With window.location.href you will be able to use the back and forward buttons.
And yes, when using $(document).ready(function() { }); it runs when the DOM is ready.
http://api.jquery.com/ready/
One last thing is that I would not rely on Javascript here, I would do all checking with PHP instead when the user changes page. I would also handle the redirection there.

update the div display after jquery post without reloading the page in mvc3

What is the bestHi everyone, a MVC3 newbie here! please take a look at these:
in my View page, i have there:
<div id = "AccounStatusDiv" class="display-field">
#Html.DisplayFor(m => m.AccountStatus)
<input id="btnBool" type="button" class="btnGrid ActStatBtn" value="#(Model.AccountStatus ? "Deactivate" : "Activate")" onclick="ChangeStatus()"/>
</div>
and a script:
<script type="text/javascript">
function ChangeStatus() {
$.post('#Url.Action("SetAccountStatus", "User")',
{ UserName: "#(Model.UserName)",
accountStatus: "#(Model.AccountStatus)" });
// change the display of the AccounStatusDiv elements, or maybe just reload the div element if possible. is it?
}
</script>
while in my Display Template, i have there:
<div id = "AccountStatusDiv" style="display:inline-block;">
<img src="#Html.Custom().ResolveImage((bool)Model ? imgPositive : imgNegative)" alt="#Model" />
<label> #ResourceManager.Localize(resource, display)</label>
</div>
in the controller:
public ActionResult SetAccountStatus(string userName, bool accountStatus)
{
SecurityManager.GetMembershipProvider().SetStatus(userName, !accountStatus);
return AjaxResult.JsonRedirect("/User/ViewUser?username=" + userName);
}
The results are shown only after I reload the page.
I want to display the updated img, label and btnBool elements right after clicking the btnBool without reloading the whole page. What is the best way in such case?
Please post your code suggestions, it would be a great help for me!
Thanks in advance!
You're only using $.post() to send data (request) to the server. AJAX can be two-fold: send a request, and receive the corresponding response. In your code, you're not receiving data back (or, at least, making the necessary arrangements so that you are).
If the SetAccountStatus action of your UserController is set to return some data back (maybe through return Json(), or similar), you can modify the $.post() call to receive it, and have your Javascript react accordingly using a callback function.
var data = {
UserName: "#Model.UserName",
accountStatus: "#Model.AccountStatus"
};
var call = $.post(
'#Url.Action("SetAccountStatus", "User")',
data
);
// set the success callback here
call.success(function (m) {
// the [m] variable contains the data returned by the server
// during the resolution of your call
// this will be called when your AJAX call succeeds,
// and you can use this opportunity to update the HTML DOM with new data
});
this is to event click in button and without refresh page
$("#btnBool").click(function(e){
e.preventDefault();
//to do your code, you can use `$.ajax` to request and get response from server
$.ajax({
url: '#Url.Action("SetAccountStatus", "User")',
type:"GET",
dataType: 'json',
data: { UserName: "#(Model.UserName)",accountStatus: "#(Model.AccountStatus)" },
async:'true',
success:function (data) {
alert(data);
//success to parsing json if you data type of your response is json
}
});
}
you can use web service to send request and get response from server , and to request,get response from server you can use $.ajax() in jquery http://api.jquery.com/jQuery.ajax/

Categories