JSON returning duplicates - javascript

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"]

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);
}
}

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,

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.

Related

How do I get value from SQL using AJAX

I know how to pass data from JS to PHP using AJAX, but have no idea how to select data to JS from db using AJAX+php.
I tried to find examples of it but nothing clear found.
Could anyone show me how can I get data from SQL? How I tried:
js function
getdata() {
// ?
var result // I want result to store here
var data = new FormData();
data.append('somekey', 'somevalue');
// AJAX CALL
var xhr = new XMLHttpRequest();
// query for getting some data from SQL
xhr.open('POST', "../php/get_answer.php", true);
xhr.onload = function(){
result = this.response // I presume that I can get result here
};
xhr.send(data);
console.log("RESULT GETTING JSON")
console.log(result)
}
get_answer.php
<?php
include("config.php");
$con = setConnection();
$id = $_COOKIE["id"];
$query = "SELECT results FROM `survey_results` WHERE user_id='$id'";
$n = mysqli_query($con, $query);
$results = 0;
while ($row = mysqli_fetch_assoc($n)) {
$results = $row['results'];
}
// return results ?
$con->close();
?>
In your php file, you can return your data as JSON string.
To do this, tell the client it's json by settings the response header to
header('Content-Type: application/json');
and return the results or data with
echo json_encode($data);
For the Javascript part, XMLHttpRequest is now an old way to make Ajax request but it's a good start to learn.
Fisrt, in your code you have to check if XMLHttpRequest is available in the navigator and try to use the old IE fashion way if not. To do this:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
now you have your object so you have to set a listener witch listen for change in the state of XMLHttpRequest. If all seems ok the result go there:
xhr.onreadystatechange = function()
{
console.log("Wait server...");
if(xhr.readyState == 4) // 4 : request finished and response is ready
{
if(xhr.status == 200) // HTTP OK
{
console.log("Got data!");
result=xhr.responseText; // or result = JSON.parse(xhr.responseText) to have your data as js object
//It's here you have to modify your dom to show your data, change a variable, etc...
} ;
else // bad http response header like forbiden, not found, ...
{
console.log("Error: returned status code", xhr.status, xhr.statusText);
}
}
};
now you can set the URI and send your request:
xhr.open("GET", "../php/get_answer.php", true);
xhr.send(null)
;
If you want more informations about states and status, have a look at XMLHttpRequest Object Methods

I am trying to implement an AJAX call. What am I doing wrong?

This is my HTML text:
<input type="text" class="resizedsearch" name="searchdb">
<button id="submit" onclick="ajaxCall()">Search!</button>
This is Javascript:
ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
}
And this is where I am trying to display the response that I am receiving from the PHP file:
<b><font size="24" face="Cambria"><p id="democity"></p></font></b>
<font size="6" face="Cambria"><p id="demodes"></p></font>
</br>
The output of the PHP file is stored in $outp and it is in the JSON format.
Any help appreciated. Thank you.
!!UPDATE!!
function ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
}
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
This is how the improvised code looks. Still not working.
Example by FactoryAidan is not going to work as it violates Same Origin Policy (unless you'll run the code in browser console on Google page). Try replacing http://www.google.com with your local address. I tested the code with a little modification and it works, or at least gives alert, so the function is called. Here's it is:
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080"; /* but make sure the url is accessible and of same origin */
xmlhttp.onload=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here');
}
Your code update after my first answer looks like it was done in haste and I think makes the question a little harder. The .open() and .send() methods ended up inside your .onreadystatechange function definition but they need to be outside. Your first one didn't have those placement issues. The code I wrote below has your exact building blocks but with no placement issues so you should be able to follow along with how it matches your example code. I also tested it and it sucessfully sends and receives data back and successfully calls the myFunction() callback function.
Nonetheless, I took your code and rewrote it a bit. If you get an alert('') message when you run it, that means that your xml request worked perfectly. If you don't see an alert('') message. It means your xml request is returning a http 404 error, which means your request URL is bad. Try changing your request URL to something you know won't give you a 404 error, like 'http://www.google.com'. If it works and you get the alert message, then the only problem is that your localhost:8080 url is a bad url.
Also, in your myFunction callback function, javascript treats line-breaks as the end of a line of code. So you must write assignments that use an '=' sign on the same line with no line-breaks. Due to this javascrit principle, you also don't need a semicolon ';' at the end of a single line like you would in PHP script.
Finally, a big cause of errors can be the JSON.parse() call. The data received MUST be a valid json string. So if the URL you call returns anything other than pure json... your myFunction() callback function will break on the JSON.parse() command.
Lastly, if there is an error in your myFunction() callback function, your browser inspector will not report it in a useful way and will instead throw an error that points to your xmlhttp.onreadystatechange=function(){} as being the culprit because that is where the browser thinks the error resides (being the calling function), even though the real error is in your myFunction() callback function. Using my edit of your ajaxCall(){...} code and with a valid url, you can be positive that the ajax call works and any errors you have are in your myFunction() callback function.
Lastly again, You have to be careful in your callback function because there are so many things that could break it. For example, document.getElementById() will cause an error if no html element exists on your web-page with the id you provided. Also, if the JSON you received back from the ajax call is missing any properties you mentioned like (city or latitude) it is likely that the innerHTML will be set to 'undefined'. But some browsers may treat the missing json properties as an error instead of just saying they are 'undefined' when you try to call them.
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://www.google.com";
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here')
/*
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML = obj.city
document.getElementById("demodes").innerHTML = obj.description
document.getElementById("latlon").innerHTML = obj.latitude + "," + obj.longitude
*/
}

If statement always proving false when using the $_GET[] global variable set with AJAX

