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.
Related
I am getting json response from ajax request
I want to return json result to getTwitterVal() function call in var obj. And then getting name and id in $('#loginTwitter').click(function data() {}. How to this this?
Following code returns alert 'undefined'
function getTwitterVal()
{
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)
{
var result = xmlhttp.responseText;
//result looks like this : {"name": jack,"id":1}
//obj = JSON.parse(result);
return result;
}
}
xmlhttp.open("POST","redirect.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
// api_call();
}
$('#loginTwitter').click(function data() {
var obj = getTwitterVal();
alert(obj.name); // I want retrieve name and id both value here
}
UPDATED code
function getTwitterVal(clb)
{
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()
{
var result = xmlhttp.responseText;
var obj = JSON.parse(result);
clb(obj);
}
xmlhttp.open("POST","redirect.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
// api_call();
}
$('#loginTwitter').click(function data() {
getTwitterVal(function(obj) {
alert(obj.name);
});
});
Gives error
SyntaxError: JSON.parse: unexpected character var obj = JSON.parse(result);
It doesn't work like that. AJAX call is asynchronous. Although it is possible to make it synchronous you should never do it (since it will block all other scripts on the page). Instead pass a callback to getTwitterVal:
function getTwitterVal(clb) {
// some code
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
var obj = JSON.parse(result);
clb(obj);
}
// other code
}
and then
$('#loginTwitter').click(function data() {
getTwitterVal(function(obj) {
alert(obj.name);
});
}
Use asynchronous ajax, as mentioned by #freakish. Also, if you already use jquery, then let it makes its ajax work also. Something like that:
$('#loginTwitter').click(function() {
$.post(
'redirect.php',
function(data) {
var obj = JSON.parse(data);
alert(obj.name);
});
});
I have an application that has a long time processing in code behind.
I was thinking on starting the long time processing by calling from javascript a page,
function OnCopy(type){
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){
//window.clearInterval(interval_handler);
alert('done');
}
}
xmlhttp.open("GET", "<%=Request.Path %>?copy=" + type, true);
xmlhttp.send();
interval_handler = window.setInterval(OnCheckStatus, 1000);
}
The last line of this function will start a timer, to check every second the status:
function OnCheckStatus(){
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){
//window.clearInterval(interval_handler);
//var result = eval(xmlhttp.responseText);
//var pb = document.getElementById('progressbar_' + result[0]);
//if(pb != null)
// pb.innerHTML = result[1] + ' % - ' + result[2];
debug++;
var pb = document.getElementById('progressbar_test');
pb.innerHTML = debug;
}
}
xmlhttp.open("GET", "<%=Request.Path %>?checkstatus=1", true);
xmlhttp.send();
}
On code behind I have this long time processing function and check status function:
private void Copy(string type)
{
Application["ProgressBar.Type"] = type;
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(100);
Application["ProgressBar.Value"] = i.ToString();
}
Application["ProgressBar.Type"] = null;
Application["ProgressBar.Value"] = null;
}
private void CheckStatus()
{
Response.Clear();
string type = (string)Application["ProgressBar.Type"];
string value = (string)Application["ProgressBar.Value"];
if (type == null) type = "";
if (value == null) value = "";
string response = "['" + type + "','" + value + "','" + DateTime.Now.ToString("HH:mm:ss") + "']";
Response.Write(response);
Response.End();
}
Now, the problem is that until the Copy function is not finished, there is no answer on the CheckStatus function from code behind (I think all calls are queued), but, when is finished, the displayed debug value is starting from 10, directly, like all the answers for these 10 calls are coming at the same time.
Is like ASP.NET is only responding to one call only at a time, from the browser. I was having the impression that the server will process at least 2 calls at the same time from the same browser.
Can you help me with this, please?
Please check this article. I think that it will help you with your issue.
But also there is an integrated solution in asp.net webforms named as UpdateProgress msdn link with example
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.
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>";
}
Starts with shuffle functions (just shuffles arrays). It works.
Then I define 2 global variables that will determine the random order for images to be displayed on the page.
picOrder will be a simple array from 0 to picCount, with picCount determined by Ajax onload. The picCount is being retrieved, but the the picOrder array is not being set! If I manually run "arrangePics();" in the console it works. It fills the array picOrder and then shuffles it. But it does not work by placing the calls to both functions inside "" or by putting the "doStuff()" function in there.
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
while (s.length) this.push(s.pop());
return this;
}
var picOrder = new Array();
var picCount;
function getPicCount() {
// picCount = array(10);
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) {
picCount = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/example.com/images.php?count=hello",true);
xmlhttp.send();
//picCount.shuffle;
}
function arrangePics() {
for(var i = 0;i<picCount;i++) {
picOrder[i] = i;
}
picOrder.shuffle();
//alert(picOrder);
}
HTML
<body onLoad="getPicCount();arrangePics();">
or
<body onLoad="doStuff();">
You need to arrangePics() after the asynchronous AJAX call has returned, i.e. you can only call it in the if (xmlhttp.readyState==4 && xmlhttp.status==200) {} (callback) block otherwise you cannot be sure that the data has been fully received.
What is currently happening is that JavaScript is calling getPicCount();arrangePics(); - the first method initiates the AJAX call and returns immediately and then the second method will by trying to arrange 0 pics. Executing arrangePics() manually on the console would have introduced enough delay into the system for the AJAX call to complete and the picCount would be set as expected.
So if you change the callback function to:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
picCount = xmlhttp.responseText;
for(var i = 0;i<picCount;i++) {
picOrder[i] = i;
}
picOrder.shuffle();
}
it should shuffle the pics after the count has been received.