Update two different values with one AJAX response - html

I want to update two different values with one ajax-response.
<span id="nr1">Change this</span>
<span id="nr2">and change this</span>
Now I can just change one value, I do like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText;
Is it possible to do something like this:
document.getElementById('nr1').innerHTML = xmlHttp.responseText1;
document.getElementById('nr2').innerHTML = xmlHttp.responseText2;
**** UPDATE ****
The response comes from php.
I'm totally new to JSON.

There are no responseText1 and responseText2 properties of an XMLHTTPRequest(which I assume your xmlHttp is), just responseText, so you have to return something parsable in that responseText field(like JSON). So you server may send back {"firstResponse":"value1","secondResponse":"value2"} and you can fill your fields from that JSON string. Use the json2.js library from json.org
<script type="text/javascript" src="json2.js"></script>
. . .
var theResponse = JSON.parse(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = theResponse.firstResponse;
document.getElementById('nr2').innerHTML = theResponse.secondResponse;
EDIT:
In order to craft this JSON response from PHP you should use the PHP JSON libraries. There are several examples in the json_encode page that can get you started. The other code I posted(and that is posted in other responses) are all browser side javascript code.
$arr = array ('firstResponse'=>'value1','secondResponse'=>'value2');
echo json_encode($arr);
Place that code into your PHP script to generate the JSON string
{"firstResponse":"value1","secondResponse":"value2"}
Then the previously posted javascript code will parse that.

If you trust and control the server, just return a dictionary in JSON for the response and use it on the client side. So:
v = eval(xmlHttp.responseText);
document.getElementById('nr1').innerHTML = v['nr1']
document.getElementById('nr2').innerHTML = v['nr2']

As already said it would make sense to return your Ajax call as a JSON Object. I recommend the more secure JSONP call (don't know if you can use any library that supports this natively).
// Your script returns this
callback123(
{
"nr1" : "This is conten for nr1",
"nr2" : "Some content for nr2"
});
// JavaScript callback looks like this
function callback123(data)
{
for(var key in data)
document.getElementById(key).innerHTML = data[key];
}

use JSON.parse
link text

Related

JSON.parse returning undefined object

Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")

Having trouble retrieving JSON from res

I'm using node, express, and mongoose.
I have a function that performs a search in a database and sends the response in a JSON format with:
res.jsonp(search_result);
This displays the correctly returned result in the browser as a JSON object. My question is, how do I get that JSON object?
I've tried returning search_result but that gives me null (possibly because asynchronous). I'd also like to not edit the current function (it was written by someone else). I'm calling the function and getting a screen full of JSON, which is what res.jsonp is supposed to do.
Thanks in advance.
Just make a new function that takes this JSON as parameter and place it inside the old one. Example:
// Old function
app.get('/', function(req,res){
// recieve json
json_object = .....
// Get json to your function
processJson(json_object);
// Old function stuff
.
.
.
});
function processJson(json_object) {
// Here you'll have the existing object and can process it
json_object...
}

Polymer core-ajax won't post JSON?

I'm using core-ajax to retrieve JSON data just fine. Turning the component around to post back to the server as JSON is another thing altogether. In all cases, and irrespective of the contentType or handleAs parameters passed in, it appears that my JSON object I'm passing in as an input is being converted back to key=value in the server headers.
The code:
var ajax = document.querySelector('core-ajax');
ajax.method = 'POST';
ajax.handleAs = 'JSON';
ajax.contentType = 'application/json';
ajax.params = JSON.stringify(data);
ajax.go();
Really straightforward. The logs in Go give me:
2014/07/22 14:23:09 utils.go:139: OPTIONS /1/users/173?access_token=(token)
2014/07/22 14:23:09 utils.go:124: POST /1/users/173?access_token=(token)
2014/07/22 14:23:09 users.go:379: full_name=Greg%20Johnson
We've verified that there's no transformation happening on our side. Request headers are going out just fine.
I could completely be missing something. How else can we successfully POST out JSON data?
.params is for URL params. What you want is to post the JSON as the request body? For that, I believe you need to set the .body property:
This should do the trick:
ajax.body = data
See https://github.com/Polymer/core-ajax/blob/master/core-ajax.html#L151

how to send the data in Json structure

I have a rest service for which I am sending the Json data as ["1","2","3"](list of strings) which is working fine in firefox rest client plugin, but while sending the data in application the structure is {"0":"1","1":"2","2":"3"} format, and I am not able to pass the data, how to convert the {"0":"1","1":"2","2":"3"} to ["1","2","3"] so that I can send the data through application, any help would be greatly appreciated.
If the format of the json is { "index" : "value" }, is what I'm seeing in {"0":"1","1":"2","2":"3"}, then we can take advantage of that information and you can do this:
var myObj = {"0":"1","1":"2","2":"3"};
var convertToList = function(object) {
var i = 0;
var list = [];
while(object.hasOwnProperty(i)) { // check if value exists for index i
list.push(object[i]); // add value into list
i++; // increment index
}
return list;
};
var result = convertToList(myObj); // result: ["1", "2", "3"]
See fiddle: http://jsfiddle.net/amyamy86/NzudC/
Use a fake index to "iterate" through the list. Keep in mind that this won't work if there is a break in the indices, can't be this: {"0":"1","2":"3"}
You need to parse out the json back into a javascript object. There are parsing tools in the later iterations of dojo as one of the other contributors already pointed out, however most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is:
var str = your_incoming_json_string,
// here is the line ...
obj = JSON.parse(string);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
For the browsers that don't support JSON.parse() you can implement it using json2.js, but since you are actually using dojo, then dojo.fromJson() is your way to go. Dojo takes care of browser independence for you.
var str = your_incoming_json_string,
// here is the line ...
obj = dojo.fromJson(str);
// DEBUG: pump it out to console to see what it looks like
a.forEach(function(entry) {
console.log(entry);
});
If you're using an AMD version of Dojo then you will need to go back to the Dojo documentation and look at dojo/_base/json examples on the dojo.fromJson page.

Post JSON to Codeigniter controller

I am trying to receive and parse a JSON object sent in a POST request using Codeigniter but I cannot "find" it.
This is my controller code:
public function parse () {
$json = $this->input->post();
$json = stripslashes($json);
$json = json_decode($json);
print_r($json);
}
This is my JSON object:
{"data":"value"}
This is the correct way to do it.
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$post = json_decode($this->security->xss_clean($this->input->raw_input_stream));
When you use $this->input->raw_input_stream you can read it multiple times and its basically the same as file_get_contents('php://input'). This works on CI3. I don't know if it works on CI2.
Try this code, it will output an array with all your parameters.
$this->input->raw_input_stream;
$input_data = json_decode($this->input->raw_input_stream, true);
$input_data will return array
Try this instead
$json = $this->input->post('data');
$json = stripslashes($json);
$json = json_decode($json);
print_r($json);
You need to pass in the key of the data variable you want from the post array as an argument to post()
Firze's answer is correct but here is a more elaborated answer. I am not allowed to comment so I am posting it as an answer.
It has to do with CodeIgniter not being able to fetch JSON. jQuery does some under the hood tricks and transforms your data into form-data-x, that's why it works when you don't specify the content type, don't encode your object, or other situations.
If you want a pure JSON the solution is to use $this->input->raw_input_stream to fetch your JSON and decode it using php's json_decode. Check the full answer and code below:
Retrieve JSON POST data in CodeIgniter
controller:
puplic function exam(){
$obj = file_get_contents('php://input');
$edata = json_decode($obj);
echo $edata->name;
}
Go to post man->type->post
url:http://www.exam.com/exam
formate:json
{
"name":"atm fahim"
}
==>send
make sure you have POST data, using $this->input->post() it will always return empty, you should put on the input type name $this->input->post('name_of_input_text')
Are you sure you're POSTing the data and not doing a GET instead? I ran into this issue earlier today (which is how I found this question) and I was doing a POST but using JSONP which seems to be done with a GET.
CodeIgniter has a function called get_post that will get the data from wherever it happens to be.
$this->input->get_post_string('data');
I hope this helps you out.
You can do it manually like so if you'd like.
function get_post($index = '', $xss_clean = FALSE){
if ( ! isset($_POST[$index]) )
{
return $this->get($index, $xss_clean);
}
else
{
return $this->post($index, $xss_clean);
}
}
I know this is an old post, but for others looking, this might be helpful:
On the browser side, I create my data packet using code similar to this pattern:
var form_data = { };
$.each($('#mvt_dialog_form').serializeArray(), function() {
form_data[this.name] = this.value;
});
// add the address data to the payload
var result = {
form_data: form_data,
locations: addressData,
selected_location: selectedLocation
};
// now wrap it all up with a pretty bow
// Seriously, the key:value format is required for codeigniter INPUT class to be able to "see"
var movement = {
movement_dlg: JSON.stringify(result)
};
I then "post" movement to the server.
In the controller, I then use the following logic:
// Perform XSS filtering
$postData = $this->input->post(NULL, TRUE);
$result = json_decode($postData['movement_dlg']);
Just add correct content type to your request header
Content-Type: application/json
In order to use the standard CI methods.
In index.php, insert a couple of lines:
$json = json_decode(trim(file_get_contents('php://input')), true);
if(!empty($json)) {
$_POST = $json;
}
Either implement in the bootstrap.
RIP Codigniter...(
try
json_decode(array($this->input->post()))
OR
$tmp[] = (array)json_decode($this->input->post());
print_r($tmp);