My ajax code doesnt output JSON file - php

So ive been trying to get this to work for hours now but im just stuck.
I have a simple guestbook page setup and I have this code creating a JSON file:
<?php
/* Konstanter för db-inställningar */
define("DBHOST", "localhost");
define("DBUSER", "guestbook");
define("DBPASS", "password");
define("DBDATABASE", "guestbook");
/* DB-anslutning */
$db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBDATABASE) or die('Fel vid anslutning');
$numrows = 999; // Maxvärde
if(isset($_GET['numrows'])) {
$numrows = intval($_GET['numrows']);
}
/* SQL-fråga */
$sql = "SELECT * FROM users LIMIT $numrows";
$result = mysqli_query($db, $sql) or die('Fel vid SQL-fråga');
/* Loopa genom resultet och spara till ny array */
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$json = json_encode($rows, JSON_PRETTY_PRINT);
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
echo $json;
This outputs it in JSON format and then I have this code trying to read the file and output the content of the JSON to this page:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title>Guestbook</title>
</head>
<link rel="stylesheet" href="css/stilmall.css?<?php echo time(); ?>" type="text/css">
<body>
<nav id="mainmenu">
<ul>
<li>Home</li>
<li>Administration</li>
<li>JSON</li>
<li>Webbservice</li>
</ul>
</nav>
<div class="posts">
<h2>WebService</h2>
<div id="info"></div>
<script>
var xhr = new XMLHttpRequest();
// läs ut svar
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
var jsonStr = JSON.parse(xhr.responseText);
var users= jsonStr.posts;
for(var i=0; i<users.lenght; i++) {
document.getElementById("info").innerHTML = xhr.responseText;
}
}
};
xhr.open("GET","http://localhost/webbutveckling2/moment3/webservice.php",true);
xhr.send(null);
</script>
</p>
</div>
</body>
</html>
I cannot for the love of good see what im doing wrong.
I need this to output the JSON content, also I would like to just output the 3 latest entried from the JSON file only.
What im doing wrong?
Edit:
Here is the JSON output:
[
{
"id": "2",
"name": "Emil1234",
"post": "My name is Emil and this is a test for a post on the guestbook wall",
"postdate": "2018-03-15 16:41:10"
},
{
"id": "22",
"name": "golddigger",
"post": "Hi! This is my first visit to this epic guestbook",
"postdate": "2018-03-25 14:52:11"
},
{
"id": "23",
"name": "Tester123",
"post": "Im just doing another test dont mind me",
"postdate": "2018-03-25 14:52:31"
},
{
"id": "24",
"name": "the bluff",
"post": "Whatsup all",
"postdate": "2018-03-25 15:17:17"
}
]
When I update my code in the js to the following:
<script>
var xhr = new XMLHttpRequest();
// läs ut svar
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
document.getElementById("info").innerHTML = xhr.responseText;
</script>
It does put out the raw information in the following way:
How do I output this to be show just the latest 3 posts?
Edit 2:
<script>
var xhr = new XMLHttpRequest();
// läs ut svar
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText);
document.getElementById("info").innerHTML = xhr.responseText;
//var jsonStr = JSON.parse(xhr.responseText);
var users = JSON.parse(xhr.responseText);
for(var i=0; i < users.length; i++) {
document.getElementById("info").innerHTML = users[i].name + " - " + users[i].post + " - " + users[i].postdate ; }
}
};
xhr.open("GET","http://localhost/webbutveckling2/moment3/webservice.php?numrows=3",true);
xhr.send(null);
</script>
This outputs just one, is my url wrong?
Outputs the following:

There is not " numrows " is going as a get request in the ajax call thatsand just try putting the fetch function in a while loop and concatenate in the output variable

Related

ajax send a request in ajax and get the response

