Appending Div after AJAX post - javascript

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.

Related

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

HTML onchange not getting fired from Ajax insert

I am new to Jquery Ajax.
I have a jquery ajax function, which receives a value from a server.
function servertransfer_reg(datapack1,datapack2,datapack3,datapack4) {
alert('Start of Ajax Call');
//Ajax , Jquery Call to Server for sending free time data
$.ajax({
type: "POST",
dataType: 'json',
url: "xyz.php",
data: {M_N : datapack1,
Em : datapack2,
TandC: datapack3,
News: datapack4
},
success: function(data) {
alert(data.appid);
$("#server_answer_reg").html('<p>Your App ID Successfully created<p/>' + data.appid);
//document.getElementById("partyID").innerHTML = data.appid;
$("#partyID").html(data.appid);
}
});
}
Here, I am getting data.appid from server.
I want to insert it into an html element #partyID, and after insert I am expecting onchange event to get fired which will do some work for me.
Below is the html.
<input onchange="saveIDs()" type="text" id="partyID" class="none_visible" value=""></input>
Here, my saveIDs() function is not getting called.
I am receiving the intended data from my Ajax call.
Please let me know if you need more information.
The onchange will fire when you leave the focus from it (if you performed any changes). After the successful execution why don't you call the saveIDs() function in the next line? What I mean is
success: function(data) {
alert(data.appid);
$("#server_answer_reg").html('<p>Your App ID Successfully created<p/>' + data.appid);
//document.getElementById("partyID").innerHTML = data.appid;
$("#partyID").html(data.appid);
saveIDs();
}
You must trigger the onchange event.
See:
http://api.jquery.com/trigger/

Pass javascript function from .Net code behind shared function or web method to page

I need to send a script to the page from WebMethod used by Ajax that fires when click HTML link. I couldn't use the script manager with "Me" or "Page" control and can't reference any controls.
I just need to return that session is nothing , Any Ideas?
The button clicked to send Ajax is HTML link and all I need to check if session expired (which I can check it on load) so if it's expired want to alert user since I already don't complete the process after checking it in code behind
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
''''' my code
''''''''''''''''''''''
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Return "Success"
Else
Return "noSession"
End If
Catch ex As Exception
Return "failure"
End Try
Else
ScriptManager.RegisterStartupScript(Me, GetType(String), "Checkeng", [String].Format("LevelsMsg();"), True)
End If
End Function
JQuery Ajax
It's more complecated but I thinkk this is the main part:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
},
error: function() {
alert("There is a problem in saving data");
}
});
});
Your WebMethodis a Shared function which is equivalent to a Static function in C#. This means you will not be able to access any variables other than those declared inside of this Shared function. However, the nature of WebMethods allow a return to "its" caller via "Success" or "error" which can be "intercepted". Thus, no need to use ScriptManager.RegisterStartupScript since your POST will return to AJAX realm anyway, which means you can call any JavaScript function there.
You could Change your code this way:
VB.NET Code-Behind:
<WebMethod()> _
Public Shared Function Send(ByVal data As String) As String
If Not System.Web.HttpContext.Current.Session("MemberID") Is Nothing Then
Try
' YOUR CODE
Return "Success"
Catch ex As Exception
Return "Failure"
End Try
Else
Return "NoSession";
End If
End Function
JavaScript:
$(document).on("click", "#Add", function() {
var _fulldata = $('#basket').html();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Order.aspx/SendOrder',
data: "{'fulldata':'" + _fulldata + "'}",
async: false,
success: function(response) {
/* since we put "NoSession", then we should check for it here */
if(response.d == "NoSession") {
/* This is where you "replace" the use of RegisterStartupScript
by safely calling any JS function here */
LevelsMsg();
}
},
error: function() {
alert("There is a problem in saving data");
}
});
});

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

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

ASP.Net call codebehind on $.ajax success

I have a page (default.aspx) with codebehind. The a$.ajax url is getting a response from one place, and on its success I want to call the codebehind function.
(In case I made a mistake while obfuscating the code, the $.ajax works perfectly and I get the desired response).
How is this possible?
Code I'm using:
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
$.ajax({
type: "POST",
url: URL,
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var resultCount = response.d
alert("*** RESULT ****" + resultFields);;
var string = StringReturn(); // the codebehind
alert(string);
},
error: function (e) {
alert("Unavailable");
}
});
Codebehind:
[WebMethod]
protected static string StringReturn()
{
return "StringReturn() success";
}
However, I'm getting error messages saying that StringReturn isn't a valid function.
Any help would be appreciated?
I've added the following lines of code to the page as advised:
<asp:ScriptManager ID="ScriptMgr" runat="server" EnablePageMethods="true"> </asp:ScriptManager>
I've also changed the code to call a javascript function on the Success event, the function being:
function HelloWorlds() {
alert("HelloWorld() method");
message = PageMethods.StringReturn();
message.toString();
alert(message);
}
however that doesn't appear to work. What am I missing?
You need to have a scripmanager on your page and then you can call it like this PageMethods.StringReturn()

Categories

Resources