How to call an asp function when a submit button is clicked? - javascript

I'm new to asp. I have a submit button called "search" in a file called results.asp. I just need to run an asp function called "searchRecords" in the same file as the search button when the button gets clicked. Without redirecting to another page. I tried doing everything, using js, vb script... nothing works the way I want.
the submit button:
<form action="what goes here?">
<input type="submit" value="Search Records" name="search">
</from>
the function:
<% function show()
...stuff here....
%>
Also I found this asp code from another file that works in same kind of situation, but it does not work in my file.
<% if (request("button name")= "button value") then
function to call
end if
%>
Please help me to figure this out... thanks in advance...

With your case, I think you need to use Jquery ajax:
jQuery.ajax({
type:"POST" // Or GET
data:"id=12&name=abc",
dataType:"xml", // Default type - text
url:"/search/searchRecords", // URL of service
success: function (data){
}
});
If you use ASP.NET MVC, you can call a asp function direct. But with asp-classic, you only call a asp function through a service.

$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
if (response.GetClientsResponse.Result != "Invelid Tokenkey !!!") {
}
else {
window.location.assign("Login.html");
}
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});

Related

JS / JSON: Cannot redirect to next page after insert data (AJAX JSON)

Based on my question, I have successfully added input data to the database using ajax. However, it cannot redirect to the next page, "viewDetails.html" after inserting the data. Can anyone know how to fix it?
<script>
$('#userForm').submit(function(e){
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
Add e.preventDefault() after submit function line.
Like
<script>
$('#userForm').submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "https://yes.hus.com/yesss/husss.asmx/TGA_AppAttendanceInsert?",
data:$('#userForm').serialize(),
beforeSend: function(){
console.log("Pending to send");
},
success: function(response){
console.log("Pending to send" + response);
window.location.href = "viewDetails.html";
return true;
},
});
});
</script>
When you use element.submit function, javascript will automatically send request to server side. So usually you don't need an ajax function inside it. Except you need to do something after request.
With e.preventDefault(), submit default function will stop and go to your ajax function.
Also you don't need a question marks on url. Ajax will generate it automatically.

Javascript addClass or removeClass not working in subclass after ajax call

I have an ajax script that inserts a value if it is not in the database and removes the value if it is already there, and returns 1 or 0 accordingly, based on the return value it adds or removes a class in the existing button.
I have tried with find() to take the subclass value but still it is not working.
<form method="post" class="wish" action="process.php">
<input type='hidden' id='value' name='value' value='1'>
<button type="submit" class="card-fox list active" >fan</button>
</form>
This line has active I want it to be added if it is not there and remove if it is there.
below is the ajax:
$(document).ready(function (e) {
$(".wish").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
if (data == 1) {
$(".list", this).addClass("active");
}
if (data == 2) {
$(".list", this).removeClass("active");
}
},
error: function (e) {}
});
}));
});
the problem is that although the ajax script is being executed and everything else is working, the active class is neither adding or removing.
Use:
$(".wish").find('button').addClass("active");
$(".wish").find('button').removeClass("active");
Or:
//when form is submit, make a copy of this
let self = this;
//send ajax
//in success ajax
$(self).find('button').addClass("active");
Greetings!
The this in your ajax success function is not the form.
You can set the context of the ajax call to the for to address this.
$.ajax({
context: this, //<- this this is the form, and tells jQuery to set the this of its callbacks to the form

Appending Div after AJAX post

I'm struggling to understand why the following is occurring. I am calling a very simple webservice as shown below. For some reason, my jquery appends the div, but it vanishes immediately? Apologies for the poorly formatted thread...
Also, using jquery 1.7.1 as provided by VS2013
<WebMethod()>
Public Function GetTime() As String
Dim time As String = ""
time = Now().TimeOfDay.ToString
Return time
End Function
My AJAX below
function CallWebServiceFromJquery() {
$.ajax({
type: "POST",
url: "WebService.asmx/GetTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: setTime,
error: OnError
});
}
Success function
function setTime(data, status) {
//alert(data.d);
$("#time").css("visibility", "visible")
$("#time").append("<h1>" + data.d + "</h1>")
}
Lastly, the onclick
<asp:Button ID="btnCallWebService" runat="server" OnClientClick="CallWebServiceFromJquery()" Text="Call Webservice" />
The button click itself is causing a postback, hence why the appended div seems to disappear. You need to stop the default event behaviour using preventDefault():
<asp:Button OnClientClick="CallWebServiceFromJquery(event)" ...
function CallWebServiceFromJquery(e) {
e.preventDefault();
$.ajax({
// ajax settings...
});
}
Make sure CallWebServiceFromJquery returns false. Based on your description of the div appearing and disappearing, your page is doing a postback.

ajax form submission refreshes page

I'm working on this project and am attempting to make a call to a controller function without performing a page refresh. I tried setting up an ajax function in order to do this but haven't had any luck. I've placed the related script both in the html and in a separate jquery.js but to no avail. It appears as if the form submission just isn't hitting the script at all. Any help would be greatly appreciated!! The form is in a cshtml file, controller in .cs, and script in .js
the form in question:
<form id="tableForm" action="#(Url.Action("AddToOrder", "Order"))" method="post">
#{foreach (var item in (IList<Item>)ViewData["items"]){
<input type="hidden" id="#("item_id_" + item.id)" name="#("item_id_" + item.id)" value="#item.id" />
<tr>
<td>#item.description</td>
<td>#String.Format("{0:C}",item.price)</td>
<td><input type="text" id="#("item_quantity_" + #item.id)" name="#("item_quantity_" + #item.id)" style="width: 50px;" value="0" /></td>
</tr>
}}
<tr>
<td><input class="submit" type="submit" value="Add item(s) to order" /></td>
</tr>
</form>
the script in question:
$('#tableForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
succes: function (data) {
alert(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
To reiterate, the controller and method are working great, but the form submission refreshes the page.
refer the below code, call the preventdetfault after the submission
$('#tableForm').submit(function (e) {
$.ajax({
type: "POST",
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
succes: function (data) {
alert(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
e.preventDefault();
});
Is your AJAX method getting called on page submission. Try adding an alert to confirm that.
You might want to add ClientIdMOde="static" to your form tag, so that if it is with in master page the control id will be static and JS can bind to it.
May be clientidmode will do the trick.
Let me know if it doesn't
Without your full page shown, I can only make an educated guess: that you have included your .js file at the top of the page or in the head element.
That means that the following code does nothing (returns an empty jQuery object):
$('#tableForm')
That is because the code runs as soon as it is loaded/defined and the form element it references has not been loaded yet.
The simply solution is: to either put your JS code at the end of the body element, or wrap it in a DOM-ready event handler. The handler is preferred as you can be moved about the page without failing:
e.g.
$(function(){
// your jQuery code here can now use the DOM safely
});
which is a shortcut for this:
$(document).ready(function(){
// your jQuery code here can now use the DOM safely
});
That means you code will now look like:
$(function(){
$('#tableForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
succes: function (data) {
alert(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
If it still fails, the usual cause in a Javascript error preceding your code (missing jQuery library include etc). You will need to show your entire page to clarify that though.

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

Categories

Resources