Morning! Please i will like to get some data from mySQL(like getting the number of rows of a mySQL table using ajax). Please how can i do it? Here are my 2 pages. The first one send a number to the php page and the second one do a request to the database and send the result to the page in ajax(the first one). The table voisin_par_distance has 3 columns: cel_id, cel_id_1 and cel_id_2 Thanks.
<!DOCTYPE html>
<html>
<body>
<script>
var xhr1 = new XMLHttpRequest();
var i=1;
var j=4;
xhr1.onreadystatechange = function() {
if (xhr1.status == 200 && xhr1.readyState == 4) {
document.getElementById('content').innerHTML = xhr1.responseText;
}
};
xhr1.open('GET', 'test.php?i='+i+'&j='+j, false);
xhr1.send('');
</script>
<?php
// I would line to get for example the number of rows of table voisin_par_distance which is returned by test.php
$m = (int) $_GET['n'];
echo $m;
?>
</body>
</html>
and this is the php page which is in the same directory.
<?php
$dbname='BD';
try {
$bdd = new PDO( 'mysql:host=localhost;dbname=BD', 'root', '' );
}
catch ( PDOException $e ) {
die("Could not connect to the database $dbname :" . $e->getMessage() );
}
$i = (int) $_GET['i'];
$j = (int) $_GET['j'];
//to select the number of rows of my table
$req = $bdd->prepare("SELECT serveur FROM voisin_par_distance WHERE cel_id_1=':cel_id_1' AND cel_id_2=':cel_id_2'");
$req->execute( array(
'cel_id_1' => $i,
'cel_id_2' => $j
) );
$nbre_ligne = count( $req );
?>
<!DOCTYPE html>
<html>
<body>
<script>
var nbre_ligne = <?php echo $nbre_ligne; ?>
var xhr = new XMLHttpRequest();
var a = 2;
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState == 4) {
document.getElementById('content').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'show_map.php?n='+nbre_ligne);
xhr.send('');
</script>
</body>
</html>
Best and Easy way to use ajax:
$.ajax({// on an event
type: "GET",
url: "test.php", #with valid path
data: {col1: "value1", col2: "value2"},
cache: false,
success: function (responce) {
// alert your response to check data
if (responce.length > 0) {
var data = JSON.parse(responce); // Parse JSON
//Your logic here
}
}
});
In Your PHP file, return data in json format. e.g.
echo json_encode(array('col1' => $val, 'col2' => $val2));
exit;
I hope this will help you.

Parsing string on HTML page

