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>
Related
I'm doing a POST request via JQuery's Ajax, with the type of data defined as json, containing the values to be posted to server, something like Username: "Ali".
What I need to do in a Handler, is to read the values, deserialize them to an object named User.
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
User user = JsonConvert.DeserializeObject<User>(data);
While debugging, the value of data is the following:
Username=Ali&Age=2....
Now I'm sure this isn't JSON, so the next line would certainly produce an error:
"Unexpected character encountered while parsing value: U. Path '', line 0, position 0."
What is the proper way to read JSON data from POST request?
Client Side
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: {
Username: 'Ali',
Age: 2,
Email: 'test'
},
success: function (data) {
},
error: function (error) {
}
});
Convert your object to json string:
$.ajax({
type: 'POST',
url: "http://localhost:38504/DeviceService.ashx",
dataType: 'json',
data: JSON.stringify({
Username: 'Ali',
Age: 2,
Email: 'test'
}),
success: function (data) {
},
error: function (error) {
}
});
I am not sure why your datastring is encoded like an url (as it seems).
But this might solve the problem (altough i am not sure)
String data = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
String fixedData = HttpServerUtility.UrlDecode(data);
User user = JsonConvert.DeserializeObject<User>(fixedData);
Use This In c# file... Will give you result you require...
string username=Request.Form["Username"].ToString();
Similarly For others...
I hope this will help you
Another Answer Or you can send data like this
$.ajax({
url: '../Ajax/Ajax_MasterManagement_Girdle.aspx',
data: "Age=5&id=2"
type: 'POST',
success: function (data) {
}
});
ANd get the answer like this in c#
string Age=Request.Form["Age"].ToString();
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
In PHP, I can call a page like this
var data = {
type: 'simple_data'
};
jQuery.ajax({
url: 'http://www.example.com/haha.php', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
And in the PHP server side page, we catch it like
$type=$_POST['type'];
Pretty simple right! It gives back the XML info and GOAL.
Now I want to do it for ASP.NET pages in same way as PHP. I want to call the ASP.NET page like
var data = {
type: 'simple_data'
};
jQuery.ajax({
url: 'http://www.example.com/haha.aspx', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
So how can I catch the data and extract values in ASP.NET. That means I want the functionality similar to this '$_POST['type']' in ASP.NET. I tried to search but nothing found yet or may be didn't find in the right direction. Can anyone please tell me how can I extract this data from this ajax call with XML??
You can use Request.Form["type"]
It is very easy. You need to pass the method name in your URL parameter like so:
jQuery.ajax({
url: 'http://www.example.com/haha.aspx/MethodName', //load data
type: "POST",
dataType: "xml",
data: data,
async: false,
success: loading_complete,
error: function (request, status, error) {
alert(error);
}
});
ASP.Net will know how to handle the web request and parse the data. You can write something on the .aspx page as simple as:
[WebMethod]
public static string MethodName(string type)
{
// do work with type
}
I want to insert data from JavaScript to database using ajax and webservice,
I have some controls which by jQuery I get their values and make an array of their values.
When I send the array it causes this error:
Cannot convert object of type 'System.String' to type'System.Collections.Generic.List1[System.String]'
var variables = Array();
var i=0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: "{ 'a':'" +variables + "'}",
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
This is the C# Code
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables})
The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here
Also, you had an extra } in the success function.
So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so:
var someArr = ['el1', 'el2'];
JSON.stringify({
'param1': 1,
'param2': 'two'
'param3': someArr
// etc
});
JavaScript:
var variables = Array();
var i = 0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: JSON.stringify({'a': variables}),
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
});
});
C#
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
data: Data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So, try to add a new parameter to your ajax call:
$.ajax({
type: 'post',
data: { 'a': variables }, // Notice some changes here
dataType: 'json',
traditional: true, // Your new parameter
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
Try this way. Maybe you'll need to change the Web service method to expect an array instead of a List, but I'm not sure.
Try this
data: JSON.stringify({ 'a': variables }),
I am getting a JSON object in my javascript function in aspx page. I need to fetch this data from my code behind file. How can I do it?
My javascript function is :
function codeAddress()
{
var address = document.getElementById("address").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location });
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
var requestParameter = '{' +
'output:"' + results + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
data: requestParameter,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() { alert("error"); }
});
});
}
Default.aspx.cs
[WebMethod]
public static string GetData( Object output)
{
return output.ToString();
}
I am getting the output as an array of objects instead of the actual result - [object Object],[object Object],[object Object] .Please provide me a solution to get the actual result. The JSON I am working on is given below
http://maps.googleapis.com/maps/api/geocode/json?address=M%20G%20Road&sensor=false
Create a WebMethod on your aspx Page that get the array on the page as:
[WebMethod]
public static GetData( type[] arr) // type could be "string myarr" or int type arrary - check this
{}
and make json request.
$.ajax({
type: 'POST',
url: 'Default.aspx/GetData',
data: "{'backerEntries':" + backerEntries.toString() + "}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response) {}
});
or you can use .post().
Check the url: in ajax request GetData WebMethod must be declared on the Default.aspx on that page where you are making ajax request.
Check this question to know that how to format array for sending to the web method.
Why doesn't jquery turn my array into a json string before sending to asp.net web method?
Check these links for reference:
Handling JSON Arrays returned from ASP.NET Web Services with jQuery - It is Best to take idea
How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?