SOLUTION: After a teamviewer session with #skobaljic he figured out that I was not actually opening the html in localhost but using the file system (as in file://...). I apologize for wasting everyone's time like that.
I am trying to send some php arrays through Ajax and print them out and despite getting a 200 OK response, there is no actual effect in the received html. The status text says "parsererror".
The files are the following:
<!DOCTYPE html>
<html>
<head>
<title>Page Title Woo!</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js'></script>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph.</p>
<ul></ul>
<script type='text/javascript'>
$(document).ready(function(){
$.getJSON('DbGetter.php', function(data) {
console.log(data);
$.each(data, function(key, array) {
$('ul').append('<li id="' + key + '">'
+ array.longitude + ' '
+ array.latitude + '</li>');
});
})
.fail(function(error) {
console.log(error);
});
});
</script>
</body>
</html>
and the php:
<?php
$servername = "localhost";
$username = "testuser";
$password = "password";
$dbname = "Locations";
header('Content-Type: application/json');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM places";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//declare associative array
$array = array();
$num = 0;
// output data of each row
while($row = $result->fetch_assoc()) {
//store them in an array
$place = array(
'id' => $row["id"],
'latitude'=> $row["latitude"] ,
'longitude'=> $row["longitude"],
'place_name' => $row["place_name"],
'country_code'=> $row["country_code"],
'postal_code'=> $row["postal_code"]);
/*
echo "Coordinates: " . $row["latitude"]. " " . $row["longitude"]. " - Name: " . $row["place_name"]. " " . "<br>";
*/
//building the second associative array
$array[$num] = $place;
$num += 1;
}
echo json_encode($array);
} else {
echo json_encode("0 results");
}
$conn->close();
?>
I've tried looking at the value through firebug, but either I'm blind or it's just not stored anywhere in the DOM. I'm pretty new to web application in general so I don't know how to go about debugging it.
Running the php by itself I get: [{"id":"1","latitude":"57.0502","longitude":"9.9173","place_name":"1000fryd","country_code":"DK","postal_code":"9000"},{"id":"2","latitude":"58.0502","longitude":"10.9173","place_name":"same_place","country_code":"DK","postal_code":"9000"}]
Which are the 2 rows I expect.
There is also no XHR request marked by Firebug.
You're not encoding valid JSON here.. This will give you a "parseerror" if you try using JQuery's $getJSON with it. Notice the JQuery Ajax Source from lines 275-281.
echo json_encode("0 results");
You could probably change it to something like:
echo json_encode(["0 results"]);
You are using $.getJSON method, so the data is already parsed correctly. In case you do not get the JSON it would trigger fail.
So, just remove:
try { JSON.parse(data); } catch (e) { console.log('Not JSon') }
Related
I am calling a php file, into my HTML document using AJAX, and it is working too. The problem is that, there are few script tags in that PHP files, which works just fine if the PHP files is viewed individually. But when I call it using AJAX, those scripts are not functioning.
I am attaching my PHP code, and the screenshots below.
trial.php
<script>
document.getElementById("response1").onload = function() {
document.body.style.backgroundColor = "#ffa31a";
}
</script>
<h1 class="restitle"> Responses</h1>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "portfolio";
$conn = mysqli_connect( $servername, $username, $password, $dbname );
if ( !$conn ) {
die( "Connection failed: " . mysqli_connect_error() );
}
$sql = "SELECT NAME, EMAIL, MESSAGE, TIME FROM Feedback ORDER BY TIME";
$result=$conn->query( $sql );
if ( $result == TRUE ) {
$i=0;
?>
<script>
var n = 1;
</script>
<?php
while ($row = $result -> fetch_row()) {
$i = $i+1;
echo "<div class='response' id='response$i'><h1 class='responsetitle' id='responsetitle$i'><i class='fa fa-user' aria-hidden='true'></i> " . $row[0]. " <span class='responseemail' id='responseemail$i'> (". $row[1] .")</h1><hr class='responseline'><p class='responsetxt' id='responsetxt$i'>\"" . $row[2] . "\"</p><br /><div class='responsetimecontain'><span class='responsetime'>- " . $row[3] . "</span></div></div>";
echo "<div id='valuepipe$i' style='display:none;'>" . $i . "</div>";
?>
<script>
var i = document.getElementById("valuepipe" + n).textContent;
if (i % 2 == 0) {
document.getElementById("response" + n).style.backgroundColor = "#ffa31a";
document.getElementById("responseemail" + n).style.color = "#f2f2f2";
document.getElementById("responseemail" + n).style.opacity = "0.6";
document.getElementById("responsetitle" + n).childNodes[0].style.color = "#f2f2f2";
document.getElementById("responsetxt" + n).style.color = "#f2f2f2";
}
n++;
</script>
<?php
}
$result -> free_result();
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close( $conn );
?>
When this file is viewed individually:
But when I call it using AJAX:
<script>
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("main2").innerHTML = this.responseText;
}
xhttp.open("GET", "trial.php");
xhttp.send();
</script>
I get the following view :
Somehow all the script tags are being ignored or something. Need a solution. Any help would be appreciated.
Note: The other styles are implemented in my CSS file, so they are visible. Only the Scripts are not working
From the MDN reference
HTML5 specifies that a <script> tag inserted with innerHTML should not execute.
You'll need to separate the scripts from the HTML content and either include them as part of the code that loads the content, or place them in their own script file that is loaded separately.
So I am trying to reach into a MySQL table and draw out a value. I have the following PHP that does so:
<!DOCTYPE html>
<html>
<body>
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','PRIVATE','PRIVATE','PRIVATE');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?></body>
</html>
I've put PRIVATE where the database ID and password go for security reasons. Essentially, this PHP takes the value out of the 'wealth' column in according to the logged on user. I have this AJAX function that triggers this PHP (the ajax is located inside of the document I would like to send the PHP variable to). Note that this function sends the username of the current logged on user and their 'score' (the var clicks) to the PHP.
function sendScore() {
$.post("sendScore.php",{username:localStorage.getItem('userName'),wealth:clicks},function(response){
console.log("The service replied"+response);
});
}
Now, I know the value I retrieved is equal to the PHP variable $wealth. I also understand that PHP is server based and Javascript/html are client based, so you can't simply reach into another document and find the value of the variable. I'd like to assign the value of $wealth to a javascript variable named: userWealth
Thanks for reading!
EDIT: I WROTE THE Q WRONG ...
#Ilan Kleiman Small problem... I have two separate PHP files, sendScore and getScore. I had mistakenly pasted the wrong ones in the question. So, I have the sendScore AJAX which you can see in the question, but this triggers a different PHP code which isn't shown above, which essentially writes into the 'wealth' column. I have a separate piece of PHP, shown above, which is used to RETRIEVE written info from the wealth column (like how cookie clicker saves the number of clicks you have when you close the tab, this code activates when you open the website back up again, and it loads the last written value in 'wealth'). I am looking into how to create a piece of AJAX that can turn the $wealth PHP variable generated by the code into a javascript variable. Sorry for the confusion.
EDIT #2: CODE
AJAX FOR SENDSCORE
$.post("sendScore.php",{username:localStorage.getItem('userName'),wealth:clicks},function(response){
console.log("The service replied"+response);
});
PHP FOR SENDSCORE
<!DOCTYPE html>
<html>
<body>
<?php
$username = strval($_POST['username']);
$wealth = strval($_POST['wealth']);
$con = mysqli_connect('localhost','PRIV','PRIV','PRIV');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql = "UPDATE users SET wealth=".$wealth." WHERE username='".$username."'";
$result = mysqli_query($con,$sql);
}
mysqli_close($con);
?></body>
</html>
AJAX FOR GETSCORE IS WHAT I AM TRYING TO FIND
PHP FOR GETSCORE
<!DOCTYPE html>
<html>
<body>
<?php
$username = strval($_GET['userName']);
$con = mysqli_connect('localhost','PRIV','PRIV','PRIV');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
} else {
$sql="SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$wealth = $row['wealth'];
echo $wealth;
}
}
mysqli_close($con);
//return $wealth;
?></body>
</html>
In your PHP file:
change
echo $wealth;
to
echo "<div id='wealth'>" . $wealth . "</div>";
AJAX Request:
var userWealth;
function getScore() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
userWealth = document.getElementById("wealth").innerHTML;
alert(userWealth);
}
};
xhttp.open("GET", "getScore.php", true);
xhttp.send();
}
This will set "userWealth" to $wealth from the PHP.
Keep in mind, the Javascript should be on the same "server/website" as the PHP otherwise the AJAX request won't work.
I'm trying to figure out how do I send a javascript array of x,y coordinates to a Mysql database? I don't have any forms or anything.
I'm very new the mysql so I basically know how to connect using this:
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
but I don't know how to connect that to the javascript. I know it has something to do with this code
jQuery.post(url, data);
Any help would be really appreciated!
I've put together this little one-page demo. Having a look at it might help you understand how it works.
To make it work, you need to put it on a server (no way!), and to have a table with x and y fields. Then, replace database credentials with your own.
References
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://api.jquery.com/jquery.ajax/
Live demo
http://shrt.tf/coordinates
Note
This one does not check for types (you can input any String), but you can add that.
test.php
<?php
// Replace these parameters to match your database
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'mydatabase';
$table = 'coordinatesTable';
// Connect
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
// If parameters are received
if(isset($_POST['x']) && isset($_POST['y'])){
$error_messages = array();
if ($mysqli->connect_errno) {
$error_messages[] = "Couldn't connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Prepare insert
if (!($stmt = $mysqli->prepare("INSERT INTO `$table` (x,y) VALUES (?,?)"))) {
$error_messages[] = "Couldn't prepare statement: (" . $mysqli->errno . ") " . $mysqli->error;
}
// Bind parameters x and y
if (!$stmt->bind_param("dd", $_POST['x'], $_POST['y'])) {
$error_messages[] = "Couldn't bind parameters: (" . $stmt->errno . ") " . $stmt->error;
}
// Execute the insert
if (!$stmt->execute()) {
$error_messages[] = "Couldn't execute the query: (" . $stmt->errno . ") " . $stmt->error;
}
// Prepare some data to return to the client (browser)
$result = array(
'success' => count($error_messages) == 0,
'messages' => $error_messages
);
$stmt->close();
// Send it
echo json_encode($result);
// Exit (do not execute the code below this line)
exit();
} // end if
// Fetch all the coordinates to display them in the page
$res = $mysqli->query("SELECT x,y FROM `$table`");
$rows = array();
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
$mysqli->close();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test page</title>
<style>
table{ border-collapse: collapse; }
th,td{ border: 1px solid #888; padding: .3em 2em; }
</style>
</head>
<body>
<h1>New coordinates</h1>
<p>
x: <input type="text" id="x">
y: <input type="text" id="y">
<button id="addBtn">Add</button>
</p>
<table id="coordinates">
<tr>
<th>x</th>
<th>y</th>
</tr>
<?php
if(count($rows)){
foreach($rows as $row){
?>
<tr>
<td><?=$row['x']?></td>
<td><?=$row['y']?></td>
</tr>
<?php
}
}
?>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function(){
$('#addBtn').click(postCoordinates);
function postCoordinates(){
var x = $('#x').val(),
y = $('#y').val();
if(x.length && y.length){
// Change this if it is on a different page
var url = window.location.href;
$.ajax({
'url': url,
'method': 'post',
'data': {'x': x, 'y': y},
'dataType': 'json', // The server will return json
'success': function(res){
if(res.hasOwnProperty('success') && res.success){
$('#x, #y').val(''); // Empty the inputs
$('#coordinates').append('<tr><td>'+x+'</td><td>'+y+'</td></tr>');
} else if(res.hasOwnProperty('messages')) {
alert( res.messages.join('\n') );
}
},
'error': function(x, s, e){
alert( 'Error\n' + s + '\n' + e );
}
});
} else {
alert('You need to provide x and y coordinates');
}
}
});
</script>
</body>
</html>
Search for ajax. Send the data from client side to server side:
For example:
$('selector').on('click', function(){
var coordinates = [x,y];
$.ajax({
method: 'POST',
url: 'yourURL',
data: {coordinates: coordinates},
success: function(response){
Console.log(response);
}
});
});
In PHP:
$coor = $_POST['coordinates'];
echo $coor;
//Search the manual of php for storing it in the database
NOTE: Don't use mysql because it is deprecated, use mysqli or PDO.
I'm querying a set of data from MySQL on a hosted server. When I did it on my local machine, it worked fine, but on the hosted server, it's not returning anything. The weird thing is, when I use this GUI for the hosted environment to run the same query, it does return the results.
So here are some codes, etc.
This is index.php:
<?php
$servername = "username.db.theservername.ether.com";
$mysqllogin = "username";
$mysqlpassword = "thepassword";
$dbName = "StepsMath";
$conn = new mysqli($servername, $mysqllogin, $mysqlpassword, $dbName);
if($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
echo "connection failed.";
}
$set_name = 'test_set';
$query = "select word, definition from word_list where set_name = '$set_name'";
$result = $conn->query($query);
$conn->close();
// *********************************************
echo $query; // <-------- *******this prints the query*******
// *********************************************
$result = mysqli_fetch_array($result);
?>
<!DOCTYPE html>
<html lang="en"><head>
<title>this is a title</title>
<script type="text/javascript">
var json = '<?= json_encode($result) ?>';
var word_list = JSON.parse(json);
console.log(word_list); //line 24
console.log(json); //line 25
function getUserId(){
return '<?= $user_id ?>';
}
if(!getUserId()) window.location = 'login.html';
</script>
</head>
<body>body stuff</body>
</html>
Table word_list only has three columns: word, definition, and set_name
The above code is supposed to return rows of words and definitions. Instead, as I check in the browser console, it returns the following:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
This is the query that runs:
select word, definition from word_list where set_name = 'test_set'
If I copy that exact query and run it in the MySQL GUI in the hosted server,
the following is returned:
So to summarize the question, why is there a discrepancy in the result between the GUI and the code??
change this line:
$result = mysqli_fetch_array($result);
to this:
while ($row = mysqli_fetch_assoc($result)) {
$res[] = $row;
}
var_dump($res);
The information you previously got: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} are all mysqli_result properties.
Read this, it will help you uderstand what you did wrong:http://php.net/manual/en/class.mysqli-result.php
basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);