The issue is that either the PHP file isn't sending the data back or the JS file isn't catching the data.
The exact issue is that the data isn't display on the index.php page inside the <div>.
I included code in the getDetails.php file to record what it was doing. It allows me to see that the query is running and data is being returned.
I have used similar code to this in the past without any problems. The only difference is that the previous code was working with MySQL. This code is dealing with an Access database. I don't know if I need to do anything special with the json_encode to deal with Access data.
I used an alert() at the beginning of java.js to make sure that the java code is being called. It is. An alert right after the details = result command never gets called.
INDEX.PHP:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="java.js" type="text/javascript"></script>
</head>
<body>
<div id="reportDetails" class="reportDetails" align=center></div>
</body>
<html>
JAVA.JS:
jQuery(document).ready(function () {
var ra='7100913063';
$.ajax({
type: 'POST',
url: 'getDetails.php',
data: 'value=' + ra,
dataType: 'json',
cache: false,
success: function(result) {
details = result;
$("#reportDetails").text("");
for (var i = 0; i < details.length; i++) {
$("#reportDetails").append("<tr class='bottom'><td width=200 align=center class='bottom'>" + details[i][0] + "</td><td width=200 align=center class='bottom'>" + details[i][1] + "</td><td width=200 align=center class='bottom'> " + details[i][2] +"</td></td><td width=200 align=center class='bottom'> " + details[i][3] +"</td></td></tr>");
}
$("#reportDetails").append("</table>");
},
});
});
getDetails.php
<?php
include("../../scripts/adodb/adodb.inc.php");
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$ra = $_POST['value'];
set_time_limit(0);
date_default_timezone_set('America/Chicago');
$counter = 0;
$connect = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=//server/directory/database.mdb", '', '');
$query = "SELECT distinct ra, MIN(received) as startDate, MAX(completion) AS stopDate, MAX(status) as stat FROM cont WHERE ra = '" . $ra . "' GROUP BY ra";
$result = odbc_exec($connect,$query);
while(odbc_fetch_row($result)){
$radetails[0] = odbc_result($result,"ra");
fwrite($fh, $radetails[0]);
$radetails[1] = odbc_result($result,"startDate");
fwrite($fh, $radetails[1]);
$radetails[2] = odbc_result($result,"stopDate");
fwrite($fh, $radetails[2]);
$radetails[3] = odbc_result($result,"stat");
fwrite($fh, $radetails[3]);
}
fclose($fh);
echo json_encode($radetails);
?>
I had the line "echo <br/>" in my getDetails.php. Removed that line and it works now.
Related
I am creating a php file to alter file systems and I want to make this php run in the background on a ubuntu server. The html creates a webpage but the php does not trigger at all.
I followed a youtube video to this point but I need to pass both new and old string to the php in the Data part of my query which I am unsure how to do.
HTML code
<html>
<head>
<meta charset ='utf-8'/>
<title> JQuery test </title>
<script src= "https://ajax.googleapis.cpm/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<td>Please type in the old string</td>
<input id= 'Old_String' />
<td>Please type in the new string</td>
<input id= 'New_String' />
<script>
$(document).ready(function() {
$('#New_String').change(function(){
$.ajax({
type: 'GET',
url: 'replace.php',
data: 'Old_String='+$('#Old_String').val(),
success : function(msg){
$('#results').html(msg);
}
})
});
});
</script>
<table border="0">
<div id="results' ></div>
</body>
My php code
<?php
$valid = true;
if (!empty($_GET["Old_string"])) {
$Old_string = $_GET["Old_string"];
} else {
$valid = false;
echo "Old string is Empty . Please Enter value to proceed\n";
}
if (!empty($_GET["New_string"])) {
$New_string = $_GET["New_string"];
} else {
$valid = false;
echo "New string is Empty . Please Enter value to proceed\n";
}
if ($valid) {
echo "all input correct\n";
$myfile = fopen("word.txt", "r+") or die("Unable to open file!");
if (flock($myfile, LOCK_EX)) {
$text = fread($myfile, filesize("word.txt"));
$count = 0;
$newstring = str_ireplace($Old_string, $New_string, $text, $count);
file_put_contents("word.txt", $newstring);
echo "Number of changes made = " . $count;
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
fclose($myfile);
}
?>
}
For some reason my PHP does not fire at all and no output is shown in the div results. Am I passing the values incorrectly or am I not quite doing this right? Please any suggestion would be appreciated. I am also trying to switch the event so that it triggers on a button click if you could show me how to do that I would very much appreciate it.
You had multiple errors.
These languages are case sensitive. You had different cases for the varables all over the place. So I made everything lowercase.
You can't mix the quotes. So when you start with a ' you need to end with a '.
You may need to create the word.txt file manually. The web server normally does not have permissions to create files in the web root dir.
The browser does not pay attention to new lines "\n" you need to use
Added some error reporting on the top.
index.php
<html>
<body
<head>
<meta charset ='utf-8'/>
<title> JQuery test </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<table border="0">
<tr>
<td>Old String</td>
<td align="center"><input type="text" name="old_string" size="30" id="old_string" /></td>
</tr>
<tr>
<td>New String</td>
<td align="center"><input type="text" name="new_string" size="30" id="new_string" /></td>
</tr>
<div id="results" ></div>
</table>
</form>
<script>
$(document).ready(function() {
$('#new_string').change(function(){
$.ajax({
type: 'GET',
url: 'replace.php',
data: 'old_string='+$('#old_string').val()+'&new_string='+$('#new_string').val(),
success : function(msg){
$('#results').html(msg);
}
})
});
});
</script>
</body>
</html>
replace.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$valid = true;
if (!empty($_GET['old_string']) and isset($_GET['old_string'])) {
$old_string = $_GET['old_string'];
} else {
$valid = false;
echo 'Old string is Empty . Please Enter value to proceed<br>';
}
if (!empty($_GET['new_string']) and isset($_GET['new_string'])) {
$new_string = $_GET['new_string'];
} else {
$valid = false;
echo 'New string is Empty . Please Enter value to proceed<br>';
}
if ($valid) {
echo 'all input correct<br>';
$myfile = fopen('word.txt', 'r+') or die('Unable to open file!<br>');
if (flock($myfile, LOCK_EX)) {
if(filesize('word.txt')>0){
$text = fread($myfile, filesize('word.txt'));
} else {
$text = '';
}
$count = 0;
$newstring = str_ireplace($old_string, $new_string, $text, $count);
ftruncate($myfile,0);
fwrite($myfile,$newstring,strlen($newstring));
echo "Number of changes made = $count<br>";
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print 'Could not lock $filename!<br>';
}
fclose($myfile);
}
You're referencing $_GET["Old_string"] in your PHP code but passing it by query string parameter under the Old_String key in this line.
data: 'Old_String='+$('#Old_String').val(),
use case consistently, either Old_string or Old_String in both places.
To pass both values, I'd use a simple json object instead of building a query string manually.
data: { 'Old_String': $('Old_String').val(), 'New_String': $('New_String').val() }
i have simple code in which i get the content of a file and whant to save it in browser
local Db in HTML5
here the code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 100 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log, content LONGBLOB not null)');
<?php
$sql1 = "INSERT INTO LOGS(id, log,content)
VALUES('5','abc','" . mysql_escape_string(file_get_contents("43.mp3")) . "')";
?>
var v= "<?php echo $sql1;?>";
console.log(v);
tx.executeSql(v);
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML = msg;
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++){
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
});
</script>
</head>
<body>
<div id="status" name="status">No Data </div>
</body>
</html>
it not insert record i think file_get_content()
return the content list but not a proper string format
console.log(v); point out illegal synex
You're using mysql_escape_string() to escape for Javascript Database API. That escape is not safe for Javascript to call as a string.
Instead, I think you should use base64_encode in PHP to encode the mp3 binary. For example:
<?php
$sql1 = "INSERT INTO LOGS(id, log,content)
VALUES('5','abc','" .
base64_encode(file_get_contents("43.mp3")) . "')";
?>
String in base64 format should be save for Javascript, include Database API and console.log(v). You should then load the mp3 data with Audio API's readAsDataURL() and play it.
If I embed my XHR file into my HTML document directly, everything works fine. As soon as I src it via
<script type="text/javascript" src="js/ajax_gallery.js">ajax_json_gallery('gallery');</script>
Nothing works, and I get no errors. I'm assuming it's something to do with the XHR being created in a separate file to the HTML. I just don't like XHR script cluttering up my HTML, I just want to load as an external JS file.
I've moved my main 3 scripts, galleryHandle.php, XHR.js, ajax_gallery.html all to the same dir level to keep things simple. And the gallery images are in a folder called "gallery", also on the same level.
Here's my code:
HTML
<html>
<head>
<title>Test</title>
<link rel="stylesheet" type="text/css" href="css/gallery.css" />
</head>
<body>
<div id="pagetop"></div>
<div id="thumbnailbox"></div>
<div id="pictureframe"></div>
<script type="text/javascript" src="XHR.js">ajax_json_gallery('gallery');</script>
</body>
</html>
JavaScript
function ajax_json_gallery(folder) {
"use strict";
var httpRequest = new XMLHttpRequest();
document.getElementById("pagetop").innerHTML = "dynamic ajax json gallery";
var thumbnailbox = document.getElementById("thumbnailbox");
httpRequest.open("POST", "galleryHandle.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
var pictureframe;
pictureframe.innerHTML = "<img src='"+data.img1.src+"'>";
thumbnailbox.innerHTML = "";
for (var obj in data) {
if (data[obj].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+data[obj].src+'\')"><img src="'+data[obj].src+'"></div>';
}
}
}
};
httpRequest.send("folder="+folder);
thumbnailbox.innerHTML = "Loading...";
}
function putinframe(src) {
"use strict";
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src = " '+src+' " >';
}
PHP
<?php
header("Content-Type: application/json");
//bring in folder name
$folder = $_POST["folder"];
//start componding json
$jsonData = '{';
//compound directory path
$dir = $folder."/";
//open directory
$dirHandle = opendir($dir);
//init while looop
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && strpos($file, '.jpg')){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
I understand there are some redundancies in my code but it's just a tutorial I'm going through to learn the basics of JSON building with POST, XHR.
Anyway, help appreciated as always.
Thanks
Explanation
FROM W3C:
<script type="text/javascript" src="myscript.js">
alert('I am pointless as I won\'t be executed');
</script>
Upon meeting this element in a page, browsers will then load the file myscript.js and execute it. Any content inside the script element itself will be skipped when you provide a src attribute. The [last] example will load the file myscript.js and execute the code in it but will not execute the alert inside the script element at all.
Solution
Try the following in your head tags:
HTML
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">
ajax_json_gallery('gallery');
</script>
<script type="text/javascript" src="XHR.js">
You can't have src attribute and javascript both in a single tag. Separate them out. Like this...
<script type="text/javascript" src="XHR.js"></script>
<script type="text/javascript">ajax_json_gallery('gallery');</script>
I am trying to save json data to a file using AJAX and PHP but the resulting file is empty. Why is it not working?
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
var dataset = {"value1": 2, "value2": 1000};
$.ajax({
url: 'save.php',
type: 'POST',
data: dataset,
success: function() {
alert('Success');
}
});
</script>
</body>
</html>
save.php:
<?php
$map=json_decode($_POST['json_string']);
$file = "test.json";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $map);
fclose($fh);
?>
You're using wrong POST variable name. Firstly, send your AJAX request with:
data: {
json: dataset
},
And then use:
$map = $_POST['json'];
Don't decode it since you want to save JSON string, not an array. If you want PHP representation, better use var_export():
$map = var_export(json_decode($_POST['json'], true), true);
change this line $map=json_decode($_POST['json_string']); to $map=json_decode($_POST['dataset']);
I have a problem with some JSON data. I don't know how to take some data generated in PHP and turn that into something that I can use in my jQuery script. The functionality I need is this: I need to be able to click on images on the page, and depending on the selected element, I need to show results from my DB.
Here's the HTML page that I've got:
<html>
<head>
<title>pippo</title>
<script><!-- Link to the JS snippet below --></script>
</head>
<body>
Contact List:
<ul>
<li><a href="#">
<img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
</a></li>
<li><a href="#">
<img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
</a></li>
<li><a href="#">
<img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
</a></li>
</ul>
</body>
</html>
Here's PHP code being called:
<?php
include('../dll/config.php');
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$_POST['name'] = ucfirst($row['name']);
$_POST['tel'] = $row['telephone'];
$_POST['companymail'] = $row['companymail'];
$_POST['mail'] = $row['email'];
$_POST['fbid'] = $row['facebook'];
}
?>
Here's the Ajax JavaScript code I'm using:
<script type="text/javascript">
function change(user) {
$.ajax({
type: "POST",
url: "chgcontact.php",
data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
success: function(name,tel,companymail,mail,fbid){
alert(name);
}
});
return "";
}
</script>
Someone told me that this JS snippet would do what I want:
$.getJSON('chgcontact.php', function(user) {
var items = [name,surname,tel,companymail,email,facebook];
$.each(user, function(surname) {
items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
});
/*
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
*/
});
But it is not clear to me - I don't understand how I need to use it or where I should include it in my code.
You will have to create a proper JSON string in your PHP script, and then echo that string at the end of the script.
A simple example:
$person = new stdClass;
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
$person->name = ucfirst($row['name']);
$person->tel = $row['telephone'];
$person->companymail = $row['companymail'];
$person->mail = $row['email'];
$person->fbid = $row['facebook'];
}
echo json_encode($person);
There are several problems with your code I have tried to explain via the corrected and commented code here:
HTML & JavaScript
<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
$.ajax({
type: "POST",
url: "chgcontact.php",
// use javascript object instead of `get` string to represent data
data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
success: function(data){
// removed name,tel,companymail,mail,fbid
alert(JSON.parse(data));
}
});
return "";
}
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</li>
<li><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</li>
<li><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</li>
</ul>
</body>
</html>
PHP
<?php
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )){
// create data object
$data = new stdClass();
// add values to data object
$data->name = ucfirst($row['name']);
$data->tel = $row['telephone'];
$data->companymail = $row['companymail'];
$data->mail = $row['email'];
$data->fbid = $row['facebook'];
// send header to ensure correct mime type
header("content-type: text/json");
// echo the json encoded data
echo json_encode($data);
}
?>
All code is untested, but you should be able to see what I have done at each step. Good luck.
And to expand on Brian Driscoll's answer. You will need to use the user.name format to access the name field from the returned $.getJSON("blah", function(user){});
so...
items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);
In this format that you have created it will just push a long ugly looking string so you might want to spend some time making it look better. Good luck!
JSON that is POSTed to a PHP page generally isn't in the $_POST variable, rather it is in $HTTP_RAW_POST_DATA.