ajax-loading doesn't stop or infinite loop? - javascript

I'm not sure if it is an ajax issue or if I have an infinite loop, I'm trying to get the values of one page to another.
My 1st page is a cakephp contoller:
$arr = ($this->Phone->find('all'));
$arr2 = json_encode($arr);
echo $arr2;
$_GET ['var1'] = $arr2;
die();
My 2nd page that gets and displays the output is this one
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="sizeof.js"></script>
<script type="text/javascript">
var results;
{
$.ajax({
type: 'GET',
url: 'http://localhost/restdemo/',
data: {
var1: results
},
success: function(data) {
console.log('success');
var output = JSON.parse(data);
for (x = 0; x <= output.length - 1; x++) {
var hello = (output[x]["Phone"]["name"]);
document.write('<table border="1" cellspacing="1" cellpadding="5">');
document.write('<tr>');
document.write('<td>' + hello + '</td>');
document.write('</tr>');
document.write('</table>');
}
}
});
}
</script>
</head>
<body>
</body>
</html>
I am getting my desired results however the page doesn't stop loading which makes me think that I have an error in my code to cause such an action. What causes this?and how can I fix it?. any feedback, comments and suggestion is highly appreciated.

Related

My ajax call returns a data with html code

I saw some posts with this question, but I still have the problem. When I make my ajax call, it returns the data that I expect, but with the HTML code of the whole page. I tried to put dataType : 'Jason' and many other things, but they don't help me.
function validarUsuario()
{
var Pseudo = $('#Pseudo').val();
$.ajax({
url:'Bienvenu.php',
method:"POST",
data:{'Pseudo':Pseudo},
success:function(data)
{
console.log('|' + data + '|')
if(data != '0')
{
alert('pseudo already taken');
}else
{
alert('pseudo correct');
}
}
});
}
///Bienvenu.php/////
if(!$stmt->execute())
{
$sBody .= 'erreur<br />';
}
else
{
$iNbResultat = $stmt->rowCount();
echo $iNbResultat;
}
///OUTPUT Firefox/// This is the data when I use console.log(data)
|<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1 /jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"> </script>
0</body>
</html>

Live Data Feed and Scrollbar Position

