I am trying to receive the JSON data from the WCF service url in javascript.
I used the following javascript code.
$(function(){
$("input:button").click(function() {
$.ajax({
dataType: 'json',
type: "GET",
url: "http://192.168.1.109/EIM/EIS.svc/json/getLatestLocation/Mobile/Mobile/1001",
success: function (data) {
var innerHtml = "";
document.getElementById('test').innerHTML=data;
//'test' is ID of <div>
document.getElementById('testlab').innerHTML=data.getLatestLocationResult.status.code;
//'testlab' is ID of <label>
$("#test").html(innerHtml);
alert("JSON DATA");
alert(data.getLatestLocationResult.status.code);
}
});
});
});
JSON data from url is:
{"getLatestLocationResult":{"status":{"code":"00","description":"Request
OK"},"reason":{"code":"000","description":"Request
OK"},"PersonDetails":{"PersonName":"Santosh Kumar
Sahu","PersonNumber":"1001","Identification":"Pan
Card","IdentificationNumber":"P567","ContactNo":"987654","Gender":"Male"},"location":[{"dateandtime":"7\/17\/2013
10:45:20 AM","latitude":"19.0469536","longitude":"72.9112502","address":"ND","city":"ND","state":"ND","country":"ND"}]}}
Please give me a suggestion to use receive this data.
Thank you.
You should eval the data - otherwise it's just a string.
obj = eval('(' + data + ')');
Now you can use obj as a rightful JS object and access it's members.
Here is the fiddle which evaluates your data string and accesses the resulting object members http://jsfiddle.net/M4BK5/
Related
I have the following JSON data from my API
[{"email":"user#gmail.com","status":"Active"}]
This is the JS/jQuery code I am using to get the data
function formLogin() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var dataString = "email=" + email + "&password=" + password;
jQuery.ajax({
url: "http://localhost/OnlineShop/API/fetch_user_login_api.php",
data: dataString,
type: "POST",
success: function(data) {
$("#login-form").html(data);
console.log('success');
//window.location.href = "store.html?shopper=";
var obj = jQuery.parseJSON(data);
alert(obj.email);
},
error: function() {
console.log('error');
}
});
return true;
}
alert(obj.email) is throwing undefined. How do I retrieve the email and status from the JSON result?
Your "data" variable is already an object or an array, you don't need to call parseJSON.
Then, it seems that your object is an Array of objects
This should work:
alert(data[0].email);
I advice you to check if your array is empty or not before calling this line.
The API returns [{"email":"user#gmail.com","status":"Active"}] as it is of type Array.
first you need to take the first element of the Array by obj = obj[0].
then it is something like {"email":"user#gmail.com","status":"Active"}.
now you can get the email element by simply obj["email"]
if you call your api and get the result like this:
[{"email":"user#gmail.com","status":"Active"}]
it's an array, what you can do to fix the error is:
1) change your api response structure to JSON not array
2) use for to iterate your response
And I advice you next time, you have this kind of error, just console.log the raw data to find what's the structure of it, and you'll have the solution.
var buttonOptions = {
gmap: map,
name: 'Download JSON File',
position: google.maps.ControlPosition.TOP_RIGHT,
action: function () {
$.ajax({
type:"GET",
contentType: "application/json; charset=utf-8",
url: "getJSON.php",
data: "{}",
//dataType: 'json',
cache:false,
success: function(data){
}
});
}
}
I have a button that returns the JSON file below
[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]
My question is, how am I going to loop and display each field in the Success function? I tried using $.each to no avail. Also how can I count each value. I used $('#msg').html(data.length);, however it is counting each character in the JSON file, instead of the actual value. Thanks.
I used $('#msg').html(data.lenght);, but it is counting each character in the JSON file, instead of the actual value.
It's quite evident because you haven't parsed the JSON yet, so data is evaluated as a string here.
Solution:
You need to parse the JSON data before trying to access it. So your code need to be like this:
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
}
how am I going to loop and display each field in the Success function?
And then you can loop over dataafter it's parsed with .each():
success: function(data){
data = JSON.parse(data);
$('#msg').html(data.length);
data.each(function(){
//Your code here
});
}
Edit:
Another thing in your Ajax call why are you using url: "getJSON.php"? In that case the Ajax call will just load the content of the PHP file as a string.
In the URL you should put your .json file or a web service that returns a JSON string.
Demo:
Here's a Demo snippet showing the problem in details and where did 1610 came from in data.length :
var json = '[{"marker_title":"Santa Venera","marker_description":"Hometown","longitude":"","latitude":"","icon":"undefined"},{"marker_title":"Hamrun","marker_description":"Street","longitude":"0.1709747314453125","latitude":"51.44395066709662","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"},{"marker_title":"PlaceA","marker_description":"PlaceA","longitude":"0.292510986328125","latitude":"51.40884344813292","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceB","marker_description":"PlaceB","longitude":"0.232086181640625","latitude":"51.434106241971826","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"PlaceC","marker_description":"PlaceC","longitude":"0.07656097412109375","latitude":"51.43325010472878","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/info-i_maps.png"},{"marker_title":"Home","marker_description":"Town","longitude":"0.1764678955078125","latitude":"51.43753063050015","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/library_maps.png"},{"marker_title":"PLACED","marker_description":"PLACED","longitude":"0.26641845703125","latitude":"51.41783689062198","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"FF","marker_description":"EEE","longitude":"0.2053070068359375","latitude":"51.426828563976954","icon":"https:\/\/maps.google.com\/mapfiles\/kml\/shapes\/parking_lot_maps.png"},{"marker_title":"Qormi","marker_description":"Road","longitude":"14.471054077148438","latitude":"35.875419840918845","icon":"https:\/\/maps.gstatic.com\/mapfiles\/ms2\/micons\/tree.png"}]';
//logging json.length without parsing it
console.log('logging json.length without parsing it');
console.log(json.length);
var data = JSON.parse(json);
//logging data.length after parsing it
console.log('logging data.length after parsing it');
console.log(data.length);
As #chsdk said data is returned being as a string instead of a Javascript object you may want to take a look at $.getJSON() instead of $.ajax() for iterating over JSON objects
$.getJSON( "getJSON.php", function( data ) {
var count = data.length;
$.each( data, function( key, val ) {
//perform operations on data
});
});
http://api.jquery.com/jquery.getjson/
I am using PHP and Ajax to parse some JSON. The PHP is creating the array like this.
$myObj->pid = $_POST["parentid"];
$myObj->comp = $comp;
$myObj->colour = $statuscolour;
$myJSON = json_encode($myObj);
header('Content-Type: application/json');
echo $myJSON;
I use the following jquery code
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var response = jQuery.parseJSON(JSON.stringify(msg));
console.log(response);
pid = response[0].pid;
console.log('id = ' + pid);
});
I can see the output from the first console.log as
Object {pid: "p1", comp: 20, colour: "red"}
However I cannot extract the individual variables, it gives the message
Uncaught TypeError: Cannot read property 'pid'
How can I extract the variable?
You've made this more complicated than it needs to be. msg is already an object, which you then convert to a string and back to an object with stringify and parseJSON. And then you try to use it like an array, when it is an object.
Try this:
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
var pid = msg.pid;
console.log('id = ' + pid);
});
You are returning an object, not an array.
Also it makes no sense to stringify the data object and parse that string back to object again
Try
var pid = msg.pid;
console.log('id = ' + pid);
First of all, it can't imagine why it would be neccessary to first stringify, then parse the JSON response.
Second, you are trying to access response[0] as if it were an array, which it isn't. You can simply use
response.pid;
To access the object key.
As you don't need to stringify then parse the response, you can just access msg directly, so it all comes down to
$.ajax({
type: "POST",
dataType: "json",
url: "msstatup.php",
data: data
}).done(function(msg) {
console.log(msg.pid);
});
I made this webservice that handles my database functions, and this is an AJAX call to one of the methods.
$.ajax({
type: "POST",
url: "Service/dataBaseService.asmx/getRMAData",
data: '{"RMAId": 1 }',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (data) {
console.log(data);
alert(data.RMA_ID);
}
});
this is what is logged:
({d:"[{\"RMA_ID\":1,\"RequestDate\":\"2013-02-28T00:00:00\",\"Company\":1,\"Status\":\"Accepted \",\"Serial\":201764,\"LastChangeDate\":\"2013-02-28T00:00:00\",\"LastChangeBy\":\"Foreign \",\"Price\":null}]"})
However alert(data.RMA_ID) returns undefined aswell as data.d.RMA_ID?
How can I get hold of the values?
The value of data that you've logged is an object with a property named d, that contains a string value. You could probably make adjustments at your server side to make the value of d an object rather than a string, but the way it is currently constructed, you would be able to parse it into an object using JSON.parse.
Once you've done that, the resulting object should be an array, containing one single object. Thus, your access to RMA_ID would be as follows:
var data = JSON.parse(data.d);
alert(data[0].RMA_ID);
Using simple javascript you need to parse JSON response
var resp = eval('(' + data + ')');
or thru jQuery
var resp = jQuery.parseJSON(data);
now you can access the data using '.' and key name
console.log(resp.d[0].RMA_ID)
I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.