On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
On the client side I have
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
users contains
{"ss":"Sandra Schlichting","fn":"Full name"}
but it is not an array. When I use $.each() it takes on character at a time.
Problem
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
which should produce
Initials Full Name
ss Sandra Schlichting
fn Full name
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.
There is also $.parseJSON() method to parse string to json if you want to go that way.
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.
Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/
You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js
include the json2.js in your page, the you can do:
var object = JSON.parse(string);
Then you can use it as an array.
you can use for in statement
var index = 0;
for(user in users){
result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}
Related
I try to get a new list for each country select, in symfony, with jquery.
For this i use ajax, but i have this error :
TypeError: invalid 'in' operand a
My jquery :
$('.country').change(function(){
var val = $(this).val();
$.ajax({
type: "POST",
url: "{{ path('ajax') }}?country_id=" + val,
success: function(data) {
$('.extension').html('');
$.each(data, function(k, v) {
$('.extension').append('<option value="' + v + '">' + k + '</option>');
});
}
});
return false;
});
My path ajax call my function ajax in controller :
public function ajaxAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get extension ID
$numCountry = $request->query->get('country_id');
$result = array();
$extensions = $this->get('extension')->getExtensionByCountry($numCountry, array('name' => 'asc'));
foreach ($extensions as $extension) {
//$result[$extension->getName()] = $extension->getId();
$result['test'] = 1;
}
return new JsonResponse($result);
}
You are trying to iterate over a string, that is causing this error.Try using $.parseJSON(data)
success: function(data) {
$('.extension').html('');
data = $.parseJSON(data);
$.each(data, function(k, v) {
$('.extension').append('<option value="' + v + '">' + k + '</option>');
});
}
Read more $.parseJson
Are you sure your data is an array ? this normaly happen when you use "each" on a non array element.
I would like to suggest you few more things :
use FOS js routing : http://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html . It will be better for you to put you ajax in js files
you shoudln't name you method 'ajax' but instead use a clearer name
So I've been trying to figure out a way to return only a specific key-value pair from a REST API call using JQuery. The initial call I'm going off of is:
jQuery.ajax({
type: "GET",
url: "https://BASEURL/api/project-type/list-all",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function ()
{
$('#projectTypeListLoading').text("Loading...");
},
success: function (data, status, jqXHR)
{
var trHTML = "";
$.each(data, function (i, item)
{
trHTML += '<tr><td>' + item.Name + '</td><td>' + item.Code + '</td><td>'
+ item.Order + '</td><td>' + item.IsActive + '</td><td>' + item.Id + '</td></tr>';
});
$('#projectTypesTable').append(trHTML);
$('#projectTypeListLoading').html("DONE");
},
error: function (jqXHR, status)
{
$('#projectTypeListLoading').html("Error loading list");
}
});
With this I can get a list of JSON Objects from my REST API like so:
[{"Name":"Project Type 2","Code":"2","Order":2,"IsActive":true,"Id":"c497e4e8-16b4-44e2-b6ac-a9a2c392d9d4"},{"Name":"Project Type 3","Code":"3","Order":3,"IsActive":true,"Id":"6da2a240-2327-4260-a6df-f4bec25535c2"}]
I then use these in my Ajax success portion and stick them in a table. Works perfectly. However, what I would like to have happen is to ONLY get say the Name key-value pair part of the JSON Object as the Response from my REST API. Like so:
[{"Name":"Project Type 2"},{"Name":"Project Type 3"]
And then in my Success function use:
success: function (data, status, jqXHR)
{
var trHTML = "";
$.each(data, function (i, item)
{
trHTML += '<tr><td>' + item.Name + '</td></tr>';
});
$('#projectTypesTable').append(trHTML);
$('#projectTypeListLoading').html("DONE");
},
I could achieve this result in two different ways. I could:
Change my REST API call to 'https://BASEURL/api/project-type/name'. And call this and have the API only return the name. I don't want to do this because I have 20 different urls which already return all, I will not be making a separate URL to access each key-value individually for each of these.
Get all like in my initial example then just ignore every key-value pair that isn't 'Name'. This would do what I want but the point is there will be many hundreds of these calls going on. Each of these calls would return the full JSON object then I'd cut that down; that's a lot of unnecessary chatter. I'd rather be able to specify which key-value pair I want to reduce server load.
Any advice on how to achieve this? Thanks.
There's no easy answer to this with REST endpoints. This is the exact problem that GraphQL, Falcor, OData and a number of other libraries were created to assist with.
I would like to ask how could I convert the following $.getJSON() to $.ajax() please.
I have a set of arrays from var googleApi like this:
Array [Object, Object, Object, Object, Object]
// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}
I would like to ask how could I identify if the value of a declared variable (eg. content with the value of user1) is the same as a value within the list of name keys in the array?
Below is my attempt and you might find my full code in $.getJSON() here:
$.getJSON():
var googleApi = 'https://api.com/url_here';
$.getJSON(googleApi, function(json){
console.log(JSON.stringify(json));
var item = json.result.find(function(e){
return e.name == content;
}) || json.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Below is my attempt on $.ajax() but I got an error of "TypeError: data.result is undefined";I have also tried using $(this) to replace data.result but without luck... it would be very nice if someone could identify what have I done wrong please:
var googleApi = "https://sheetsu.com/apis/v1.0/f924526c";
var googleKey = "0123456789";
var googleSecret = "987654321";
var data = [];
$.ajax({
url: googleApi,
headers: {
"Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
},
data: JSON.stringify(data),
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
var item = data.result.find(function(e){
return e.name == content;
}) || data.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Merci beaucoup :))) x
...how could I identify if the value of a declared
variable ... is the same as a value
within the list of name keys in the array?
As per your provided response object you could iterate through it and check the values against your variable content:
var content = "user1";
$.each(response, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
Example Fiddle
As for the second part of your question:
but I got an error of "TypeError: data.result is undefined";
The reason you may be getting your error is because find is expecting a jQuery object, you have received a JSON object back from your endpoint, so using dot notation as above will should work as well:
success: function(data) {
$.each(data, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
}
You can see the answer to this question for a bunch of awesome information on how to access / proccess objects.
Also note your success callback in your code above is not closed, which will create errors.
function getID(name){
$.each(data,function(key,value){ //value = object.value (name)
$.each(value,function(key1,value1){ //value1 = user name (actual names in array)
if(value1 == content){
console.log(value.id);
var name = value.name;
$('#nameText').text(name);
console.log("Name: " + name);
return;
}
});
});
}
getID(data);
return false;
Okay, i want to process another javascript request foreach value returned inside a JSON response from a jQuery Request, Here's the current code i'm using for this request
function waitForEvents(){
$.ajax({
type: "GET",
url: "/functions/ajax.php?func=feed&old_msg_id="+old_msg_id,
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){
var json = jQuery.parseJSON(data);
**//Foreach json repsonse['msg_id'] call another function**
setTimeout('waitForEvents()',"1000");
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("Error:" + textStatus + " (" + errorThrown + ")");
setTimeout('waitForEvents()',"15000");
},
});
};
for each json response variable ['msg_id'] i want to call another javascript function but don't know how to process the array using a foreach in javascript, any idea how ?
As you're already using jQuery, you can use the $.each function:
http://api.jquery.com/jQuery.each/
$.each(json.msg_id, function (index, value) {
// Do something with value here, e.g.
alert('Value ' + index + ' is ' value);
})
use a simple for loop, likely faster than for each
function myfunction(id){
alert("myid:"+id):
}
var i=0;
for (i=0; i< json.length;i++){
var thisId = json[i].msg_id;
myfunction(thisId);
}
simpler:
function myfunction(id){
alert("myid:"+id):
}
var i=0;
for (i=0; i< json.length;i++){
myfunction(json[i].msg_id);
}
since you asked:
function checkArrayElements(element, index, array) {
console.log("a[" + index + "] = " + element);
var myId = element.msg_id;
};
json.forEach(checkArrayElements);
and discussion in case older browsers where not implimented: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach so you can do that
I have this function in jquery which has the result array and how can I get this result array to C# code. Can anyone help me regarding this.
function generateData() {
var result = $('#accordion').sortable('toArray');
}
You could do this asynchronously through a web method call from script, such that you define a web method appropriately, then call and handle the data and potential return value, as desired. For example:
Defining a web method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HandleData(object[] data)
{
//handle data
return string.Empty;
}
Defining a reusable jQuery script method to handle web method calls:
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
And, of course, the call itself:
ExecutePageMethod("Default.aspx", "HandleData",
["data", result], successCallback, failureCallback);
Naturally we now need to make sure our callback methods exist:
function successCallback(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
function failureCallback(result) {
}
Use a hiddenfield to store the result..
<asp:HiddenField id="hfResult" runat="server" />
JQuery
$('hfResult').val(result);
C#
String result = hfResult.Value;
Note that a hiddenField only holds a string, so you might need to use some kind of seperator to seperate your array objects..