I have a php file which has svg embedded in php variable. Using an onclick event on the svg elements displayed (lines with ID's) I want to change the colour of the SVG element and then send a parameter to a mysql table to return the x and y coords etc of other lines which join my selected line.
This part unto sending the parameter to mysql table works fine using ajax in my javascript function:
<!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>
<meta http-equiv="Content-Type" content="application/json" />
<title>Enter Exercises</title>
</head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
<script type="text/javascript">
function GetPathways(elt)
{
document.getElementById(elt.id).style.stroke = "blue";
var test=elt.id;
var test = document.getElementById(elt.id);
test.setAttribute("x2", "550");
test.setAttribute("y2", "450");
document.getElementById(elt.id).style.visibility = "visible";
var exid = parseInt(elt.id);
$.ajax(
{
type: "POST",
url: 'GetPathways.php',
data: {id: exid},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(message)
{
alert (message);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert("Error code is....:"+xhr.status);
}
});
};
</script>
Ajax calls php file which executes the sql required to return the table rows (multiple). I have tested the query in my phpAdmin and it works fine retrieving some appropriate rows of data.
Ajax script however only executes error function and not the success function.
The success function will eventually use the ID of the returned svg element to be displayed ie update the webpage based on the onclick event. Seems like a good use of ajax to refresh page without reloading.
GetPathways.php
<!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>
<meta http-equiv="Content-Type" content="application/json" />
<title>Get Pathways</title>
</head>
<body>
<?php
//echo "Hello from processing file GetPathways.php"."<br>";
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id";
mysql_query($query);
mysql_close($conn);
?>
</body>
</html>
Error code is 200
You have to echo the data inorder to get response from ajax call and also you did not execute the query. change the GetPathways.php as follows
<?
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id LIMIT 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
mysql_close($conn);
print_r($value);
?>
Related
This question already has answers here:
Download CSV file using "AJAX"
(6 answers)
Closed 3 years ago.
I have the following problem:
I'm upgrading a working system, so I have to create code that fits in.
I want to create a csv file on a php page and a mysql database. I'm also using Ajax to stay on the same page while running other php-Files. Here are the Code snippets:
PHP/HTML-Page with Button
<div class="btn" id="export">Export</div>
Javascript Ajax
$("#export").click(function() {exportInfos();});
function exportInfos() {
$.ajax({
type: "POST",
url: "functions/exportInfos.php",
data: { searchterm: $("#search").val(), filterbycat: $("#filterbycat").val(), filterbytype: $("#filterbytype").val()},
success: function(response){
console.log("success_export");
},
});
}
PHP-File to create csv(exportInfos.php):
<?php
include ('../../config.php');
$searchterm = $_POST["searchterm"];
$filterbycat = $_POST["filterbycat"];
$filterbytype = $_POST["filterbytype"];
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv');
$output = fopen("php://output", "w");
$query = "SELECT * FROM database";
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($output, $row);
}
fclose($output);
?>
I'm not sure where the Problem is but in the console I only see that the php script is called and the success_export text from the log, but no file is opened or downloadable. I think the problem could be with the AJAX part because thats the part Im not sure about the most.
The data values in the Ajax part are there to edit the query as soon as i get some output File.
$mysqli is the connection defined in the config file.
I think you need the change download methodology. Maybe it can be as follows.
Static Page :
<!doctype html>
<html lang="en">
<body>
<div class="btn" id="export">Export</div>
</body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('#export').click(function() {exportInfos();});
function exportInfos() {
$.ajax({
type: 'POST',
url: 'functions/createCSV.php',
data: {
searchterm: $('#search').val(),
filterbycat: $('#filterbycat').val(),
filterbytype: $('#filterbytype').val(),
},
success: function(response) {
if (response.filename != undefined && response.filename.length > 0) {
window.open('functions/downloadCSV.php?filename='+response.filename);
}
},
});
}
</script>
</html>
createCSV :
<?php
include('../../config.php');
$searchterm = $_POST["searchterm"];
$filterbycat = $_POST["filterbycat"];
$filterbytype = $_POST["filterbytype"];
//header('Content-Type: text/csv');
//header('Content-Disposition: attachment; filename=export.csv');
$outputPath = '/path/to/save/outputFile.csv';
$output = fopen($outputPath, "w");
$query = "SELECT * FROM database";
$result = mysqli_query($mysqli, $query);
while ($row = mysqli_fetch_assoc($result)) {
fputcsv($output, $row);
}
fclose($output);
header('Content-Type: application/json');
echo json_encode(
[
"filename" => basename($outputPath),
]
);
downloadCSV :
<?php
if (!empty($_GET['filename'])) {
http_send_status(404);
}
$filepath = "/path/to/save/" . $_GET['filename'];
if (!is_file($filepath) || !is_readable($filepath)) {
http_send_status(404);
}
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=" . $_GET['filename']);
echo file_get_contents($filepath);
This is my page and I want to pass my php variable witch is number from my sql database to html script function. If i replace values with anything it ruin everything. If I fetch data from input it works fine. Sql part work and I can display data through php echo but i cant pass it to html script function.
I use template chart to display my data from mysql on my webpage. All i need to do is pass my php values (that part works) to .myfunc on the bottom. In other words I need to change myValues, and myValues2 with my php values (that part i didnt figure up)
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'esp8266_baza'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT vrijeme_unosa, temp, hum from temp_hum where p_key = (SELECT MAX(`p_key`) FROM `temp_hum`)';
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$ptemp = $row['temp'];
$phum = $row['hum'];
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<html>
<head>
<link href="css/meter.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br>
<?php echo $ptemp;
echo $phum; ?>
<br>
<input id="myValues" />
<br>
<input id="myValues2" />
</body>
<script src="js/jquery.js"></script>
<script src="js/temp.js"></script>
<script type="text/javascript">
$("#myValues").myfunc({divFact:2,eventListenerType:'keyup'});
$("#myValues2").myfunc({divFact:2,eventListenerType:'keyup'});
</script>
</html>
Why not do everything in php echo? That way you can use all variables.
echo "
<script>
$jsvar = $row[varhere]
</script>
";
I have troubles with JQuery and Ajax forms. I'm new in Ajax and Jquery. I'm creating a webapp with a search form. The data I'm fetching from MYSQL Database. So I have a request page with a form, then the mysql processing file, a javascript to return the requested data and a html file, where the results are displayed. So, my problem is, that I can't display the results under index.html. Therefore I tried to action directly to landmarks.php and there I can see the reuslts in array like this
([{"id":"1","name":"Big Ben","latitude":"51.500600000000","longitude":"-0.124610000000"}]);
The request.html file
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form method="post" action="landmarks.php">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<label for="l_name"><b>Name</b></label>
<input type="text" name="l_name" id="l_name" value="" />
<input class="submit" type="submit" value="Submit" />
</fieldset>
</div>
</form>
</body>
Then this file for mysql
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "test";
$password = "test132";
$database = "landmarks";
$l_name = $_POST["l_name"];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks WHERE l_name like '".$l_name."' ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
my json callback looks like this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.')
}
});
});
and finally my final page, where the results should be displayed
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/load-json.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>
When I echo $jsonstring, seemingly a whole blank html page is sent over (from PHP to Javascript) with the object I requested. Super new all around here, so I don't get why.
my php code:
<?php
//ini_set('display_errors', '1');
//ini_set('error_reporting', E_ALL);
require "localdbcxn.php";
$encoded = file_get_contents('php://input');
$decoded = json_decode($encoded, true);
$email = $decoded['email'];
$password = $decoded['password'];
$identify = mysql_query("SELECT UserId FROM users WHERE UserEmail='$email' AND UserPassword='$password'");
$numrows = mysql_num_rows($identify);
$row = mysql_fetch_assoc($identify);
$userid = $row['UserId'];
$sessionid = mt_rand(1111111111111111,9999999999999999);
$sessionkey = mt_rand(1111111111111111,9999999999999999);
$logindate = date("Y-m-d H:i:s");
$login = "INSERT INTO mobileSession (UserId, SessionId, SessionKey, BeginDate) VALUES('$userid','$sessionid','$sessionkey','$logindate') ON DUPLICATE KEY UPDATE SessionId='$sessionid', SessionKey='$sessionkey', BeginDate='$logindate' ";
if ($numrows == 1) {
mysql_query($login);
$session = array('UserId'=>$userid,'SessionId'=>$sessionid);
$jsonstring = json_encode($session);
echo $jsonstring;
}
?>
Here's what the console(log) shows:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>{"UserId":"33","SessionId":8207219793564744}
From UserID til ...4744 is correct, but can anyone help me understand why the html code is being echoed? In my limited experience, I haven't seen this before, and feel that I am doing something wrong.
Thanks!
you must specify the content type before printing json data. before echo set header -
header('Content-type: application/json');
Im trying to read data from mysql database and pass it to my javascript file.
I have search alot on internet and have found examples that doesnt work in my case.
.html file
<!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'>
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>Get Data.</button>
<div id='result_table'>
</div>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('#getdata').click(function(){
alert("hello");
$.ajax({
url: 'db.php',
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
and .php file
<?php
echo 'hello';
$user = 'root';
$pass = '123';
$host = 'localhost';
$db = 'internetProgrammeringProj';
$connect = mysql_connect($host,$user,$pass);
$select = mysql_select_db($db,$connect);
$query = $_POST['query'];
$mysql_query = mysql_query("SELECT * FROM ratt ");
$temp = "";
$i = 0;
while($row = mysql_fletch_assoc($mysql_query)){
$temp = $row['id'];
$temp .= $row['namn'];
$temp .= $row['typ'];
$temp .= $row['url'];
$temp .= $row['forberedelse'];
$array[i] = $temp;
$i++;
}
echo json_encode($array);
?>
alert(xhr.statusText); gives parsererror
and
alert(thrownError); gives SyntaxError: JSON.parse: unexpected character
firebug doesnt display any error in console.
QUESTION: How do i get my program to get the content from the database and pass it with json to display it with alert in ajax?
I just successfully ran this code.
All I had to do is remove the echo "hello" at the beginning which messes up your JSON.
Some more tips you can use for future development:
Don't use alert('message'). Use console.log('message'). You can view the output of console.log in "Developer's Area". In chrome you simply press F12. I think that in FF you need to install firebug or something.
output_string in function success is actually an object.
The "Developer's Area" in chrome also lets you see the response from backend. If you have used it you could have seen your output is hello{ "key":"value"} and immediately notice the nasty hello in the beginning. Read more about it at http://wiki.mograbi.info/developers-tools-for-web-development