here's my code i am trying to fetch image from Data Base using ajax but its not working please hep me out . image uploading working properly when i am trying to fetch image using anchor tag but it show my image on another page . but i want on same page at window load time.
getImage.php
if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
{
$image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
try {
$dbh = new PDO("mysql:host=localhost;dbname=flipbook", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT image, image_type FROM testblob WHERE user_id=$image_id";
/*** prepare the sql ***/
$stmt = $dbh->prepare($sql);
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$array = $stmt->fetch();
if(sizeof($array) == 2)
{
header("Content-type: ".$array['image_type']);
echo $array['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
echo 'Please use a real id number';
}
}
index.php
<body onload="showUserProfilePic(<?php echo $_SESSION['current_user_id'];?>)">
<div id="txtHint">Child Picture will be listed here.</div>
<script>
function showUserProfilePic(str) {
//alert(str);
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getImage.php?image_id="+str,true);
xmlhttp.send();
}
}
Try using
$sql = "SELECT image, image_type FROM testblob WHERE user_id='" . $image_id . "';
and where is your tag?
Related
I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.
I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.
setInterval(function () {sendRequest()}, 5000);
function sendRequest(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log("yay");
}
}
xmlhttp.open("GET","getTweets.php",true);
xmlhttp.send();
}
My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:
$conn = mysqli_connect("localhost", "*", "*", "*");
if (!$conn) {
echo("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM tweets;";
$results = mysqli_query($conn, $query);
while($list = mysqli_fetch_assoc($results)){
echo '<div class="tweet-containter">';
echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">#'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';
echo '</div>';
}
This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
And Status Code
200: "OK"
404: Page not found
with that said, try doing this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
} else if(xmlhttp.status == 400) {
alert('There was an error 400')
} else {
alert('something else other than 200')
}
}
}
ryandonohue,
PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).
Though, for your intermediate purposes you might not notice an immediate difference.
For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.
Modification:
function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
$values_str = "";
foreach($values as $key => $value){
$values_str .= $value . ", ";
}
$cond_str = "";
$hascond = false;
if($conditions != null){
$hascond = true;
foreach($conditions as $key => $value){
$cond_str .= $key . "='" . $value . "' AND ";
}
$cond_str = rtrim($cond_str, " AND ");
}
$values_str = rtrim($values_str, ", ");
$cond_str = " WHERE (" . $cond_str . ")";
$orderby = "";
$hasorder = false;
if($ascdesc != null){
$hasorder = true;
foreach($ascdesc as $key => $value){
$orderby = " ORDER BY " . $value . " " . $key;
break;
}
}
$sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
//echo $sql;
$sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
$sql_prep->execute();
return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);
}
initialization: ( returns an array so you need to json encode)
getall('table',
Array(
'*'
),
null, 5, null);
AJAX:
function ajax(file,type, params, func){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//xmlhttp.responseText
func(xmlhttp.responseText);
}
}
if(type.toLowerCase() != "post"){
xmlhttp.open(
type, file + "?" + params_to_get(params),
true
);
xmlhttp.send();
}else{
xmlhttp.open(
type, file,
true
);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params_to_get(params));
Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.
check out this POST for more information about headers:
Ajax call to PHP is returning nothing
I am trying to update a particular div of my web page without reloading the complete page. Instead on response complete web page gets inserted in the targetid. I am using a javascript function to do so. Here are my code of php from where javascript function is called.
if($check_like==0)
{
// if user has not liked this post
$divid_like = $postid.'like';
echo "<div id='$divid_like'><a href='#' onClick=\"ajax_post('Ajax.php?action=Like-Status','postid=$postid','$divid_like',0);\" name='Like'> Like </a> </div>";
//echo "<a href='action.php?action=Like-Status&postid=$postid' name='Unlike'> Like </a>";
echo "<a href='#' onClick='' > Comment </a>";
echo "<a href='#' onClick='' > Share </a>";
}
Here is my javascript function :
<script language="JavaScript">
function ajax_post(url , args , targetid, add)
{
var xmlhttp;
if(window.XMLHttpRequest)
{
// works for all browser abve IE7, chrome and firefox
xmlhttp = new XMLHttpRequest();
}
else
{
//for IE5 and IE6 which i don't think i nedd to handle still
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlhttp)
document.getElementById(targetid).innerHTML = "somesdlkvnoisnvoanfvnfnerroor";
xmlhttp.open("POST",url, false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//xmlhttp.setRequestHeader("Content-length", args.length);
//xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function()
{
var xhr = event.target;
if(xhr.readyState==4 && xhr.status==200)
{
if(add==0)
{
document.getElementById(targetid).innerHTML = xhr.responseText;
}
else
{
document.getElementById(targetid).innerHTML+= xhr.responseText;
}
}
else
{
document.getElementById(targetid).innerHTML = "somebigbigbigrroor";
}
};
xmlhttp.send(args);
}
Ajax.php file being called to process data:
<?php
include_once("Includes/master_login.inc");
include_once("Includes/connect_to_database.php");
include_once("Includes/Users.php");
include_once("Includes/Friends.php");
include_once("Includes/current_page_url.php");
include_once("JavaScript/XML.js");
include_once("profile_display.php");
include_once("Includes/Status_Likes_Comment.php");
include_once("Includes/message.php");
include_once("Includes/NewsFeed.php");
include_once("sendmessage.php");
$action = $_GET["action"];
$uid = $_SESSION['uid'];
//if(!user_online($uid)){$action=0;}
if($action=="Add-Friend") { add_friend($uid,$_POST["uid"]); if($_POST["refresh"]="profile") echo display_profile($_POST["uid"]); }
if($action=="Respond-Friend-Request") {friend_accept($_POST["uid"],$uid); if($_POST["refresh"]="profile") echo display_profile($_POST["uid"]); }
if($action=="Like-Status") { like_status($uid,$_POST["postid"]); echo "Unlike"; }
if($action=="Chat-Send") {add_message($uid,$_POST["to"],$_POST["message"]); echo display_message($uid,$_POST["to"]);}
//if($action=="Chat-Send") {echo $_POST["message"]; delay(1000);}
?>
On liking the status instead of being replaced by Unlike complete page gets loaded in this div.
Ive got an PHP which creates a .json file:
<?php
$data=array( "Name"=>"Someone", "Surname" => "Somebody");
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{objectValue: '".addslashes($key)."', textObject: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1);
$jsontext .= "]";
echo $jsontext;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($jsontext));
fclose($fp);
?>
This is the results.json:
"[{objectValue: 'Name', textObject: 'Someone'},{objectValue: 'Surname', textObject: 'Somebody'}]"
The javascript:
var xmlHttp = createXmlHttpRequestObject();
var finalText;
window.onload = process;
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp) {
alert("Cant create XmlHTTP...");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("GET", "http://localhost/results.json", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
//setTimeout('process()', 1000);
alert("Error: Server is busy");
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
finalText = xmlHttp.responseText;
}else{
//alert("Error: server is busy");
}
}
function convertJSON(){
parsedText = JSON.parse(finalText);
alert(parsedText); //This shows the parsed text, it gets here
document.getElementById('finalResult').innerHTML += parsedText.objectValue;
document.getElementById('finalResult').innerHTML += parsedText.Name;
}
Whenever I summon convertJSON from a button onclick I keep getting undefined, when printing the results into the "finalResult" div... what am I doing wrong?
You're building your JSON by string concatenation, then sending it into json_encode. Instead build your JSON as an array:
$jsonData = array();
foreach($data as $key => $value) {
$jsonData[] = array('objectValue' => $key, 'textObject' => $value);
}
$jsontext = json_encode($jsonData);
echo $jsontext;
fwrite($fp, $jsontext);
You need to use valid JSON, strings are always surrounded with double-quotes and object keys are also surrounded by double-quotes. So your JSON string that is served up by PHP should read as follows:
[{"objectValue":"Name","textObject":"Someone"},{"objectValue":"Surname","textObject":"Somebody"}]
There's a good online reference for JSON structure that you might want to give a read.
i am trying to change the select query on click or on change of the button,
the table name field names in the table general are equal to the fragment after page = (About, ContactInformation)
i'm not getting any error nor getting any result
index page code
<script>
function selectQuery(str) {
if (str == "") {
document.getElementById("editor").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("editor").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queries.php?page="+str,true);
xmlhttp.send();
}
}
</script>
<ul>
<li><i class="fa fa-file-text"></i> About us</li>
<li><i class="fa fa-list-alt"></i> Contact us</li>
</ul>
queries.php page
<?php
$page = intval($_GET['page']);
$result = mysql_query("SELECT general.'".$page."' ".
"FROM general") or trigger_error(mysql_error());
echo $result;
?>
i tried to echo $page in the queries.php file directly but also it is not showing, seems its not even getting here,
so can anyone help pls
You aren't fetching those results. You need to use mysql_fetch_* functions to get those rows. Now the next part is whether you would like to get a JSON response or just output an HTML markup that can be used directly.
Here's what the fetching would look like:
<?php
$page = $_GET['page'];
$data = array();
$result = mysql_query("SELECT general.".$page." FROM general") or trigger_error(mysql_error());
while($row = mysql_fetch_assoc($result)) {
// fetch the results
$data[] = $row;
}
echo json_encode($data);
?>
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a version with mysqli:
<?php
$default_columns = array('About', 'ContactInformation', 'Others', 'Home');
if(isset($_GET['page']) && in_array($_GET['page'], $default_columns)) {
$return_value = array();
$page = $_GET['page'];
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT $page FROM general";
$query = $db->query($sql);
while($row = $query_fetch_assoc()) {
$return_value[] = $row[$page];
}
echo implode(' ', $return_value);
}
?>