jquery and ajax request - javascript

I have js function which sends ajax request to the controller and succ. return result and append that result into desired div inside partial page. Now I want to implement pagination and I'm using $("#dataList").on("click", ".pagedList a".getPage); to listen when user click on pagination links to determine which page number is clicked
var getPage = function () {
var $a = $(this);
GetTabData(a);
return false;
}
and finally I'm sending pagenumber to the next function which sends pagenumber together with activeTab variable to the controller
function GetTabData(xdata, pageNumber) {
$.ajax({
url: ('/Home/GetTabData'),
type: 'POST',
contentType: 'application/json',
dataType: 'html',
data: JSON.stringify({ activeTab: xdata, page: pageNumber }),
success: function (result) {
$("[id^='tab-'] div").remove();
var currentTab = $("#tab-" + xdata).html(result);
},
error: function () { alert("error"); }
});
}
Something is definit. wrong here cause on controller side I'm using
Request.IsAjaxRequest()
to allow only ajax request to paginate data and I'm getting Not ajax request. Once more, If I remove pagination option completly and send just activeTab everything works.
Any thoughts?

Your GetTabData function takes 2 arguments: xdata and pageNumber but when calling it you are passing only one:
var $a = $(this);
GetTabData(a);
So you probably are getting a javascript error and the return false statement is never reached.

Related

jQuery html() is not rendering the content in a div more than once

I am having a div to show the error-popup-message.
<div id="popup-msg"></div>
And, I am making an AJAX POST call to submit login-form and if the server returns success then I am redirecting to other page, otherwise I am showing the error-popup-message. Currently, the html() is rendering the content only once when I am getting error-message from server. But when I again test it (Without reloading the page), the html() is not rendering the content, even though I am getting the error-message from server.
var getErrorPopUpHTML = function (response) {
var html_content = "";
// It returns the html string after processing the response object.
return html_content;
};
var submitSignInForm = async function () {
$("#sign-in-btnn").off("click");
$("form").submit(function (evt) {
var SIGNIN_ROUTE = getSignInEndpoint(); // This fetch the login-endpoint
evt.preventDefault();
var payload = {
email: $("#sign-in-email").val(),
password: $("#sign-in-password").val(),
};
$.ajax({
url: SERVER + SIGNIN_ROUTE, // Endpoint to make the POST call
method: "POST",
data: payload,
async: false,
dataType: "json",
success: function (response) {
resetSignInFormProperties();
if (response.statusCode === 200) {
window.location = response.values[0].link; // Redirecting to other page upon getting success from server
}
},
error: function (response) {
resetSignInFormProperties();
response = $.parseJSON(response.responseText);
var html_file = getErrorPopUpHTML(response);
$("#popup-msg").html(html_file).fadeOut(8000); // Rendering html content on the div: popup-msg
},
});
return false;
});
};
$(document).ready(function () {
$("#sign-in-btnn").on("click", submitSignInForm);
}
Could anyone please point the mistake here?
Thank you!
You fade out the div after showing the error message but never fade it in again. So only the first message is shown.
Fade div in before showing message
$("#popup-msg").fadeIn(0).html(html_file).fadeOut(8000)

Not able to reload the div while using jQuery $.ajax()

I am trying to reload a div with id #todos after the data is saved in the database.
I tried using .load() in $.ajax()
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
},
});
});
The problem with this, that it is not reloading the page but it is updating the data in database correctly.
I also tried this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
In this, it is reloading the page as well as updating the data in the database but the problem is that it only reload and update the data at the first request, and after that I need to reload the whole page to update next data.
I tried to check if I am getting any data or not
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
console.log(data);
},
});
});
It returned nothing, but my data in the mongoDB compass is changing.
I already read this articles so, please don't mark this question as duplicate.
Refresh/reload the content in Div using jquery/ajax
Refresh Part of Page (div)
refresh div with jquery
reload div after ajax request
I suggest you checking requests between your page and the server in the Network tab of browser's Development Console (F12).
Make sure you see PUT request going out to the server to update todo
Make sure that response you receive looks like { success: true } otherwise the following piece of code won't be triggered
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
Make sure you see GET request going out to the server to pull '#todos' asynchronously.
If you don't see request #3 try the following:
replace location.href with window.location.href
try reloading it manually via console (for Chrome, F12 -> Console tab -> paste $('#todos').load(location.href + ' #todos') and hit Enter). That way you are going to skip first ajax request and just will check whether '#todo' section is loadable/reloadable.
I think it’s a cache problem. Try it like this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: '/todo/${value}?t=202103010001',
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
t=202103010001 Set to a random number

How to property update bootstrap autocomplete source after Ajax call

I am currently implementing the autocomplete bootstrap control from here. I only want to populate the source when characters are more than 2. I'm wondering how do I populate my type ahead source after a successful ajax call.
https://github.com/bassjobsen/Bootstrap-3-Typeahead.
var $input = $(".typeahead");
$input.keyup(function () {
var count = $input[0].value.length;
if (count >= 3) {
$.ajax({
type: "GET",
url: '/Home/GetProducts',
data: {
characters: $input[0].value
},
success: function (response) {
$input.typeahead({
source: response,
autoSelect: true
});
}
});
}
});
When I put a breakpoint at response, this is the result
So my ajax query works, but the type ahead doesn't populate with the results and aren't searchable.

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

Redirect to another page after Ajax call?

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?
Here is the javascript/ajax code that gets called from a button being clicked.
#section scripts{
<script>
// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
},
});
});
</script>
}
For my code behind code that I am calling from the ajax call, that's below here:
public ActionResult OnPostCopyData (string accountid)
{
// Do my other stuff here
return RedirectToPage("Account_Information", new { id = account.Account_ID });
}
Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.
I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:
This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine
[HttpPost]
public ActionResult SubmitSomething()
{
return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}
And then this would be your Ajax request, I updated the success portion
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.redirectUrl !== undefined) {
window.location.replace(result.redirectUrl);
} else {
// No redirect found, do something else
}
},
});
});
This isn't tested, so I can only hope that it works for you right now
Edit: Updated the Url.Action to use OP's view names and parameters
Redirect to page returns a 301 response, which will be in the format:
HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp
To redirect after the ajax call you can redirect to the requested url by:
success: function (result) {
window.location = result.getResponseHeader('Location');
}

Categories

Resources