I started learning about AJAX very recently and this little problem seemed to have come out of no where. I wrote an html page that uses this code to create an AJAX connection and send a get request with an id.
function loadXML() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("text").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "textTesting.php?id='first'", true);
xmlhttp.send();
}
In my textTesting.php, just for the sake of testing, I compared incoming variable $_GET[id] with the string I expect to be true, first. But the comparison always seem to fail for some reason.
textTesting.php:
<?php
$output = "";
if(isset($_GET["id"])) {
$output = $_GET["id"];
if($output == 'first'){
$output .= " confirmed";
}
}
echo $output;
?>
Is there a concept of PHP or AJAX that I am missing? When writing this if statement I was expecting 'first confirmed' to become the output.
Please ask any further question if needed.
The value you are passing is 'first' but you are comparing it against first so it doesn't match.
In your query string the quotes are data. In your PHP, the quotes are string delimiters.
Either add quotes to the data in the PHP or remove them from the query string.

Sending data from javascript to php file

I have this function that gets text from a php file on the server and plonks it into an HTML page.
What changes do I need to make to it to SEND data (just a couple of javascript variables) to the php file rather than read from it ? Hoping not many !!
function process() {
if (xmlHttp) // the object is not void
{
try {
xmlHttp.open("GET", "testAJAX.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch (e) {
alert(e.toString());
}
}
}
Take a look at what all headers you can make use of. In your case, you would want to use POST instead of GET
xmlHttp.open("POST", "testAJAX.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//or JSON if needed
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(data);
You are probably better of using POST to send data it has less limitations. e.g:
var data = {
user: 'Joe',
age: 12
};
var httpReq = new XMLHttpRequest();
// true means async - you want this.
httpReq.open('POST', 'testAJAX.php', true);
// json is just a nice way of passing data between server and client
xmlhttpReq.setRequestHeader('Content-type', 'application/json');
// When the http state changes check if it was successful (http 200 OK and
// readyState is 4 which means complete and console out the php script response.
httpReq.onreadystatechange = function () {
if (httpReq.readyState != 4 || httpReq.status != 200) return;
console.log(httpReq.responseText);
};
httpReq.send(JSON.stringify(data));
And read it:
$name = json_decode($_POST['name']);
$age = json_decode($_POST['age']);
If it's just a couple of variables, you can pop them into the query string - although you'll want to make sure their values won't break your PHP script or open a security hole (for example, don't interpret user input as a SQL string). For more complicated data structures, use POST as others have suggested.
function process(var1value, var2value) {
if(xmlHttp) {
try {
xmlHttp.open("GET", "testAJAX.php?var1="+var1value+"&var2="+var2value, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} catch(e) {
alert(e.toString());
}
}
}

Javascript Returing Value from httprequest

The php script is returning a value and the 1st alert works.
I am unable to reference the value returned by httprequest at the 2nd alert. Ideally, I would call the function get_captcha() - and it would return the value - its just that I dont know how to do this.
I realize setting the variable globally may not be the best way to do this but its the only thing I could think of - Im open to alternatives.
<script type="text/javascript">
var url = "captcha_get_code.php"; // The server-side script
var cap;
function ValidateForm() {
get_captcha()
alert(cap); //undefined
}
function get_captcha() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
if (http.status==200) {
//return http.responseText;
cap=http.responseText;
alert(cap); //this one works
}
}
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
You cannot "return" values from successful XMLHttpRequest invocations. You can perform whatever sort of processing you need inside the callback function.
XMLHttpRequests are performed asynchronously. You cannot make your code "wait" for them (unless you make them synchronous) (and you really, really should not do that). There's no real need, however, because the runtime system will call your "readystatechange" handler when the request completes. From in that code, you're free to do whatever you need.
This fact requires you to think a little differently about how to write the code, but it's not really that much of an adjustment. If, for example, you would be inclined to write a "processResults()" function, then you can still do that — you would simply call that from inside the "readystatechange" handler.
I see this thread is 4 years old, but it has wrong answer!
You can get return value from a successful XMLHttpRequest invocations.
My project use WebSocket, but it use XMLHttpRequest to upload images.
In a javascript, call uploadSend(containerID) where all <img> are stored.
// ----- uploadSend()
// ----- This function sends all objects in a container (containerID)
// ----- All object has to be <img>
FILE: upload.js
function uploadSend(containerID) {
var elm = document.getElementById(containerID);
for (i=0; i<elm.childNodes.length; i++) {
var form = new FormData();
form.append('id', elm.childNodes[i].id);
form.append('src', elm.childNodes[i].src);
TOS(form);
}
}
function xhrState(self) {
if ((self.readyState == 4) && (self.status === 200))
console.log(self.responseText);
}
function xhrProgress(event) {
if (event.lengthComputable)
if (event.loaded == event.total)
console.log('Image 100% uploaded.');
}
function TOS(form) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () { xhrState(this); }
xhr.open('POST', '/upload.php');
xhr.upload.onprogress = function(event) { xhrProgress(event); }
xhr.send(form);
}
FILE: upload.php
header("Content-type: text/plain");
$filename = '/var/www/public/upload/'.microtime(true);
// ----- Save a complete file for what we did get.
$hnd = fopen($filename . 'TXT', 'wb');
fwrite($hnd, print_r($_COOKIE, true));
fwrite($hnd, print_r($_GET, true));
fwrite($hnd, print_r($_FILES, true));
fwrite($hnd, print_r($_POST, true));
fclose($hnd);
// ----- Save just jpg for the images we did get.
$hnd = fopen($filename . 'jpg', 'wb');
$image = explode(',', $_POST['src']);
fwrite($hnd, base64_decode($image[1]));
fclose($hnd );
// ----- Type the result that you want back.
echo "{$filename}.jpg";

Categories