I want to read json from php server using javascript (not jquery) like
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
json = xmlhttp.responseText;
JSON.parse(json, function (key, val) {
alert(key + '-'+ val);
});
}
}
in php file i do
$data = array();
$data['id'] = '1';
$data['name'] = '2';
print json_encode($data);
But output is
id-1
name-2
-[object Object] // why??
How to fix that thanks
If you are using normal javascript, You want to loop through the properties of an object, which u can do it in javascript with for in statement.
<script>
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
var data = JSON.parse(xmlhttp.responseText);
for(key in data)
{
alert(key + ' - '+ data[key]); //outputs key and value
}
}
}
xmlhttp.open("GET","sample.php",true); //Say my php file name is sample.php
xmlhttp.send();
</script>
From the MDN documentation about JSON.parse:
The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value.
Parsing {"id":"1","name":"2"} will generate a JavaScript object. Hence, in the last call of the reviver function, key is an empty string and val is the generated object.
The default string representation of any object is [object Object], so the output you get is not surprising.
Here is a simpler example:
// object vv
alert('Object string representation: ' + {});
You usually only use a reviver function if you want to transform the parsed data immediately. You can just do:
var obj = JSON.parse(json);
and then iterate over the object or access its properties directly. Have a look at Access / process (nested) objects, arrays or JSON for more information.
Related
I have the following code :
<head>
<script>
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp["elem"] = elems[i];
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
this["elem"].src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
}
};
</script>
</head>
<body onload="startChanging()">
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
</body>
Even though I create a new instance of XMLHttpRequest for each iteration and add the current element to an attribute, when the request returns a response only the last img element is changed.
I am looking for a simple solution to change the src of the img element without iterating through all the elements again when the response comes. I would like a pure Javascript solution (read: no JQuery).
I am certainly doing something wrong here I just don't understand what. Any help would be appreciated.
In your for loop, you are overwriting the xmlhttp variable so when you get into the onreadystatechage function and you check the value of xmlhttp.readyState, it will not be checking the right object.
I'd suggest this fix which changes two things:
It puts each ajax call into it's own IIFE which keeps the xmlhttp variable separate for each ajax call.
It passes elems[i] into the closure so you don't have to do the property saving hack.
Code:
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
(function(obj) {
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
obj.src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
})(elems[i]);
}
};
One possible approach:
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
this.elem.src = this.responseText;
}
}
As you see, I've replaced all the references to xmlhttp within that handler function to this.
The problem is even though you've created a new AJAX-serving object at each step of the loop, each newly-created 'readystatechange' handler function referred to the same object known under xmlhttp variable.
In general, this is quite a common problem when someone works with a variable declared within a loop yet referred by functions created in the same loop. Stumble upon this once or twice, and you'll begin to see the pattern. )
xmlhttp.send();
Put data into the send method:
xmlhttp.send(data);
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
void send();
void send(ArrayBuffer data);
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Where data is a JavaScript variable, you can put anything into. If you want multipart message, you'd use var data = new FormData(); and put data into it using data.append('image', file); for file upload via ajax for example.
If no multipart, simply put anything in like:
data = { images: document.getElementsByTagName("img") }
I am working on a project for a client and they want to be able to update a list of costs dynamically depending on the registrants status as member/non-member or student. So I thought AJAX would have been the best way to do this but I am having trouble with my implementations. Every time I send my object I get a syntax error. I have placed the code below.
JavaScript
function checkMember(){
var member = document.getElementById("user_mem_id");
if(member.value == "" || member.value.trim() == ""){
document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
document.getElementById("testError").style.color = "red";
}else{
var json = { "data":[{"membership_id":member.value}]}
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
xmlHttp.open("POST","member_check.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("data=" + json);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("testError").innerHTML=xmlHttp.responseText;
console.log(xmlHttp.responseText);
json_last_error;
};
};
}
}
PHP
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data[membership_id];
}
The other issue is that when I try and access the membership "cell" of the data array I get illegal off set string. Thus I thought I had declared my original JSON object incorrectly but I appears (as I have viewed many examples on here and else where) that I have declared that correctly.
I think you need to use stringify in order to perform the post successfully.
var json = { "data":[{"membership_id":member.value}]};
json_data = JSON.stringify(json);
then use json_data in your ajax call.
There are quite a few things wrong with your code. As I stated in my first comment to you, you need to escape your json before you send it in the query string, as json converted to a string, without any special rules applied turns into [object Object], and that isn't valid json, nor is it parsed as such.
To do that, use JSON.stringify(json);. Example:
function checkMember(){
var member = document.getElementById("user_mem_id");
if(member.value == "" || member.value.trim() == ""){
document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
document.getElementById("testError").style.color = "red";
}else{
var json = { "data":[{"membership_id":member.value}]}
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
xmlHttp.open("POST","member_check.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("data=" + JSON.stringify(json));
//json turned into proper string
//I should also note, you should url-encode this string if it contains
//any special characters using encodeURIComponent()
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("testError").innerHTML=xmlHttp.responseText;
console.log(xmlHttp.responseText);
//json_last_error; //Commented this out, as it will
//echo an error, causing the script to halt, as it doesn't
//exist.
};
};
}
}
Secondly, you send an object whose key 'data' contains an array of objects.. not a simple object:
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data[membership_id]; // There are many things wrong here
// ^ ^ this is not a constant and likely does not exist.
// |- This is still your string, which doesn't work
}
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $res['data'][0]['membership_id'];
// ^ ^ ^ ^
// | |first item |-string
//The result|-string
}
Hopefully my comments will be self explanatory.. but in case they are not... $res is your decoded array, 'data' is the first position of that array, 0 is the first position of the array at that position, and 'membership_id' is the item you want to access. You access members as strings, indexes as integers.
The basic problem with your code is the ";" terminator when you are defining variable. Check your following line
json = { "data":[{"membership_id":member.value}]}
You haven't put a semicolon at the end. (however it might still work a few times but mostly its an error)
Rather you have written a lot of code too. I would suggest you to use jquery's $.ajax function to simplify your task.
Also in case if you only have membership id in your json data its more easy to create a json object like the one below
var json = {"membership_id" : member.value " } ;
Also you need to send your json data after quoting in string using JSON.stringify(json)
I imagine at some point my familiarity with PHP is making me write something incorrectly, but I've been reading up and can't seem to find a way to achieve what the below is intended to achieve. In the end, I should have a multidimensional array like such:
cardArray[#]
'uniqueID' => "#";
'cardName' => "blahblah";
'series' => "blahblah";
(Where the #s are actual numbers, of course.) The string that is returned via AJAX is formatted such that each set of 3 is delimited by a colon and within each set each item is delimited by a pipe. (The final line I just threw in as a test to see if ANYTHING was getting stored.)
Here's the code:
function buildCardList() {
var returnedString;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
returnedString = xmlhttp.responseText;
}
}
xmlhttp.open("POST","test02.php",true);
xmlhttp.send();
var cardArray = new Array();
cardArray = returnedString.split(":");
for (var i = 0; i < cardArray.length; i++) {
var tempVar = cardArray[i];
var tempArr = tempVar.split("|");
cardArray[i] = {
"uniqueID" : tempArr[0],
"cardName" : tempArr[1],
"series" : tempArr[2]
};
}
document.getElementById("test").innerHTML = cardArray[0]['uniqueID'] + "<br>" + cardArray[0]['cardName'] + "<br>" + cardArray[0]['series'] + "<br><br>";
}
I want to display the binary code of a music file. But somehow the code below doesn't seem to work. Any suggestions??
function binary() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","1.wav",true);
xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
xmlhttp.onreadystatechange = function(buffer) {
var binaryCode = "";
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var binStr = this.responseText;
for (var i=0; i<binStr.length; i++) {
var byte = binStr.charCodeAt(i) & 0xff; // get byte at i
binaryCode += byte;
}
}
document.getElementById("result").innerHTML = binaryCode; // should display binary code
};
xmlhttp.send();
}
Not all byte values are expressible in a string and will not appear or cause the string to cut off short.
XMLHttpResponse.ResponseText/ResponseXML will return the http response content as a string. Any byte values of 0 for example will terminate the string.
Have the server return a Base64 representation of the bytes and decode into byte values on the client side.
Your code seems to be working fine on my chrome browser.
What is exactly the problem your are experimenting ?
You may want to display the binary in an hexadecimal form by doing something like:
binaryCode += '0x' + byte.toString(16) + ' '
edit:
this jsfiddle works on my chrome:
http://jsfiddle.net/e6Kfk/
However, i do not think that this method is crossbrowser, especially if you want to deal with ie (haven't tested it though)
i have problem in getting and testing the return value of ajax.
my code is, and return when alert is => Nan.
function getValue(table1, table2, id1, id2)
{
alert("table name "+table2+" id: "+id2);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("ajax value: "+xmlhttp.responseText - 0);
var val = xmlhttp.responseText - 0;
var price = document.getElementById("price");
var original= price.value;
original = original - 0;
var new_val = original + val;
price.value = new_val;
document.getElementById("showprice").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","_pages/ajax/advert_temp.php? t1="+table1+"&t2="+table2+"&id1="+id1+"&id2="+id2+"",true);
xmlhttp.send();
}
I am assuming you are talking about this alert.
alert("ajax value: "+xmlhttp.responseText - 0);
Order of operations here says
Add "ajax value: " and xmlhttp.responseText
Take result of 1 and subtract zero [aka "stringNumber" - 0 = NaN]
You need to change the order of operations so it is
alert("ajax value: " + (xmlhttp.responseText - 0) );
But it really makes no difference in your alert if it is a string or a number since the alert displays strings.
You can also use parseInt or parseFloat for converting numbers which some people might like to read instead of -0.