I'm fairly new to the programming world of Jquery.
I am trying to get data from a web service to be viewed on a notification via Pnotify.
However, on each page load the script does not view the notification bar. I really don't understand what I'm doing wrong. Hope you can help.
NOTE: the web service does retrieve the data correctly in JSON format.
UPDATED: I am able to do a msg.d but it retrieves the JSON but does not parse the information how I would like it to.
<script type="text/javascript">
$(function () {
$.ajax({ //DATA REQUEST
type: 'POST',
url: 'WebServices.asmx/getNote',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (msg) {
$.pnotify({ //CALL PNotify
title: msg.NoteTitle,
text: msg.NoteText
});
}
});
});
</script>
I reviewed your code and if you do the following you should be able to get the data you need.
You need to be aware that object that always need to be parsed before passing the array to a view.
In your case you didn't do that.
success: function (msg) {
var Obj= eval(msg["d"]); or // $.parseJSON(msg["d"]) Method to evaluate Json
$.pnotify({ //CALL PNotify
title: Obj["0"].NotificationText, // The pared arrays
text: Obj["0"].NotificationDescription
Related
I have a server side PHP script that looks like this
class MyObject {
function GetResult($input){
//some code
return $result;
}
}
I want to instantiate this object and call the GetResult function from client side c# application and get the get the result. How can i do so?
You can use Ajax call to hit on that PHP page and get the results from that PHP page.
Just use JQuery Ajax function like this and make object initialization in PHP page only.
$.ajax({
type: "POST",
url: "example.php",
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
}
});
Using ajax POST a url http://test/jy/post.php will get some value below
People,1220,temperature,26C,CO2 concentration,30ppm,3.jpg
Want to put each of them separately into my input text.
Trying to alert data, but it show [object],don't know how to do.
Here is my js:
window.onload = load();
function load() {
$.ajax({
url: 'http://test/jy/post.php',
type: 'POST',
success: function (data) {
},
error: function (data) {
alert(data);
console.log(data);
}
});
}
Hope someone can tell me how to do it or hint me , thanks!
I am assuming that the data in the POST response is JSON.
As mentioned by #Kaushik you can use JSON.stringify(data) to convert the JSON data to a string.
First of all, I would recommend that you take a look at the content at the following link which explains JSON objects and how to work with them. JSON Objects - W3 Schools
For my examples, I have used https://jsonplaceholder.typicode.com/todos to return example JSON data.
If you wish to only access certain properties of the JSON object then you could accomplish this using the following code. Please bear in mind that the following code snippet assumes that the JSON object consists of a single record.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log('User ID: ' + data.userId);
console.log('Title: ' + data.title);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If the JSON data consists of an array of JSON objects then you could approach this with the following code.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos',
dataType: 'json',
success: (data) => {
data.forEach((record) => {
console.log('User ID: ' + record.userId);
console.log('Title: ' + record.title);
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
If you simply just want to display all JSON data as a string then the following code would accomplish this.
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
dataType: 'json',
success: (data) => {
console.log(JSON.stringify(data));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I'm attempting to centralize one of the features in our application. Throughout the site we have a numerous areas where a user can export a table (Syncfusion Grid) as excel. One issue we have is that every time a user filters/sorts to maintain the new table data layout, in the event the user does want to export, we have to make a round trip to the server, poke the DB and run an accompanying script. The alternative to this is we send out the filtered columns each time the user filters or on the export request.
I'm currently trying to switch all these round trips in the latter most option of only sending the data when the request is made to alleviate some of the back and forth. What I'd like to do is be able to send every grid to a single Controller which from the data can figure out what columns to show. Every case I can find so far if a Controller accepting a List<MODELNAME> but if I follow this case I'm not sure if it will work. I imagine I could create a generic export model which will accept the properties. The caveat to this is that these tables are driven by the DB to limit the effort required to modify them if a requirements change. Requirements are set by the reporting agencies our clients report to, neither us nor our clients so we never really know what will change. Changing the tables returned in the stored procedure automatically updates the table on the front. This would mean a change to the DB would need a subsequent update to the model if the property didn't previously exist.
Enough background, I'm trying to sent a generic array to the MVC controller, during the POC I'm using an already existing feature and trying to modify it.
public void ExportAlertListToExcel(string name, List<object> grid, string ignore = "")
The data is sent to the server using the ajax below using jQuery
$.ajax({
url: _url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'name': "Filler", 'grid': dataexport }),
success: function (data) {
// Do something neat
},
complete: function () { },
error: function (e) {
console.log(e);
}
});
The data will look something like
[
{name: 'One', age: '10'},
{name: 'Two', age: '12'},
{name: 'Three', age: '14'},
{name: 'Four', age: '16'},
]
But when it hits the controller it the values will come back as just {object}, regardless of using List, Array, or IEnumerable. I've tried not stringifying the data being sent and stringifying the array of objects inside the array. In cases where I get the data up its a string which I just cannot convert to an object where I can access the data values per item sent. I feel this should be something trivial but I cannot seem to be able to wrap my head around how to go about it. I've tried serializing, deserialzing, passing strings to try an access the data.
you have two primitive type parameter and one composite you may use custom route for your action like :
controller/action/{name}/{ignore}
and then reorder your parameter :
public void ExportAlertListToExcel(string name , string ignore = "",object grid)
$.ajax({
url: 'contrller/action?name=filler&ignore=c',
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: dataexport,
success: function (data) {
// Do something neat
},
complete: function () { },
error: function (e) {
console.log(e);
}
});
after retrieving the object in your code cast it to list of object and work on it.
JSON array data type is string. Did you try this ?
public void ExportAlertListToExcel(string grid)
$.ajax({
url: 'contrller/action?name=filler&ignore=c',
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: dataexport,
success: function (data) {
// Do something neat
},
complete: function () { },
error: function (e) {
console.log(e);
}
});
Try this, I have it working and binding as my custom object array in my controller
$('#costRowAdd').click(function () {
var shipmentCost = {
CarrierName: $("#AgentCarrierID").val(),
CostName: $("#ShipmentCostLineItems option:selected").html(),
Quantity: $("#ShipmentCostqty").val().replace(',', ''),
Rate: $("#ShipmentCostrate").val().replace('$', '').replace(',', ''),
EstimatedCost: $("#ShipmentCostcharge").val().replace('$', '').replace(',', '')
}
var shipmentCosts = [];
shipmentCosts.push(shipmentCost);
$.ajax({
url: 'AddShipmentCosts',
type: 'POST',
dataType: 'json',
data: { ShipmentCosts: shipmentCosts, ShipmentNumber: $('#ShipmentNumber').val() },
success: function (data) {
LoadShipmentCosts($("#ShipmentNumber").val());
$("#ShipmentCostqty").val('');
$("#ShipmentCostrate").val('');
$("#ShipmentCostcharge").val('');
}
});
return false;
});
So I have seen many examples such as these :
https://stackoverflow.com/a/8094230/2525507
public class WebService : System.Web.Services.WebService {
[WebMethod]
public List<string> getList() {
return new List<string> {"I", "Like", "Stack", "Overflow"};
}
}
Where you just it seems that through the success function you can view the returned data from the c# method in the form of an alert. But what if I want to access this "input+1" data outside of the function call, how would I proceed to do that? Also I am not sure how to call a method that has no parameters?
<body>
<select id="wordSelect">
// Drop Down Menu to be populated
</select>
<script>
$(function () {
$.ajax({
url: 'WebService.asmx/getList',
data: '{**NO PARAMETERS?!**}', // should I also call JSON.stringify?
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (data, status) {
alert(data);
alert(typeof data);
}
});
});
$.each(data.i, function(index, item) { // will this access "I", "Like", ... etc?
$(#wordSelect).append(
$("<option></option>")
.text(item)
);
};
</script>
</body>
In the end, I would like to populate a dropdown list using returned JSON data from a c# method that has been called through ajax, but I'm not sure how I can play with that retrieved JSON data that seems to be stuck in the function call?
Sorry, I am new to Jquery/AJAX/etc... But Thank you so much!
If your method takes no arguments, just don't specify the data property on the ajax call
<script>
$(function () {
$.ajax({
url: 'WebService.asmx/getList',
type: 'POST',
dataType: 'json', //make sure your service is actually returning json here
contentType: 'application/json',
success: function (data, status) {
//here data is whatever your WebService.asmx/getList returned
//populate your dropdown here with your $.each w/e
}
});
});
</script>
Also I could be wrong, but the WebService method you showed, doesn't look like it will return json. I think you will have to serialize, or set the content type or something similar. (Been along time since I've used the asmx type services)
See my answer to this post. I reference a web site called Encosia, written by Dave Ward. He has an excellent series on using Ajax with ASP.net / MVC. That is a great place to start, with numerous examples.
I am using JQuery to make a AJAX to a local service. My local service is a HttpHandler (e.g., Request.ashx). Within Request.ashx, it's responsiblity is to make a call to an external website (e.g., CallExternalWebsite()). CallExternalWebsite() uses .NET's System.Net.WebRequest() to initiate a request. When the external website is accessed, neither the success or error events are fired. (NOTE: I have also tried this a WCF service hosted in IIS. I am seeing the same results)
Here are two scenarios:
This scenario works:
In ProcessRequest(), comment out callExternalWebsite().
For object o, intialize with data to simulate results.
Click on myButton
The success event fires on the client.
In Fiddler, I can see the header info. I see Json result, etc.
This scenario does not work:
In ProcessRequest(), enable the call for callExternalWebsite().
For object o, callExternalWebsite() will return an appropriate object.
Click on myButton
The success event does not fires on the client.
In Fiddler, I can see the header info. I see Json result, etc.
I know the callExternalWebsite() is working because I have it sending results to my phone.
To sum it up, the external http call within the HttpHandler is effecting the Ajax success event.
Here is a snippet from AJAX call:
(I was trying different interations)
$(document).ready(function () {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
In the HttpHandler Request.ashx,
public Void ProcessRequest(httpContent context)
{
// Do some stuff....
// Make call to external web site
object o = callExternalWebsite (Uri, Data, "POST");
// Return results from callOtherWebsite
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(o);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
Any thoughts?
Thanks.
Steve
What happens if you do this, msg vs msg.d:
$(document).ready(function () {
$("#myButton").click(function (event) {
$.ajax({
cache: false,
type: "POST",
url: "http://localhost/Service/Request.ashx",
data: '{"id" : "053252f3"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 20000,
success: function (msg) {
AjaxSucceeded(msg.d);
},
error: AjaxFailed
});
});
});