Jquery ajax call is not working.. Please provide me the solution - c#

//When focusout event is working, tested with alert.. but ajax call is not working and my aspx.cs method also not firing.. Please solve this issue.
//This is my aspx page jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elem = document.getElementById('<%=txtProduct.ClientID %>');
$(elem).focusout(function () {
myF($(this).val());
});
function myF(value) {
var fist = value.split(' ( ', 1);
$.ajax({
type: 'POST',
url: 'Invoice.aspx/getProductDetails',
data: "{'strCode':'" + fist + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d.toString());
},
failure: function (response) {
alert('error');
}
});
}
});
</script>
//Server side code
[WebMethod]
public static string getProductDetails(string strCode)
{
List<string> companyInfo = new List<string>();
companyInfo.Add(HttpContext.Current.Cache[Convert.ToString(HttpContext.Current.Session["UserID"]) + "CompanyID"].ToString());
companyInfo.Add(strCode);
List<string> price = Database.MasterDB.getProductInfo(companyInfo);
if (price.Count > 0)
return price[0].ToString();
else
return "000";
}

Since you are using Session thing inside web method, that might be giving null values or blank values. This is because you have not enabled session for webmethod.
Like this - [WebMethod(EnableSession=true)].
Read more

Related

How to get data through asp.net core api call using html and jquery?

I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
Have you tried your api function trough postman or a tool likewise?
Settting breakpoints can be nice to look into your program's data at runtime.
if these values are null in your database it would be nice to see what userInterface.InsertCustomer(Register); does.
Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
1.When you use .serialize(), it generates the data in a query string format which needs to be sent using the default contentType which is application/x-www-form-urlencoded; charset=UTF-8, not as JSON. Either remove the contentType option or specify contentType: application/x-www-form-urlencoded; charset=UTF-8 can work.
2.Also you need move the serialize method into onclick event.
3.Be sure change [FromBody] to [FromForm].
Here is a whole working demo:
View:
#model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}

Ajax call is not working - Collect Information from merchant transaction page

I am new to Ajax. I want to retrieve the transaction details from the merchant website after payment processing. My ajax call script is not working. Please help.
C# Method
public class RetrieveCache
{
[WebMethod]
public string RetrieveTransactionData(string ID)
{
ChannelFactory<ServiceSoap> PayChannelFactory = new ChannelFactory<ServiceSoap>("ServiceSoap12");
ServiceSoap Paychannel = PayChannelFactory.CreateChannel();
XmlNode node = Paychannel.RetrieveCachedData(ID);
return node.InnerXml;
}
}
Ajax call Script in HTML Page to call the above c# method
Html Page URL: http://localhost:55014/SuccessPage.html?id=29473740923
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.search;
debugger;
var token = (url.replace("?", "").split("=")[1]).toString();
debugger;
var dataval = JSON.stringify({ token: token });
$.ajax({
url: "http://localhost:55014/RetrieveCache.cs/RetrieveTransactionData",
type: 'post',
data: JSON.stringify({ token: token }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data){
alert(data);
},
error: function (err) {
alert(err)
}
});
});
</script>

Ajax call to c# function not working

I'm trying to use Ajax to call a C# function but the call is not working.The script shows the hello message but does not show the success/error message.What am i doing wrong
Java script
<script type="text/javascript">
$(document).ready(function () {
$('#btnsave1').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function () {
alert('Successfully Saved');
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
C# Method
protected void apply()
{
MessageBox.Show("hi");
}
Try this:
[WebMethod]//write [WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
data:'{}',
success: function (result) {
alert(result);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
Few things you need to fix here. First: there's no MessageBox in webforms. change the apply() method to return string:
protected string apply()
{
return "hi!";
}
Second: Use '#btnsave1' to '#<%= btnsave1.ClientID %>' to get server generated id for button and also catch the string returned by apply() method. Your script should look like:
<script type="text/javascript">
$(document).ready(function () {
$('#<%= btnsave1.ClientID %>').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function (data) {
alert(data);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
</script>
Third: Make sure you have referenced jquery in the head of your page:
<head runat="server">
<script src="Scripts/jquery-1.8.2.js"></script>

JSON TinyMCE return value "\t"

Should I use another variable for "streszczenie"? or what should I do?
In my opinion in TinyMCE body have html but I get only "\t" Pobably I have got problem with JS
this is new problem - this question is related with this link. I added this for other users
this I write in TinyMCE
this I get from TinyMCE textarea "streszczenie"
As you can see there is text ghhfgh but I can`t get this text
Now I have got problem with execute JSON
<script type="text/javascript">
function Save() {
tinyMCE.triggerSave();
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function() {
},
success: function(data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
I get this but all the time JSON is not execute
When I click button tinyMCE.get('Streszczenie').getContent() is empty I check this and I don`t know why because I have got text into textarea
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var $d = tinyMCE.get('Streszczenie').getContent();
if ($d.length != 0) {
if ($d.val().length != 0) {
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
}
else {
var Streszczenie_controll = 'ewewe';
}
}
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
You are getting the content in wrong way, not by jQuery's val().
To get the tinymce content, just use tinyMCE object reference:
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
// Get the raw contents of the currently active editor
tinyMCE.activeEditor.getContent({format : 'raw'});
// Get content of a specific editor:
tinyMCE.get('content id').getContent()
As mentioned:
http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
Hope it heled. Polish man : )

JQuery Autocomplete loading data from model in aspx page

I am trying to
1) create a JQuery AutoComplete box that is populated from an aspx method, and
2)once I get the results, I wish to populate these results inside a list.
At the moment I am trying to do step one however without my success.
My code is as follows:-
ASPX
<script>
$(function () {
$("#persons").autocomplete({
//source: availableTags
source: function (request, response) {
var term = request.term;
var personArray = new Array();
$.post('JQAutoComplete.aspx/FetchPersonList', { personName: term }, function (persons) {
personArray = persons;
alert('PersonArray' - personArray);
alert('Persons' - persons);
response(personArray);
});
}
});
});
<div class="ui-widget">
<label for="persons">Persons: </label>
<input id="persons" />
</div>
</body>
and my aspx.cs is as follows :-
public JsonResult FetchPersonList(string personName)
{
var persons = ctx.GetDataFromXML(false, 0);
return (persons) as JsonResult;
}
*************UPDATE ASPX.CS*******************
ok so I changed the method to this:-
[WebMethod]
public static List<Person> FetchPersonList()
{
//var persons = this.HouseService.SelectByName(houseName).Select(e => new String(e.Name.ToCharArray())).ToArray();
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>) persons;
}
but I am still not getting through the method!
However the code is not hitting this method at all.
How can I get this list?
Thanks for your help and time
Ok I found the problem.
I changed my JQuery to the following and its calling the method now :-
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#persons").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JQAutoComplete2.aspx/FetchPersons",
data: "{'name':'" + document.getElementById('persons').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
alert(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
and my ASPX.CS looks like this :-
[WebMethod]
public static List<Person> FetchPersons(string name)
{
var persons = ctx.GetDataFromXML(false, 0);
return (List<Person>)persons;
}

Categories