Accessing Ajax Response Data - javascript

I have this code that works well:
{"livre":"empty_name"}
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (data) {
switch (data.livre) {
case 'empty_name':
break;
}
});
but when i try this code (i need the id), the case "empty name" didn't works. The option selected will be the default case:
{"id":"","livre":"empty_name"}
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (id, data) {
switch (data.livre) {
case 'empty_name':
break;
}
});
Why? and how can be solved? thanks

If I understand correctly with the object up top being the JSON response, I think you want this...
{"id":"","livre":"empty_name"}
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (data) {
var jsonId = data.id;
}
});
The data parameter of the success callback contains your response (in this case, JSON data). You access your JSON content there.

You just need to understand how the data is being returned. In this case data is the object containing all the fields. Your success callback would continue to look like success: function(data) the code you need to change is in the method block itself.
$.ajax({
url: "sent.php",
type: "post",
dataType: "json",
data: formdata,
success: function (data) {
var id = data.id; //ID lives in data.
switch (data.livre) {
}
});
Since you redefined the function, the switch will fail because in the example posted livre will reside in the id object and not in the data object.

Related

getting entire json data from API with AJAX

With my AJAX call, I want to get the json data entirely.
For example www.abc.com/api/3 gives {"information":.... json data with many levels...}}
I want to store this data in variable.So I try this:
$.ajax({
async: false,
type: 'GET',
dataType: 'json',
url: url,
data: data,
success: function(data) {
x=data;// It's wrong, but I don't know how to put whole json into x
}
})
You can use $.ajax() as a Promise:
$.ajax({
type: 'GET',
url: url,
}).then((data) => {
console.log(data);
});

i am trying to pass parameter to data through ajax

I am trying to pass value through an ajax json array but value of catergory variable is not getting in controller action
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
data: {
'category': category
},
dataType: "json",
cache: false,
contentType: false,
processData: false,
success: function(response) {}
});
You need to use the parameter namespace matching your extension/plugin:
$.ajax({
// ...
data: {
'tx_myext_foo[category]': category,
},
// ...
});
But you'll also need to configure the cHash evaluation since this will lead to a HTTP request like /?tx_myext_foo[category]=X which will fail without a matching cHash.
This can be done with the excludedParameters configuration option.
Please check the Controller action if category (parameter name) passed from the ajax is exactly same in the controller action too
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
cache: false,
async: false,
url: url,
data: JSON.stringify {
category: category
},
dataType: 'json',
success: function(response) {}
});
You need to make ajaxurl with action and controller. and then pass the data in full format.
var ajaxUrl = '<f:uri.action action="youraction" controller="Yourcontroller" />';
var category = $('#category').val();
$.ajax({
type: 'POST',
url: ajaxUrl,
data: '&tx_yourext_yourplugin[category]='+category,
success: function(response) {
},
});
Just make the following changes :
var category = $('#category').val();
var url = $('#ajax_action_search').val();
$.ajax({
type: "POST",
url:url,
data: {'category': category},
dataType: "json",
success: function(response) {}
});

Cant get value from ajax request to be save in variable outside the success

Once again I've been beating my head against the wall, trying to pull this part of returned data from ajax to a variable outside the function.
When I return the value it always comes up undefined when I alert() inside it shows the proper values.
function getItemInfo(itemHashPass) {
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
return data.Response.data.inventoryItem.itemName;
}
});
}
I've also tried
function getItemInfo(itemHashPass) {
var tmp = null;
$.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
success: function(data){
tmp = data.Response.data.inventoryItem.itemName;
}
});
return tmp;
}
Like Jonathan said you should write your business logic in the callback or you can try Deferred syntax. In this case it will looks like
function yourBusinnesLogicFunction() {
...
getItemInfo("password_hash_value").done(
function(data){
alert(data.Response.data.inventoryItem.itemName);
}
)
}
function getItemInfo(itemHashPass) {
var tmp = null;
return $.ajax({
url: 'index.php//Welcome/getItem', //This is the current doc
type: "POST",
data: 'iHash='+itemHashPass,
dataType: "json",
async: false,
})
}

Send data from a javascript ajax function to a jsp

This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});

Use an objects method as the call back to an AJAX call

I have a javascript Object called Company, which may be instantiated multiple times.
I want each Company to handle its own communication with the server, so that its ajax calls will be contained within the class.
So far I have:
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: this.ReceiveData,
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
The Ajax works fine, and the server correctly receives the data and returns the response, but the call back function does not trigger.
My guess would be because it no longer has any frame of reference to what "this" is.
Is there a way that I can keep the functions attached to an individual instance of the class?
There are several different choices for how to solve this issue. The crux of the problem is that you need to get the value of this set properly when your callback is called as it won't be correct by default.
In modern browsers, you can use the broadly useful .bind():
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: this.ReceiveData.bind(this),
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Or, you can instruct jQuery to do the work for you with the context option to $.ajax():
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
context: this,
success: this.ReceiveData,
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Or you can create your own stub function using a saved value of this (this is my least favorite option):
Company = new Object();
Company.SendData = function(){
var self = this;
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: function(result) {return self.ReceiveData(result);},
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Try this:
Company.SendData = function(){
var self = this;
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: function(res) {self.ReceiveData(res);},
error: ErrorFunc
});
}
This SO post might help to understand.
Update
Fixed the example by encapsulating the function.

Categories

Resources