I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.
Javascript code:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
var jsonStr = JSON.stringify(data);
alert(jsonStr['password']);
}
});
});
})
The response JSON code looks like this:
{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn#mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
When im running this I only get the error function. Any suggestions or solution is appreciated :)
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
// do something on success
alert(data.password);
});
});
});
Cheers !!!
dont need to JSON.stringify of data simple use
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
alert(data.password);
}
});
});
})
You should pass two argument for error:function(jqXHR, exception) as below.
And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var jsonStr = JSON.stringify(data);
//also try this way to get JSON data:
// var jsonStr =JSON.parse(data);
alert(jsonStr['password']);
},
error: function (jqXHR, exception) {
alert("An error had occurred");
},
});
});
});
Related
I have a problem with my Ajax request to download some data from a database.
There are two codes down below: one that works and one that doesn't, even though they are basically the same. I've also set up later down my code to display the variable (console.log(location)) but it just reads undefined.
I know the php part of it is working because I also do another console.log(data) on success of the ajax call and that returns with the data I entered on my database. What's going on and how do I fix it?
Code that doesn't work:
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
},
error: function(data) {
console.log(data);
}
});
}
Code that does work:
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
dataType: "json",
success: function(data) {
console.log(data);
mapCode = data.mapCode;
used = data.used;
active = data.active;
},
error: function(data) {
console.log(data);
}
});
}
//shorthand deferred way
$.getJSON( "transformerthing.php")
.done(function(data){
console.log(data);
}).fail(function(msg){
console.log(msg)
});
var location;
function downloadCoords() {
$.ajax({
type: 'GET',
url: 'transformerthing.php',
dataType: "json",
success: function(data) {
console.log(data);
location = data.location;
console.log(location);
},
error: function(data) {
console.log(data);
}
});
}
Try it again.
EDIT- I have figured out that the request is working correctly but I don't know what to do with the data once it has been retrieved from the server. I don't know how to access the JSON, how do I do this?
I am trying to do a jQuery AJAX request and parse the JSON which is hopefully received. Here is my code:
search.onsubmit = function() {
$.getJSON("http://www.geocodefarm.com/api/forward/json/d4abb1b19adb13e42eac5a7beac6f4dbeb4b4ba4/" + searchBox.value, function(data) {
var rawJSON = $.parseJSON(data);
alert(rawJSON.COORDINATES.latitude);
});
alert("test");
}
I known that the getJSON function is not working because the test alert appears. Why does it not work?
You can do it like so:
sendAjax: function (url, dataObj) {
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(dataObj),
contentType: "application/json; charset=utf-8",
timeout: 30000,
success: function (result) {
//do shit..
}
,
error: function (result) {
}
});
}
How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});
Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);
I'm used to writing ruby where I get data, then I manipulate it, then I display it.
In javascript land, I'm getting some json, on success: manipulate and display.
I want to separate out my code to look like this
$("#uiElement").click(function(){
data = getData();
upDateUi(data);
})
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
return data;
//I don't want to manipulate the ui in this code;
//upDateUi(data)
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}
You can separate the logic that updates the UI from the logic that retrieves the data from the server using a callback pattern:
$("#uiElement").click(function(){
var upDateUi = function(data) {
/* ... logic ... */
};
getData(upDateUi);
})
function getData(callback){
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
callback(data);
},
error: function(req,error){
console.log(error);
}
})
}
For more information on functions and scopes:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope
For more information on how I defined the upDateUi function:
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope#Recursion
Hard to tell what your question is, but success is any function, so this:
...
success: function(data){
upDateUi(data);
},
...
Can be equivalently written as:
...
success: upDateUi,
...
Other than that, not sure what you mean by "I don't want to manipulate the ui in this code".
Define a callback, and then in the success method invoke the callback:
$("#uiElement").click(function(){
data = getData(upDateUi);
})
function getData(callback) {
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
if (callback !== undefined) {
callback(data);
}
},
error: function(req,error){
console.log(error);
}
})
}
The only way to do that is to use a synchronous fetch, which waits for the response, but its a bad idea, as no other javascript can run (and in some browsers - nothing can run) until the response is received.
If you really, really, really want it though:
$("#uiElement").click(function(){
data = getData();
upDateUi(data);
})
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
async: false,
success: function(data){
fishes = data;
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}
I'm not shure if is this what you want.
successFunction(data){
//you can do everything here
}
errorFunction(req,error){
console.log(error);
}
function getData(){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: successFunction,
error: errorFunction
})
return fishes;
}
This code might be good for your needs:
var myData = $.parseJSON($.ajax({
url: "./somewhere",
type: 'get|post',
async: false,
data: { what: "ever" }
}).responseText);
Then you just proceed with whatever you want to do with the results.
$("#uiElement").click(function(){
var myData = $.parseJSON($.ajax({
url: "./somewhere",
type: 'get|post',
async: false,
data: { what: "ever" }
}).responseText);
upDateUi(myData);
})
You should probably get used to event-based programming. Your code could use callbacks:
$("#uiElement").click(function(){
getData(upDateUi); // make sure upDateUi is defined, it will be passed data
})
function getData(callback){
var fishes;
$.ajax({
url: '/api/fishes/'+q,
dataType: 'json',
success: function(data){
//I don't want to manipulate the ui in this code;
//upDateUi(data)
callback(data);
},
error: function(req,error){
console.log(error);
}
})
return fishes;
}