I got this string output on a page. its HTML and I need to get it "human readable"
Its stats from a server.
Could you help me getting it a bit more "clear"
The string printed is:
{"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}
Is it possible to get it to be:
Version: 9.7 - CN
Speed: 483
Temp/fan 50 20
and so on, any help is appreciated
This must be done client side
I now have this in a html file:
<!DOCTYPE html>
<html>
<body>
<script>
const regex = /{.*}/g;
var request = new XMLHttpRequest();
request.open('GET', 'http://10.0.0.20:3333', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
var json = regex.exec(resp);
obj = JSON.parse(json[0]);
document.getElementById('content').innerHTML = 'Version: ' + obj.result[0] + '
Speed: ' + obj.result[2].split(';')[0] + ' Temp/fan ' + obj.result[6].replace(';', ' ');
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
request.send();
</script>
<div id="content"></div>
</body>
</html>
Using JavaScript:
var res = {"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}
var text = 'Version: '+res.result[0]+' Speed: '+ res.result[3]+' Temp/fan '+ res.result[6].replace(';', ' ');
Would this help?
<?php
$input = '{"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}';
$parsed = json_decode($input, true);
echo "Version: ".$parsed["result"][0]." Speed: ".explode(";",$parsed["result"][3])[0]." Temp/fan ".str_replace(";"," ",$parsed["result"][6]);
?>
Might not be the prettiest code but you can also do it client-side:
var json = '{"result": ["9.7 - CN", "0", "483;0;0", "483", "0;0;0", "off", "50;20", "45550", "0;0;0;0"]}';
obj = JSON.parse(json);
document.getElementById('content').innerHTML = 'Version: '+obj.result[0]+' Speed: '+obj.result[2].split(';')[0]+' Temp/fan '+obj.result[6].replace(';',' ');
<div id="content"></div>
Client-side version with AJAX call included:
(I'm not sure if it's http or https on the URL you provided but give it a try and see if it solves the problem)
const regex = /{.*}/g;
var request = new XMLHttpRequest();
request.open('GET', 'http://10.0.0.20:3333', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
var json = regex.exec(resp);
obj = JSON.parse(json[0]);
document.getElementById('content').innerHTML = 'Version: ' + obj.result[0] + '
Speed: ' + obj.result[2].split(';')[0] + ' Temp/fan ' + obj.result[6].replace(';', ' ');
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
request.send();
<div id="content"></div>

AJAX JSON Post to PHP

I'm trying to post JSON String via AJAX to PHP, but all examples not work.
First of all I learn https://www.w3schools.com/js/js_json_php.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjson_php_db_post
Then i write own code. But no one of my example code below not working. And return one result:
index.php:6:string '[object Object]' (length=15)
index.php:7:null
index.php:8:null
First variant:
<?php
$JsonPost = file_get_contents('php://input');
if ($JsonPost != null) {
var_dump($JsonPost);
var_dump(json_decode($JsonPost, true));
var_dump(json_decode($JsonPost));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/json');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send(JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Second variant:
<?php
if (isset($_POST['JsonPost'])) {
var_dump($_POST['JsonPost']);
var_dump(json_decode($_POST['JsonPost'], true));
var_dump(json_decode($_POST['JsonPost']));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send("JsonPost=" + JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Please help.
PHP Version 5.6.28
XAMPP v3.2.2 on Windows 10 (64-bit)
Browser Chrome 56.0.2924.87 (64-bit)
UPDATED
Working Example.
<?php
$JsonPost = file_get_contents('php://input');
if ($JsonPost != null) {
var_dump($JsonPost);
var_dump(json_decode($JsonPost, true));
var_dump(json_decode($JsonPost));
} else {
?>
<html>
<script type="text/javascript">
var RequestObject = new XMLHttpRequest();
RequestObject.open("POST", window.location.href, true)
RequestObject.setRequestHeader('Content-type', 'application/json');
var SomeObject = {};
SomeObject.Field1 = 'lalala';
SomeObject.Array1 = [
'lala1', 'lala2'
];
RequestObject.onreadystatechange = function() {
if (RequestObject.readyState == 4 && RequestObject.status == 200) {
document.getElementById("body").innerHTML = RequestObject.responseText;
}
};
//var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
var JsonStr = JSON.stringify(SomeObject);
RequestObject.send(JsonStr);
</script>
<body id="body"></body>
</html>
<?php
}
?>
Many thanks to all who answered.
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send(JsonStr);
Here you are:
Creating some JSON
Setting the JSON as the value of an object property
Implicitly converting the object to a string (which will be "[object Object]")
Sending that string as the request body
But since you are trying to post JSON you should skip steps 2 and 3 … just pass the JSON:
RequestObject.send(JSON.stringify(SomeObject));
Change in you Second variant this:
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
RequestObject.send("JsonPost=" + JsonStr);
to
RequestObject.send("JsonPost=" + JSON.stringify(SomeObject));
Why:
var JsonStr = { creates an new real javascript object
but this object can not used with + to concate it
Your problem is this:
var JsonStr = {JsonPost: JSON.stringify(SomeObject)};
that is still a javasript object, you have to stringifly the whole thing
so this should wok:
var JsonStr = JSON.stringify({JsonPost: SomeObject});
RequestObject.send(JsonStr);

Populate a text box based on a dynamic drop down box

I am trying to populate a text box based on a dynamic dropbox that is populated from the database.
My Code is as Below :
index.php
<?php
include "../conn.php";
?>
<html>
<head>
<title>Changing textbox value based on dropdown list using Ajax and PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script>
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL){
var req = getXMLHTTP();
if (req){
//function to be called when state is changed
req.onreadystatechange = function(){
//when state is completed i.e 4
if (req.readyState == 4) {
// only if http status is "OK"
if (req.status == 200){
document.getElementById('cur_code').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body style="font: 12px Verdana, Arial, Helvetica, sans-serif;">
<form style="text-align:center" method="post" action="" name="form1">
<p style="color:#000099 ">When you change the dropdown list, the respective currency code of the country will be displayed in the textbox which is fetched from PHP using Ajax. </p>
<p>Department : <?PHP
echo "<select name= 'Department' class='form-control selectpicker' onChange='getCurrencyCode('find_ccode.php?country='+this.value)' Required>";
echo '<option value="">'.'--Please Select Department--'.'</option>';
$sql = "SELECT ID,Name FROM Departments";
$query = sqlsrv_query($conn,$sql);
$query_display = sqlsrv_query($conn,$sql);
while($row=sqlsrv_fetch_array($query_display,SQLSRV_FETCH_ASSOC)){
echo "<option value='". $row['Name']."'>".$row['Name']. '</option>';
}
echo "</select>";
?>
ID : <input type="text" name="cur_code" id="cur_code" ></p>
</form>
</body>
</html>
find_ccode.php
<?php
$country=$_REQUEST['country'];
include '../conn.php';
$sql = "SELECT ID,Name FROM Departments Name='$country'";
$fetched=sqlsrv_query($conn,$sql) ;
if( $fetched === false ) { die( print_r( sqlsrv_errors(), true ));}
while($sno=sqlsrv_fetch_array($fetched,SQLSRV_FETCH_ASSOC))
{
echo $formno=$sno['ID'];
}
}
?>
What I have
What I want :
The ID number of that particular department that is selected in the drop down should display in the text box. I have also attached an extract of what I am trying to do
But it doesn't seem to work. Where do you think I have gone wrong? Appreciate any help :)
FIDDLE
$('#sel').change(function() {
$('#qwe1').val($('#sel option:selected').val());
})
for dynamic value
FIDDLE
Use .change to select and get its value then put it to input box.
UPDATE
FIDDLE
var data = var data = [{
"id": "342-432-423-000","name": "name1"
}, {
"id": "342-432-423-001","name": "name2"
}, {
"id": "342-432-423-002","name": "name3"
}, {
"id": "342-432-423-003","name": "name4"
}, {
"id": "342-432-423-004","name": "name5"
}, {
"id": "342-432-423-005","name": "name6"
}, {
"id": "342-432-423-006","name": "name7"
}, {
"id": "342-432-423-007","name": "name8"
}]
for (var i = 0; i < data.length; i++) {
$('#sel').append('<option id=' + data[i].id + ' data-id="' + data[i].id + '">' + data[i].name + '</option>');
}
$('#sel').change(function () {
$('#qwe1').val($('#sel option:selected').data('id'));
})
Assuming I have the data from php I set the department name as option name and I set the department id asdata-id. Then from select change event i will get the value of data-id and set it as value of the input.

unable to pass variable to other page using ajax

I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>

Categories