this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.
Related
I am wanting to pass a dictionary of type <int,int> to my controller via an Ajax post.
The main reason here is the post may have between 1-3 key value pairs here (none of these values are known at compile time) and in the future it may go up to 5.
Also in the post I have to pass in some other data, such as Id and name, which all works as normal.
How would I construct this dictionay in the javascript then send it via the JQuery post and finally receive it on the controller to process?
Edit 2:
I have decided to just solve this with a post for each value instead of trying to pass a dictionary.
EDIT:
Here is my source for the function so you can see what I am trying:
function BindAddMenuItem() {
$(".AddMenuItem").click(function (e) {
e.preventDefault();
//get header id from link by removing addmenuitem from this.id
var currentId = $(this).attr("id").replace("AddMenuItem", "");
//get itemnumber, itemname, itemdetails from textboxes with same header id
var restaurantId = jQuery.trim($("#RestaurantId").val());
var itemNumber = jQuery.trim($("#ItemNumber" + currentId).val());
var itemName = jQuery.trim($("#ItemName" + currentId).val());
var itemDetails = jQuery.trim($("#ItemDetails" + currentId).val());
var costs = new Object();
//select all textboxes with class "Header" + currentId
$(".Header" + currentId).each(function (i) {
var optionId = $(this).attr("id").replace("Option", "");
costs[optionId] = $(this).val();
});
$.ajax(
{
type: "POST",
url: "/Menu/AddMenuItem",
data: "reastaurantId=" + restaurantId + "&menuHeaderId=" + currentId + "&itemNumber=" + itemNumber + "&itemName=" + itemName + "&itemDetails=" + itemDetails + "&costs=" + costs,
dataType: "html",
success: function (result) {
var domElement = $(result);
$("#MenuContainer").replaceWith(domElement);
var newNum = parseInt(itemNumber) + 1;
$("#ItemNumber" + currentId).val(newNum);
BindAllBehaviours();
}
});
});
}
Something like (javascript)
dict = new Object();
dict['12'] = 5;
dict['13'] = 6;
dict['1000'] = 21;
dict['9'] = 13;
dict['13'] = 48;
$.post('/client.mvc/mypostaction/', { myDictionary: dict });
You can then post the dict object to your controller using a Dictionary<int, int> as property type.
ActionResult MyPostAction(Dictionary<string, int> myDictionary)
edit from author's code second time:
The following works for me, when having a Dictionary<string, int> kvPairs. <int, int> isn't going to work after all.
Make your post like:
var dict = new Object();
dict['13'] = 9;
dict['14'] = 10;
dict['2'] = 5;
$.post('controller.mvc/Test', { 'kvPairs': dict }, function(obj) { $('#output').html(obj.Count); });
JavaScript object / dictionary has to be passed as a list of key-value pairs to ASP.NET MVC controller when Dictionary<TKey, TValue> is expected. Example:
If you have a dictionary like this:
public Dictionary<string, decimal?> SomeMapping { get; set; }
then you have to use something like this in your JavaScript:
var sourceMapping = { a: 1, b: 1.5, c: null };
var SomeMapping = [];
for (var key in sourceMapping) {
if (sourceMapping.hasOwnProperty(key)) {
SomeMapping.push({ Key: key, Value: sourceMapping[key] });
}
}
I've used this approach in asynchronous POST request (sent using jQuery) that had content type set to 'application/json' (this may or may not be important in your case).
Client (JavaScript):
var dict = new Object();
dict.Key1 = "Value1"
dict.Key2 = "Value2"
$.post('/YourController/YourAction/', dict);
NOTE: The "dict" objects gets serialized behind the scenes before being sent to your action.
Server:
public ActionResult YourAction()
{
string postData = string.Empty;
using (StreamReader sr = new StreamReader(Request.InputStream))
{
postData = sr.ReadToEnd();
}
//Load post data into JObject (Newtonsoft.Json)
JObject o = JObject.Parse(postData);
//Extract each key/val
string val1 = (string)o["Key1"];
//Do whatever....
}
None of these worked for me except for mczers, but he doesn't show all the steps, and makes it difficult when you're trying to remember how you set up an ajax request. So I wanted to put everything that actually just works. First, in JavaScript:
var validDict = new Array();
validDict[0] = { key: 1, value: 4 }
validDict[1] = { key: 42, value: 5}
var path = "#Url.Action("ControllerName", "ActionName")";
$.ajax({
url: path,
type: "POST",
data: JSON.stringify(validDict),
contentType: "application/json; charset=utf-8",
async:false,
success: function(status, xhr)
{
alert(status);
},
error: function(xhr, status, error)
{
alert(error);
}});
Then in your controller:
[HttpPost]
public ActionResult ActionName(Dictionary<int, int> validDict)
{
// doStuff();
return Content("Success");
}
A dictionary of the kind IDictionary<string, string> on server side can be posted from javascript like
{"Key1": "Value1", "Key2": "Value2"}
on the Server Side in ASP.NET Web API
[HttpPost]
public IHttpActionResult([FromBody]IDictionary<string, string> requestParam){
}
Above example is for an Http POST with the Json data in the Body
For passing a Dictionary I found the following working answer:
submitting-a-dictionary-to-an-asp-net-mvc-action
#model WebApplication3.Controllers.ExampleViewModel #{ ViewBag.Title = "New";
var first = Guid.NewGuid(); var second = Guid.NewGuid(); }
<h2>New</h2>
#using (Html.BeginForm(new { action = "create", controller = "home" })) {
foreach (var kvp in Model.Values) {
<p>
<input type="text" name="Model.Values[#first].Key" value="#kvp.Key" />
<input type="text" name="Model.Values[#first].Value" value="#kvp.Value" />
<input type="hidden" name="Model.Values.Index" value="#first" />
</p>
}
you have to generate A Guid for the dictionary index, and you have to create 3 inputs, one for the Key, one for the Value and one for the Index of the Dictionary
Also I have submited using Jquery with the following:
$('form#frmFormId').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
//debugger;
$('#cover-spin').show(100);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false
}
);
return false;
});
I'm trying to convert an array of Hazards(class that i created) to JSON,
this is my code:
$.ajax({
async: true,
url: web + "/GetHazards",
method: "POST",
contentType: "application/json",
success: function (data) {
var res = data.d;
var i;
alert(res[0]);
the returned data is like this :
"[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165},{\"Hazard_ID\":3012,\"Hazard_Lat\":32.3426857
My server side code returns the correct values that i need, but the problem is when i alert the res[i] it behave like res is a string and alerts me "["
what i need to get is
{\"Hazard_ID":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423}
i dont know if it mind this is my server-side code by the way:
{
List<Returned_Hazard> rh = new List<Returned_Hazard>();
JavaScriptSerializer json = new JavaScriptSerializer();
.
.
.
while (reader.Read())
{
Returned_Hazard RH = new Returned_Hazard(
int.Parse(reader[0].ToString()),
float.Parse(reader[1].ToString()),
float.Parse(reader[2].ToString())
);
rh.Add(RH);
}
command.Connection.Close();
return json.Serialize(rh);
}
You need to parse the JSON, using JSON.parse:
var data = { d: "[{\"Hazard_ID\":3014,\"Hazard_Lat\":32.2615929,\"Hazard_Long\":35.01423},{\"Hazard_ID\":3013,\"Hazard_Lat\":32.3426857,\"Hazard_Long\":34.9103165}]"
};
var res = JSON.parse(data.d);
console.log(res[0].Hazard_ID); //3014
Hello Fellow Developers,
I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.
The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.
$('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);
hideValue = function (ev) {
var $this = $(this);
$this.data('value', $this.val());
$('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());
var data2Send = '{"SSN": ' + $this.val() + ' }';
$.ajax({
type: "POST",
url: "AuthforHire.aspx/EmployeeisRehire",
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var obj = JSON.stringify(result.d);
if (obj.IsTermed) {
$('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);
var wndWidth = 900;
var wndHeight = 500;
var wnd = window.radopen(null, "RadWindowRehire");
}
},
error: function (xhr) {
alert('Form update failed. '); //error occurred
}
});
Below is a minified version of my webMethod, which works correctly
[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{
TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.
termedEmp.Name = dr["name"];
termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
......
}
So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?
Thank you in advance!
The first line in your success callback is:
var obj = JSON.stringify(result.d);
Which is trying to serialize what ASP.Net will already have serialized for you.
Change this to:
var obj = result.d;
And you will then have access to obj.Name, obj.TermDate and all the other properties by name.
I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...
When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..