I am retrieving data from a MySQL database and displaying it on a website using the EventSource API. So far everything is working as expected, but I want to display the data in a fixed height div, and fix the scrollbar to the bottom of this div - i.e always show the latest feed results first.
Now when I load the page the scrollbar is fixed to the top.
I have tried the suggestion here but it doesn't seem work. Is it because I am working with live data and AJAX requests in order to populate the div?
My cose so far is;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<style type="text/css">
#result {
overflow: auto;
max-height:224px;
width: 500px;
}
</style>
<script type="text/javascript">
// scrollbar to bottom
$("document").ready(function(){
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
});
// retrieve data from server and display in div
$("document").ready(function(){
var source = new EventSource("data.php");
var offline;
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
} // end success
});
});//end dom ready
</script>
</head>
<body>
<div id="result"><!--Server response inserted here--></div>
</body>
</html>
The strange this is, whenever I remove the live feed javascript and manually add some (lorem ipsum) text into the <div id="result"> it works, the scrollbar appears at the bottom of the div.
I could be doing something very silly :)
Any advice is appreciated.
When you load more data via ajax, the size of the content will change. Have you tried setting the scroll again after you've rendered the content? i.e.:
success: function(data){
var objDiv = document.getElementById("result");
$.each(data, function(key, value) {
objDiv.innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});
Thus setting the scroll value the same way you do when the page loads.
Alternatively, here's another completely different option:
If you want the most recent values to be most prominent, you could simply output them in reverse order, so the newest ones are at the top of the div, where the user will see them first. You can use jQuery's .prepend() method to add content to the beginning of the div, above the previous results. Then there's no need for messing about with scrolling. http://api.jquery.com/prepend/ I'd argue this is more user-friendly, but it's up to you obviously.
I'm not 100% sure about this but one issue that I see is that you're making an asynchronous AJAX call to the server after you scroll to the bottom of the div.
Maybe try something along the lines of this:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<style type="text/css">
#result {
overflow: auto;
max-height:224px;
width: 500px;
}
</style>
<script type="text/javascript">
// retrieve data from server and display in div
$("document").ready(function(){
var source = new EventSource("data.php");
var offline;
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});
});//end dom ready
</script>
</head>
<body>
<div id="result"><!--Server response inserted here--></div>
</body>
</html>
Explanation: The div gets populated after you scroll to the bottom of it. Therefore when the scrolling is executed the scrollHeight property is still at the original height value of the div. Now, if you execute the scroll action after you populate the div, it should work fine.
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
that code doesn't say "anchor" the scrollbar to the bottom, it just says scroll down the actual height of the div once, but since you put this code before your ajax request, your div must be empty, so just put theese two lines at the end of your ajax "success" function.
success: function(data){
$.each(data, function(key, value) {
document.getElementById("result").innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
var objDiv = document.getElementById("result");
objDiv.scrollTop = objDiv.scrollHeight;
}
It was just small line which you were missing, please add below code
$.ajax({
type: "POST",
url: 'data.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
var objDiv = document.getElementById("result");
$.each(data, function(key, value) {
objDiv.innerHTML += "New transaction: " + value.SerialNo + ' ' + value.TimeStamp + "<br>";
});
objDiv.scrollTop = objDiv.scrollHeight;
} // end success
});

counter - Update the number if click increase +1

I want every time a user clicks a button, increases +1 in the counter, and Ajax work every time if user click.
This is just for a test with AJAX and the function will work every time if user click on the button.
My code in HTML:
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="jquery-3.1.1.js"></script>
<script src="JS.js"></script>
<!--script src="JS2.js"></script-->
</head>
<body>
<button id="1" onclick="dadosLog()">
Login
</body>
</html>
Function .js:
var numberOrigin = 0 //
function dadosLog (){
numberOrigin++;
var obj = login("xxxLog", "xxxxxxxPassword", numberOrigin);
}
// Function 2 before function 1 its OK
function function2(otherParameter, numberOrigin){
console.log(xxxxxx);
$.ajax({
type: 'POST',
dataType: 'json',
contentType: "application/json",
url: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/request/create',
data: JSON.stringify({
"synchronize":false,
"sourceRequest":{
"numberOrigin":numberOrigin,
"description": "test"
}
},
}),
success:function(output) {
console.log(output);
alert(output.request.number)
},
error:function(output) {
return '0';
console.log(output);
}
});
}
its work:
var counter = 10; // Enter the value you want to start the counter
function Function1(){
var obj = teste("xxxxxxx", "xxxxxxxxxxx", counter);
counter++;
}
var obj;
function teste (NameV, NameV2, counter){
counter +=1;
// function (...)
Then I will make a connection class with the bank and a field where it will check if the counter number already exists and if not, +1

How to avoid html code from data result

I'm getting some data using php json, well the result bring me the html code too, so the page is giving me a unexpected token. Here my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("ready", function(){
loadData();
});
var loadData = function(){
$.ajax({
type:"POST",
url:"Users.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
</script>
and this is what I see in the console
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
[{"nombre":"Joelbis","apellido":"Rosas"},{"nombre":"William","apellido":"Mazo"},{"nombre":"Mariana","apellido":"De Barros"},{"nombre":"Daniela","apellido":"Ramirez"}]
</body>
</html>
VM396:1 Uncaught SyntaxError: Unexpected token <(anonymous function) # userview.php:22l # jquery.min.js:4c.fireWith # jquery.min.js:4k # jquery.min.js:6(anonymous function) # jquery.min.js:6
How I avoid the html code in the result?
Thank you.
You need a php file that ONLY prints out the data you need returned. Like this:
Ajax Call
var loadData = function(){
$.ajax({
type:"POST",
url:"UserData.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
UserData.php
<?php
$sql = "SELECT nombre, apellido FROM pruebaUsuarios"; $result = mysqli_query($conexion, $sql);
$array_user = array(); while($data = mysqli_fetch_assoc($result)){ $array_user[] = $data; }
echo json_encode($array_user)
?>
Your backend script must stop right after echo json_encode($data), using die() or exit() which are the same. Otherwise it will feed the rest of your page to your AJAX frontend, which is what's currently happening.
var loadData = function(){
$.ajax({
type:"POST",
url:"Users.php"
}).done(function(data){
console.log(data);
data = $(data).find('body').html();
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
Try to parse data from html

How to Print parsed JSON data in HTML page in a table

I have accessed the JSON data through web service call and parsed the JSON data. I would like to know how to print that JSON data in HTML table???
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Download</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function jsonparser1() {
$.ajax({
type: "GET",
crossDomain: true,
url: "http://10.211.2.219:8080/JerseyWebService/rest/sample/files",
dataType: "jsonp",
success: function (res) {
$.each(res['data'], function (i, row) {
var ftime = row['time'];
var fname = row['name'];
var fhref = row['href'];
document.myform.???????????????=ftime;
??????????????????????????????????????
??????????????????????????????????????
})
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<form name="myform">
<input type="button" name="clickme" value="Click here to display the details of the files" onclick=jsonparser1() />
??????????????????????????????????????????
??????????????????????????????????????????
</form>
</body>
</html>
The JSON data i am using is:
{"data":[{"id":13,"time":"02-08-2012 3:24:45 PM","name":"jersey-multipart-1.0.3.144640.jar","href":"file://chndlf716168/TempUp/1343901285087-FileName-jersey-multipart-1.0.3.144640.jar"},{"id":14,"time":"02-08-2012 3:36:0 PM","name":"icloud_hero.png.png","href":"file://chndlf716168/TempUp/1343901960304-FileName-icloud_hero.png.png"}],"code":true}
I would like to display the time,name and href attributes in a table format. The href should be in anchor tag. If more number of data are appended into JSON file means, the table should be flexible to change. First step is that i have to display the details in table format.
Anybody please helpout in this thing... Thanks in advance...
Hope this helps:
$("document").ready(function() {
$.getJSON("http://localhost:1909/encoders", function(data) {
$("#div-my-table").text("<table>");
$.each(data, function(i, item) {
$("#div-my-table").append("<tr><td>" + item.EncoderName +"</td><td>" + item.EncoderStatus + "</td></tr>");
});
$("#div-my-table").append("</table>");
});
});
Try this out
var output = "<table>";
$.each(res['data'], function (i, row) {
var ftime = row['time'];
var fname = row['name'];
var fhref = row['href'];
output+="<tr><td>VARIABLE VALUE</td></tr>";
})
output += "</table>";
When the outpur variable is ready with the content. Print it in the desire location.
This is basic jquery in your each loop do this.
$row = $('<tr></tr>');
$row.append('<td>' + somedata + '</td>');
// repeat the above line for each data item
$('#mytable).append($row);
In your HTML create <table id="mytable"></table>

Categories

Resources