I catch html from two files with javascript. In one of the files I include info to connect to my DB.
But when I do, php adds two " to my html. All files are saved with the encoding UTF8.
Index.php html
<div class="f-l" id="right-column"></div>
Javascript.js
$('#lead, #prospects').change(function() {
var kund_id = 'kund_id=' + $('#lead option:selected, #prospects option:selected').attr('value');
$.post(
'get_kund.php',
kund_id,
function(data){
$('#center-column').html(data)
});
$.post(
'get_kontaktperson.php',
kund_id,
function(data){
$('#right-column').html(data)
}); return false;
});
get_kontaktperson.php
include("db_connect.php");
$kund_id = $_POST['kund_id'];
$qry = "SELECT * FROM kontaktperson WHERE kund_id='$kund_id' ORDER BY id DESC";
$result=mysql_query($qry);
while($row=mysql_fetch_array($result)) {
echo 'some html'; }
db_connect.php
require_once('db_info_login.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: '
. mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die('Unable to select database');
}
mysql_query('SET NAMES utf8')
This adds "" above the html code from get_kontaktperson.php:
Why this seems to be a problem for me, the <div class="kontaktperson"> is missplaced by something. If I take away the include it will show the html content correct. But when I put in some data, this will occur. Margin on the right column...
Those two quotation marks are used by Chrome's web inspector to denote content inside the element. As there is no content, two quotation marks are shown without anything inside them.
Related
So I'm making a simple login/registration web application but I keep getting the following error:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
and
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
here is my login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
I've done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox
AHA! Got this today for a reason which will make me look pretty silly but which might one day help someone.
Having set up an Apache server on my machine, with PHP and so on... I got this error... and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed "file:///D:/apps/Apache24/htdocs/experiments/forms/index.html".
What you have to do to actually use the Apache server (assuming it's running, etc.) is go "http://localhost/experiments/forms/index.html" in the browser's address bar.
In mitigation I have up to now been using an "index.php" file and just changed to an "index.html" file. Bit of a gotcha, since with the former you are obliged to access it "properly" using localhost.
I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue
#PostMapping()
public void aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
}
To
#PostMapping()
public String aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
return "justReturn something";
}
Assuming you are working with javascript, you need to put a header in front of echoing your data:
header('Content-Type: application/json');
echo json_encode($response);
Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.
If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.
Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form class="modal-content animate" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
<button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
<button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
</div>
</form>
JavaScript
function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
url: 'makeUserEntry.php',
type: 'POST',
data: datasend,
success: function(response, status) {
if(response=="Username or Password did not match"){
alert("Username or Password did not match");
}
if(response=="Connection Failure"){
alert("Connection Failure");
}
else{
localStorage.userid = response;
window.location.href = "./maze.html"
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, php script returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
}); // end ajax call
}
PHP
<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];
//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
$userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$userID = $conn->query($userIDSQL);
echo json_encode($userID);
}
else{
echo json_encode("Username or Password did not match");
}
$conn->close();
?>
It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!
I have a MySQL database encoded with the default characterset UTF8. I have also a PHP code encoded with the same charset meta charset="UTF-8".
My connection to the database is configured to use UTF8 too
new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
But I have a problem when I use Ajax to get the content of a textbox and insert it into the database.
If I do not use special characters it works fine but when I use a quote or something everything stops working.
I tried to use UTF8_encode and UTF8_decode but nothing changed
EDIT
PHP
...
<meta charset="UTF-8">
...
<textarea class="commentBox" id="<?php echo $id_case;?>"></textarea>
<button class="saveComment" id="<?php echo $id_case;?>"> Save comment </button>
//id_case is different for each textarea
Javascript
$('.saveComment').click(function()
{
var idComment = this.id;
var content = $('#'+idComment+'.commentBox').val();
add_comment(idComment, content);
});
function add_comment(case_id, content)
{
$.post("../functions/ajax/add_comment.php",
{
id_case: case_id,
content: content
},
function(data,status)
{
alert("It worked !");
console.log("Function add_comment : "+status);
});
}
add_comment.php
<?php
if(isset($_POST['id_case'], $_POST['content']))
{
$case = $_POST['id_case'];
$content = $_POST['content'];
}
else
{
echo "Error during sending data to [add_comment.php]";
}
if($db != null)
{
try
{
$sql = ("UPDATE cases SET progress_remarks = '$content' WHERE id_cases = $case");
$result = $db->exec($sql);
echo $content;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
else echo "Erreur interne (fill_progress.php)";
?>
My database connection is done somewhere else but looks like this
$this->con = new PDO("mysql:host=" .$host. ";dbname=".$database,$username,$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
when I use a quote or something everything stops working.
It is unclear whether the problem is (1) just an escaping issue, or (2) also a utf8 issue.
Since PDO has a builtin way to take care of escaping, use it:
$sql = ("UPDATE cases SET progress_remarks = ? WHERE id_cases = $case");
$result = $db->exec($sql, $content);
This is probably the preferred way to set the charset with PDO: $db = new PDO('dblib:host=host;dbname=db;charset=UTF-8', $user, $pwd);
meta charset="UTF-8" refers to the tag in HTML, not PHP or MySQL.
SHOW CREATE TABLE -- Is the column in question declared CHARACTER SET utf8?
Although i have followed the sample code from http://api.jquery.com/jQuery.post/ and of course Stackoverflow i couldnt find a solution to my problem.
I have a toggle image in html which everytime a user clicks on it,changes the image and update the column in the DB.Here is the code:
HTML
<input type="image" src="smileys/heart.gif" class="play" onclick="toggle(this,'<?php echo $ida;?>')"/>
AJAX
function toggle(el,al){
if(el.className=="play")
{
el.src='smileys/lol.gif';
el.className="pause";
$.post("update.php", { "hr": 1, "ida": al } );
}
else if(el.className=="pause")
{
el.src='smileys/heart.gif';
el.className="play";
$.post("update.php", { "hr": 0, "ida": al } );
}
console.log(al);
return false;
}
update.php
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$heart=$_GET["hr"];
$ida=$_GET["ida"];
$con = mysql_connect($host,$user,$pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE tablename SET heart='$heart' WHERE id='$ida'");
?>
The toggle function works well but the DB is not updated when a user clicks and the image.
I believe it has to do with the $.post function,not sending correctly the data to the php.
BTW if i do
http://domain.com/update.php?hr=1&ida=127
it works.
NOTE: I am using mysql and not PDO only for this example.
...and yes my code is messy and ugly,still learning.
Any help?
Thanks
Well, it's a _POST request and not an _GET, so, to capture its values you need to use $_POST instead $_GET.
Also, as i noticed, there's and _GET link, so you need to change your $.post with $.get.
I want to return JSON data from a resulted SQL statement in a PHP script upon pressing Submit button, but I receive null instead.
I'll be using the returned JSON to filter-show markers on my Google Map, but for now I just want to get the data back across to my jQuery page from PHP script so I can manipulate/use it.
Submit button:
HTML
<input type="submit" id="filter" value="Filter" />
JS
$('#myform').on('submit', function(e) {
e.preventDefault();
var myData = $('#myform').serializeArray();
$.getJSON('myscript.php', myData, function(json){
alert(json);// actually filter for later
});
});
PHP script:
// action is a hidden form control I use to check if form was submitted
if(isset($_POST["action"])){
if(isset($_POST["color"]) && isset($_POST["zipcode"])){
// try to open a connection to a MySQL server
$connection = mysql_connect($host, $username, $password) or die("Could not connect" . mysql_error());
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection) or die("Can\'t use db:" . mysql_error());
$query = 'sql statement to return resutls based on what color and zipcode was provided';
$result = mysql_query($query) or die("Can\'t do that: " . mysql_error());
}
// close connection to the database
echo json_encode($result);
mysql_close($connection);
}
You can't return the result object of a mysql_query call directly. You first have to parse it with functions like mysql_fetch_array or alike (PHP docu).
...
$result = mysql_query($query);
if ( $result === false ) {
die("Can\'t do that: " . mysql_error());
}
$retVal = array();
while( $row = mysql_fetch_array( $result ) ) {
$retVal[] = $row;
}
...
echo json_encode( $retVal );
EDIT
According to the jQuery spec for getJSON (link), the data is sent using GET parameters and not using POST. So you would have to change all the $_POST appearances in your PHP code to either $_GET or $_REQUEST.
Besides this, you should return some error messages if your variables are not set. Right now (according to your code) just an empty document is returned.
Before the echo you should declare the returned content type:
header('Content-Type: application/json');
If you want to check for the receival of the data you can use:
$.ajax({
url: url,
data: myData,
success: function(json) {},
error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success)
});
I do have a code which shows number of data in database. I want to send this data to browser in real time or in between couple of seconds using ajax or any other method...
My code:
$db = mysql_connect($db_host, $db_username, $db_password) or die("Could not connect.");
mysql_select_db($databse_name,$db)or die(mysql_error());
$result = mysql_query("SELECT * FROM table")or die(mysql_error());
$num_rows = mysql_num_rows($result);
echo "$num_rows\n";
If you're using jQuery and that php code is in a file called your_code.php, you could do something like this:
$('#my_button').click(function() {
$.ajax({
url: "your_code.php",
success: function(data) {
$('#my_div').html(data);
}
});
}