This is what I want to achieve:
I want to create an interactive map using raphael.js.
Using Php, I get datas from MySql DB and converted into a JSON file.
So far so good.
Inside my raphael js file, I must now:
get those datas
use them in order to modify my raphael file.
I am currently stuck at this first step.
Here's my simplified JSON file (let's call it countries.json) :
[
{
"id": "1",
"type": "Country",
"title": "France",
"published": "1",
"description": "Republic"
},
{
"id": "2",
"type": "Country",
"title": "Belgium",
"published": "0",
"description": "Monarchy"
}
]
Here comes the simplified raphael.js
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': '', 'title': '', 'description':''});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': '', 'title': '', 'description':''});
countries.push(france,belgium);
At the end of the raphael js, I make an Ajax request (using jquery) to get my JSON datas :
$.ajax({
type : 'GET',
url : 'system/modules/countries.json',
data: {get_param: 'value'},
dataType : 'json',
success : function(data, statut){
console.log(statut);
},
error : function(data, statut,erreur){
console.log(statut);
},
complete: function (data) {
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
}
});
Here come the troubles:
I get a 'success' status trough the success function.
BUT I got an error while completing the script :
Uncaught SyntaxError: Unexpected token o
What did I miss? Can't figure out what is different from http://jsfiddle.net/fyxZt/4/ (see how to parse json data with jquery / javascript?)
That was just for part 1 :-)
Assuming someone could help me to fix that, I still then have no idea how to write js loop that will set the raphael vars attributes as it:
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': 'Country', 'title': 'France', 'description':'Country'});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': 'Country', 'title': 'Belgium', 'description':'Monarchy'});
communes.push(france,belgium);
Thanks an advance for your help and please excuse my unperfect english!
Vinny
There is no data argument passed to the complete callback,
according to jQuery API:
complete
Type: Function( jqXHR jqXHR, String textStatus )
(...)The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
So you only need to use the success callback :
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
var json = data;
$(json)
.each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Concerning your second question, you cannot interact directly with variable name (accessing dynamic variable) in js, so you'll need to create an object where values are indexed by one of your json's values. However, the cleanest way to handle this would probably be to add your paths to the json...
var rsr = Raphael('map', '548', '852');
var countries = [];
//here I used the "id" property from the json
var paths={
"1":rsr.path("M ... z"),
"2":rsr.path("M ... z")
};
countries.push(france,belgium);
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
datas.forEach(function (country) {
paths[country.id].data(country);
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Related
I have some javascript:
datasetID is set from the url value.
I get the json data.
const datasetID = urlParams.get('datasetID')
var data;
$.getJSON("json/data.json", function(json){
data = json;
});
Next I want to filter the json data based on the datasetID, then retrieve the value assigned to another attribute vernacularName and assign it to a const.
const record = data.filter(d => d.datasetID === datasetID);
const vernacularName =
How far away am I? Suggestions welcome.
sample code
[
{
"datasetID":"A1"
"language":"en",
"accessRights":"CC BY 4.0",
"vernacularName":"goat"
}
]
Filter in front-end is not a good option (let say your data.json is large) so if you could filter it in back-end before retrieving. For example, I send an ajax request with parameter ID: datasetID :
const datasetID = urlParams.get('datasetID')
var data;
$.ajax({
type: "POST",
url: "/getjson",
dataType: "json",
success: function (json) {
record = json
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
data: {
ID: datasetID
},
cache: false
})
If you can't tweak in back-end and datasetID is unique then this should be enough:
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!
I'm using jQuery bootgrid to display data in table. I get data using Ajax and I return the values in JSON format. On the JSON string it comes a variable I want to read to display in other section out of the table.
Ajax function is the following:
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response_pedidos.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
},
error: function (request, error) {
console.log(arguments);
}
}); }
I'm watching response from PHP page and it comes with the following format:
{"current":1,
"rowCount":20,
"total":7,
"cantidad_totales":8.5,
"id_pedido":13,
"rows":[{"id_pedidos_productos" :"57",
"cantidad":"1.5",
"descripcion":"prueba con decimales",
"nombre":"Astro naranja"},
{"id_pedidos_productos":"52",
"cantidad":"1",
"descripcion":"",
"nombre":"Gipso grande"},
{"id_pedidos_productos":"54",
"cantidad":"1",
"descripcion":"",
"nombre":"Lilis Rosita"},
{"id_pedidos_productos":"53",
"cantidad":"1",
"descripcion" :"",
"nombre":"Plumosos"},
{"id_pedidos_productos":"56",
"cantidad":"1",
"descripcion":"",
"nombre":"ROSAS BABY VENDELA"},
{"id_pedidos_productos":"55",
"cantidad":"1",
"descripcion":"",
"nombre":"Rosas rojas"},
{"id_pedidos_productos":"51",
"cantidad":"2",
"descripcion":"",
"nombre":"ROSAS ROSITAS \"MATIZADAS\"" }]}
On the page, my table looks like this, I want to display obtained value in the field below the table:
Now, what I want to do is to read returned value named: "cantidad_totales".
I would like to catch it to display in resume section of the page.
Does anyone know how can I do it ?
This is how you could handle it:
var cantidadTotales;
$('#tbl').bootgrid({
formatters:{
...
},
rowCount: [5, 10, 25],
...
labels: {
....
},
css: {
...
},
responseHandler: function (data) {
var response = {
current: data.current,
rowCount: data.rowCount,
rows: data.rows,
total: data.total,
cantidad_totales: data.cantidad_totales,
id_pedido: data.id_pedido
};
//store cantidad_totales into a variable...
cantidadTotales = data.cantidad_totales;
return response;
},
ajaxSettings: {
method: 'POST',
contentType: 'application/json'
},
ajax: true,
url: 'The_Url_To_Load_Your_Data'
}).on("loaded.rs.jquery.bootgrid", function (s) {
//Now, display the cantidad_totales in your div or whatever
$('div#YourTotalDiv').html(cantidadTotales);
});
})
For below JSON
{
"partnerNameListBeanStruts2Map": [
{
"firstName": "sachin",
"partnerId": 123
},
{
"firstName": "Ankit",
"partnerId": 234
}
]
}
What code should I wright to done jQuery autocompleter.
Here is my code.
Here I want autocomplete element's value is like sachin OR ankit and id is like like 123 OR 234 is id of element.
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "list.action",
type : "POST",
data : {
term : request.term
},
dataType : "json",
success : function(data)
{
****What should I write here to work my code?****
}
});
}
});
});
According to the doc, You should return your data with the response callback function.
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
$(function($) {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "list.action",
type : "POST",
data : {
term : request.term
},
dataType : "json",
success : function(data)
{
***response (data) ;***
}
});
}
});
});
I'm generating JSON response from PHP witch looks like this:
{ done:'1', options: [{ message:'Example message'},{message:'This is the 2nd example message'}]}
I want to grab these results using ExtJS. This is what I have so far:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"}
});
What do I have to write next to get the json results like this:
var mymessages = jsonData.options;
And mymessages should contain Example message and This is the 2nd example message.
Thank you.
The straightforward approach:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(resp) {
// resp is the XmlHttpRequest object
var options = Ext.decode(resp.responseText).options;
Ext.each(options, function(op) {
alert(op.message);
}
}
});
Or you could do it in a more Ext-ish way using Store:
var messages = new Ext.data.JsonStore({
url: 'myfile.php',
root: 'options',
fields: [
{name: 'text', mapping: 'message'}
],
listeners: {
load: messagesLoaded
}
});
messages.load({params: {id: "1"}});
// and when loaded, you can take advantage of
// all the possibilities provided by Store
function messagesLoaded(messages) {
messages.each(function(msg){
alert(msg.get("text"));
});
}
One more example to address the last comment:
var messages = [{title: "1"},{title: "2"},{title: "3"}];
var titles = msg;
Ext.each(messages, function(msg){
titles.push(msg.title);
});
alert(titles.join(", "));
Although I would prefer doing it with a Array.map (which isn't provided by Ext):
var text = messages.map(function(msg){
return msg.title;
}).join(", ");
alert(text);
Use the success and failure properties:
Ext.Ajax.request({
loadMask: true,
url: 'myfile.php',
params: {id: "1"},
success: function(response, callOptions) {
// Use the response
},
failure: function(response, callOptions) {
// Use the response
}
});
See the Ext API docs for more details
check this sample fiddle which is for Ext JS 4. http://jsfiddle.net/mrigess/e3StR/
Ext 4 onward utilizes Ext.JSON.encode() and Ext.JSON.decode() ; while Ext 3 uses Ext.util.JSON.encode() and Ext.util.JSON.decode()
if you are sure that your input is correct (beware of xss attacks) you can use the eval() function to make your javascript object from your json result, which can then be accessed through your command:
var mymessages = jsonData.options;
But then again, Ext does that nicely for you, as Rene has pointed out through the Ext.decode function