I'm new to Jquery and Ajax calls... This is my call:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "some url",
success: function(response){
console.log(response);
}
})
});
The console log show this response:
{"2014/08/08":[{},{"TEST":0}]}
How can I save the value of TEST to a variable?
Similar to var t = document.getElementById('test').value
using JSON.parse
$(document).ready(function () {
$.ajax({
type: "GET",
url: "some url",
success: function(response){
try{
json = JSON.parse(response);
test = null;
$.each(json,function(i,item){
test = item[1].TEST;
});
alert(test);//this is what you want
}catch(e){}
}
})
});
The response from the server is json, so the best way to handle it is to tell jQuery to expect a json answer and turn it into a regular javascript object. This is done by adding the dataType: 'json' to your $.ajax(...) call :
$.ajax({
type: "GET",
url: "some url",
dataType: "json",
success: function(response){
console.log(response);
}
})
You can alternatively use the shortcut $.getJSON(...) :
$.getJSON("some url", function(response){ console.log(response); });
Now that you have a regular javascript object, you can use what other answers suggest :
success: function(response) {
console.log(response["2014/08/08"][1].TEST);
// or
$.each(response, function(i, itm) {
console.log(itm[1].TEST);
};
}
"want to save the value of TEST to a variable" Try this:
var t = response["2014/08/08"][1].TEST;
Demo
try this,
$.each(response,function(i,value){
alert(value[1].Test);
});
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.
Hi I am trying to make a simple call like this in ajax:
$.ajax({
type: "GET",
url :"${info.contextPath}/secured/contribution/employer/contributionsearch/viewNewContribution?employerCode="+code+"&contbYear="+year+"&contbMonth="+month
+"&orgId="+orgId+"&contbStatus="+status+"&employerDetailId="+employerId,
success: function(data){
alert('123'+data);
$("#newContribution").html(data);
}
});
However, when I see the pop up of my alert I only see '123'. Is my call wrong ?
Use data: {key: value} instead of url concatenation.
Make sure that server's response is correct
Check for the server's response. If possible follow this approach :
$.ajax( {
method : 'GET',
url : '/uri',
data : {key1 : "value1", key2 : "value2"}
}).success(function (data) {
console.log(data);
alert(data);
});
Just try to serialize the response in alert.
$.ajax({
type: "GET",
dataType: "json",
url :"${info.contextPath}/secured/contribution/employer/contributionsearch/viewNewContribution?employerCode="+code+"&contbYear="+year+"&contbMonth="+month +"&orgId="+orgId+"&contbStatus="+status+"&employerDetailId="+employerId,
success: function(data){
var resp = JSON.stringify(data);
alert('123'+resp);
$("#newContribution").html(resp);
}
});
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 have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});
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;
}