1

When I try to draw data from a database, my javascript is returning the JSON twice. Why would my JSON return this way?

PHP:

<?php
require ('functions.inc');
dbconn(); //establish my db connection
mysql_selectdb("acts");
$query = mysql_query("SELECT * from actInfo");
while ($row = mysql_fetch_assoc($query)){
     $name = $row[ActName];
}
$json=json_encode($name);
echo $json;
?>

Javascript:

function getActNames(){
if (windows.XMLHttpRequest)
{
     xmlhttp=new XMLHttpRequest();
}
else
{
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
     var json = xmlhttp.responseText;
     var parseV = JSON.parse(json);
     $("#somediv").append(parseV);
}
xmlhttp.open("POST","PHP/actMgmt.php",true);
xmlhttp.send();
}

And I'm calling it in HTML via the following:

<p class = "button" onclick= "getActNames();return false;">Some Button </p>

My JSON call is creating 2x the requested records. SO instead of getting the following:

["act1","act2","act3"]

I am getting:

["act1,"act2","act3"]["act1","act2","act3"]

It seems that every time, its called twice.

ALSO, when I just go to the PHP page, it only returns the following like I expect:

["act1","act2","act3"]

**EDIT

var_dump($name) outputs: array(6)=>{ [0]=>string(4)"act1" [1]=> string(4)"act2" [2]=> string(4)"act3"}

**EDIT

console.log(xmlhttp.responseText) gives me:

JSON.parse: unexpected end of data
["act1","act2","act3"]
5
  • all of the articles in this table are unique for that column Commented Nov 8, 2013 at 1:36
  • Can you var_dump($name) and output that? Commented Nov 8, 2013 at 1:37
  • Hey Shivanshu, thanks for the info but I already have separate pages. Using the javascript as an intermediate between my PHP page that gets the data and my HTML page that presents it. Commented Nov 8, 2013 at 1:37
  • Added var_dump to question. Commented Nov 8, 2013 at 1:41
  • Can you also console.log(xmlhttp.responseText) ans show here? Commented Nov 8, 2013 at 1:43

3 Answers 3

1

I see it now. I would, in the future, HIGHLY suggest you use a framework like jQuery to avoid this. Writing your own AJAX function tends to lead to problems like this. Your AJAX call isn't checking for a proper status. It's just looking for any return at all. As such, every time you get a packet, it kicks off your anonymous function.

Change your code to this and you should get only one array

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
     var json = xmlhttp.responseText;
     var parseV = JSON.parse(json);
     $("#somediv").append(parseV);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, gave it a shot. Same result.
Edited response. I bet that fixes it
Wow, I'm not that great as JS yet but I def knew I should have included that. Bit of a newb move I guess. Thanks for your help! Worked PERFECTLY.
That's a major reason why I recommend jQuery. I hate writing my own calls like this. JQ saves you the headache :)
0

It is due to multiple ajax call on the same page(you can observe that as this may happen on first run), so not a solution but still you can escape from the current scenario, by making seperate php and html(containing ajax) pages,

7 Comments

Can you tell me where I am making the duplicate calls here? I have checked and no other JS function in my scripts call this.
Intentionally you are not, Its default !
What is the best way to just get the single result? <<Thats an answer I'd +1 :)
as I said earlier, just code ajax+html on a separate page and php on a separate page, just give it a try at least !
I have an html page, a separate JS script file, and a separate PHP file. Is that what you mean?
|
0

according to w3schools the onreadystatechange event is triggered every time the readyState changes.

which means in every request cycle it is called more then once with the possible options:

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

so what you need to do is:

function getActNames() {
    if (windows.XMLHttpRequest) {
         xmlhttp=new XMLHttpRequest();
    }
    else {
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        // Called when the request finished successfully and response is ready.
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
             var json = xmlhttp.responseText;
             var parseV = JSON.parse(json);
             $("#somediv").append(parseV);
        }
    }

    xmlhttp.open("POST","PHP/actMgmt.php",true);
    xmlhttp.send();
}

seeing as you are using jQuery I strongly advise you use the jQuery ajax as shown:

$.post("PHP/actMgmt.php", { pram1: "value1" }, function( data ) {
    $("#somediv").append(data);
}, "json");

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.