i have this code in ajax
var settings = {
"url": "https://sample.com",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": basicauth,
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"key": "value1",
"key": "value2"
}
};
$.ajax(settings).done(function(response) {
console.log(response);
});
when i execute that code it only submit the value2. How can i make it submit the value1 and value2?
Having duplicate keys in an object will just have the previous values overwritten. To send multiple values with the same key with $.ajax you can pass an array as the value. By default $.ajax uses PHP style parameters so [] will be appended to your key, to avoid this you have to set the parameter traditional: true.
var settings = {
"url": "https://sample.com",
"method": "POST",
"timeout": 0,
"headers": {
"Authorization": basicauth,
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"key": ["value1", "value2"]
},
traditional: true,
};
$.ajax(settings).done(function(response) {
console.log(response);
});
So this is my JSON.stringify'd return before I try to run JSON.parse
{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null},
{"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null},
{"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}
When I try to JSON.parse I get Unexpected end of JSON input. And I can't access it as a JSON object because it will say can't define id or something to that extent.
JSON.parse(this.searchService.searchJson(this.php_url));
this.searchService.searchJson(this.php_url) is basically what my JSON string is. Gives error as mentioned above.
Also if I just try to stringify 1 of the 3 elements, it'll give me Unexpected token u in JSON at position 0
Calling function:
searchJson(url: any): any
{
let items: any = [];
let new_data: any = [];
$.getJSON(url ,
function(data)
{
let temp_items: any = {};
console.log(data);
$.each(data, function (key, val)
{
new_data.push(JSON.stringify(val));
});
});
return new_data;
}
You have to wrap it with [] because that is an array of objects:
const data = [{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}]
console.log(data); will return [Object, Object, Object]
or if you wanna process as a JSON string you should do this:
const data = '[{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}]'
JSON.parse(data) will return too [Object, Object, Object]
Changed the calling function to this:
searchAjax(url: any): any
{
let new_data: any;
return $.ajax({
url: url,
type: 'post',
dataType: "json",
async: false
}).responseText;
}
The most likely cause was that my variable was that my variable was null at the time of being called because of async.
file Nmae: self.json
[
{
"id": "2",
"name": "<small>L</small>(+)-Amethopterin Hydrate",
"class": "6.1",
"subclass": "",
"packing_group": "III",
"un": "2811",
"cas": "133073-73-1",
"poisons": "",
"hazardous": "Yes",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
},
{
"id": "3",
"name": "(+)-Biotin 4-Nitrophenyl ester",
"class": "",
"subclass": "",
"packing_group": "",
"un": "",
"cas": "33755-53-2",
"poisons": "",
"hazardous": "No",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
},
{
"id": "4",
"name": "(+)-Biotin N-hydroxysuccinimide ester",
"class": "",
"subclass": "",
"packing_group": "",
"un": "",
"cas": "35013-72-0",
"poisons": "",
"hazardous": "No",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
}
]
$(document).ready(function($) {
$.ajax({
url: 'self.json',
type: 'GET',
dataType: 'json',
})
.done(function(respose) {
for (var i = 0; i < respose.length; i++) {
resText = respose[i].id+' '+respose[i].name+' '+ respose[i].class+' '+respose[i].subclass;
console.log(resText);
};
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
Output:
I am using a reader in a store to parse a json response:
{ "results": 2,
"errors": "",
"success": true,
"data": [{
"list": [{
"code": "123456",
"otherCode": "Y"
},
{"code": "369852",
"otherCode": "G"
}],
"failedHost": false,
"hostMessage": "",
"hostReturnCode": 0
} ]}
And this is my store:
var gridStore = Ext.create('Ext.data.Store',
{
proxy:
{
url: "myUrl",
reader:{
type: 'json',
rootProperty: 'list',
totalProperty: 'results'
},
type: 'ajax',
model: 'myModel'}}
The server is responding correctly but my store don't parse the response. The problem in my opinion is the deeper rootProperty, but I have found no solution.
Your rootProperty needs to be:
rootProperty: 'data[0].list'
instead of:
rootProperty: 'list'
Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.
I use a standard function to retrieve an image within the system, as we have the binary in the database, this works good throughout the whole system.
Currently implementing jqGrid and have some issues to use the current structure as images don't show up and the jquery structure ($obj = $("<div>");) is not useable.
Now I try to implement to get the binary image, however it won't show up, when using a static url it works and image data is being retrieved.
$.extend($.fn.fmatter, {
getBinairy: function (cellValue, options) {
//var object = $();
var width = 50;
var html = "";
getImage(cellValue).success(function (data) {
$.each($.parseJSON(data.d), function (idx, obj) {
p_image = obj.img;
p_type = obj.type;
p_width = obj.width;
p_height = obj.height;
});
var _width = width / p_width;
var _height = _width * p_height;
html = "<img src='data:" + p_type + ";base64," + p_image + "' />";
//object = $("<img/>", {
// src: "data:" + p_type + ";base64," + p_image,
// width: width,
// height: _height
//});
//object.append($img);
});
//var html = "<img src='img/test/20131027_132450.jpg' />";
return html;
},
As far I think the fn is loading the "html" too fast, I can't understand other reason, however have no idea how to avoid this.
Any help?
---UPDATE---
var ip = "";
var station = "";
return $.ajax({
type: "POST",
url: "services/general.asmx/SendBinairy",
data: JSON.stringify({ session: 'ed6d1cc6-82f9-46e8-91bb-eae341a771cf', ip: ip, station: station, id: id }), ///, _filter: JSON.stringify(_json) }),
contentType: "application/json; charset=utf-8",
dataType: "json",
loaderror: function (xhr, status, error) {
},
success: function (data) { }
});
---UPDATE---
"dataset": [
{
"id": 5,
"suffix_type_id": 0,
"sexe_type_id": 1146,
"first_name": "Varvara",
"middle_name": "",
"last_name": "D",
"full_name": "Varvara D",
"company_name": "",
"nickname": "",
"birthday": "1983-12-18",
"age": 31,
"language_type_id": 6,
"relation_type_id": 0,
"job_status_type_id": 404,
"nationality_type_id": 0,
"last_online": "",
"last_online_app_id": 0,
"profile_image": 24,
"profile_rating": 7.000,
"number_contacts": 0,
"number_applications": 0,
"address_id": 0,
"address_1": null,
"address_2": null,
"address_3": null,
"number": 0,
"add": null,
"postal_code": null,
"city": null,
"city_type_id": 0,
"latitude": null,
"longitude": null,
"state": null,
"state_type_id": 0,
"country_type_id": 0,
"address_type_id": 0,
"image": [
{
"file_id": 24,
"binary": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIB
And this is how I add the data to the jqGrid
$("#" + grid_id).jqGrid({
loadonce: true,
type: "POST",
url: "services/general.asmx/HelloWorld",
postData: { q: session },
datastr: colD,
contentType: "application/json; charset=utf-8",
datatype: "jsonstring",
colModel: colM,
rowNum: 10,
rowList: [10, 20, 30],
pager: '#' + grid_id,
sortname: 'id',
viewrecords: true,
sortorder: "desc",
The function getImage is undefined in your code, but I still think that you've chosen wrong way for getBinairy formatter. I suppose that you makes asynchronous Ajax call to the server inside of the formatter. So the function getBinairy returns "" (the initial value of html variable).
I recommend you to change the format of cellValue - the format of data for the column which returned by filling the main grid. For example the data could be JSON encoded object {src:.., width:... , height:... } or {mimeType: ..., charset: ..., base64: ..., width: ... , height: ...} or some other. It's important just that the input data should be full and the formatter will be just produce <img> based on the data without any Ajax calls.