I have two pages one called upload-file.php, this page uploads the image into the database and my folder.
My PHP page looks like this.
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file))
{
$insert=mysql_query("insert into match_item_image set item_id='".$_SESSION["session_temp"]."', image='".$name."', adid='$adid'") or die(mysql_error());
$cc=mysql_insert_id();
echo "success".$cc;
My other page consist of a javascript function which displays my images upon upload.
The problem I am having is that I need to change the image name when uploading it into my folder. I was able to change the image name but when I upload the image it displays blank because the JavaScript function Is looking for the original name of the image, when the users uploads the file.
This is part of the function:
$(function()
{
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext)
{
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}status.text('Uploading...');
},
onComplete: function(file, response)
{
//On completion clear the status
status.text('');
//Add uploaded file to list
var bb=response.substr(0,7)
var idd=response.replace('success',' ');
var idb =idd.replace(/^\s*|\s*$/g,'');
if(bb==="success")
{
$('<span id='+idd+'></span>').appendTo('#files').html('<img src="upload/+file+" alt="" width="290" height="330" class="image1" /><br><a href="javascript:void(0)" onClick="deleteFile('+idd+');" class="image1" > <span style="font-weight:bold; font-size:14px; color:red;" > Delete </span></a>').addClass('success');
}
else
{
$('<span></span>').appendTo('#files').text(response).addClass('error');
}
Please let me know if anyone can help.
I am new to javascript.
Hi,
I forgot to add that the form to upload the image looks like this
<div id="upload" ><span>Upload Image<span></div><span id="status"></span>
<table><tr><td id="files"></td></tr></table>
I just need to know how I can make my code display the image name I have saved in my folder and right after i upload it and not the original image name that the users upload because there might be other users who uploaded images with the same name and they are getting mixed up.
Thanks for everyone help. I been working on this for weeks now and i cant seem to figure it out. I just dont want to give up on this piece of code because it is exactly what I need.
You can write PHP right into your javascript like this:
<script>
alert('<?php echo $myVar; ?>');
</script>
Alternatively, you can create AJAX calls to acquire database variables, processed by a PHP script.
Recommendation based on your code:
Make your onSuccess function give you the name of the file from the PHP page. You can do this with JSON. Please ask if you need help.
Instead of this PHP-Code:
echo "success".$cc;
you could output your result as a JSON-String, which can be easily access by JavaScript:
header("Content-Type: application/json");
echo "{
\"status\" : \"success\",
\"filename\" : "$file",
\"id\" : $cc
}";
Instead of this JavaScript part
//Add uploaded file to list
var bb=response.substr(0,7)
var idd=response.replace('success',' ');
var idb =idd.replace(/^\s*|\s*$/g,'');
you would then be able to access the parameters of your result just like properties of the response object:
var bb = response.status;
var idd = response.id;
var filename = response.filename;
See http://de.wikipedia.org/wiki/JSON for more info.
You can also use php functions for JSON output: http://www.php.net/manual/de/function.json-encode.php
echo '<script type="text/javascript">var myJSVar = '.$myPHPVar.';</script>';
You will want to have your PHP script output the new name, and then use that in your JavaScript. How you would go on extracting the response depends on your AJAX code, and I am not familiar with what you used in the example.
Related
Currently I have a PHP file and a .js file. In my PHP file I have div class called wrapper_tab-content. Now the code for this is present in my js file which shows the following code:
$(document).ready(function() {
portalarray = new Array();
$('input.checkbox').change(function(){
portalname = $(this).attr('data-name'); pid= $(this).attr('id');
if ($(this).is(':checked')) {
portalarray.push(pid);
$(".wrapper_tab-content").append('<div class="portalcontent content--active" id="'+pid+'"><div class="col-md-12 text-left">
<label class="control-labels ">Title</label><input id="'+pid+'" name="'+portalname+'" placeholder="'+portalname+' Title" type="text"></div></div>');
}else {
$(".portaltabs .container--tabs li#"+pid).remove();
$(".wrapper_tab-content #"+pid).remove();
tabslength = $(".wrapper_tab-content").length;
}
});
});
Now I have to enter the property title inside value attribute that I can get by using <?php get_portals[0]['property_title'] ?> inside my .js file for which I'm assuming there needs to be an AJAX call being made?
To clear things up for you Javascript is client side and PHP is server side .
What you looking at doing is getting PHP value's into Javascript .There are a few ways to do this . Most programmers use events as server side could have updated during the lifetime of the page
most common is post and get requests through Ajax but you could also get data through an event
<script type='text/javascript'>
document.body.onclick(function(){
var Variable = <?php echo(json_encode($Variable)); ?>;
};
</script>
I have a php code that retrieves image from database and stores it in json by encoding it using base64.
$query=mysql_query("SELECT Id,Image FROM $table_first");
while ($row=mysql_fetch_assoc($query)) {
$array=$row;
$array['Image']=base64_encode($row['Image']);
$output[]=$array;
}
echo json_encode($output);
now i have a html file where i have to decode this image and display it in a div element. I have no clue as to how to decode the image.
$(document).ready(function(){
$.ajax({
url:"loc.php",
dataType:'json',
type:'POST',
success:function(output) {
}
});
});
</script>
</head>
<body>
<p> Test page </p>
<div class="Ch" id="Ch"></div>
Here i need to display the ouptut[0].Image(which is in base64 format) inside the div with the id "ch"
Storing images directly in DATABASE is not a good idea. One way which i recommend is to store the image directly in a specific location in your server and then insert the path to the image in the database.You can avoid much hassle by using this method. :) By the way why are you encoding the image to base_64? How are you storing the image in your Database?
Untested(Assuming the path is stored in the database table )
$query=mysql_query("SELECT Id,Image FROM $table_first");
while ($row=mysql_fetch_assoc($query)) {
$image=$row['Image'];
$id=$row['Id'];
$output=array("id"=>$id,"image"=>$image);
}
echo json_encode($output);
Then in your ajax script
$(document).ready(function(){
$.ajax({
url:"loc.php",
dataType:'json',
type:'POST',
success:function(output) {
var imagehtml='<img src="'+output.image+'" alt=""/>';
$("#Ch").html(imagehtml); //id of the div where you want the image
}
});
});
</script>
You can use (assuming a png )
<img src="data:image/png;base64,input_your_base64_from_database_here" />
Please check Data_URI_scheme and how to display images for more details.
I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)
EDIT: Check at the end of this for the solution
I am new to php, ajax and all other things :)
My question is: is there a way for a php file to return a value?
I have:
a file "loadImages.php" containing the script to get the paths to images from the database.
an image gallery where I want to load images via ajax.
a database containing the path to the images (/images/image1.jpg, /images/image2.jpg).
4 categories of images.
What i'm trying to do is :
When clicking on a link (example, first category), I want to call via jquery's ajax(), loadImages.php with the category passed via POST (cat0, cat1, cat2, ...)
I want to return the value from this php file for example : <img src="image/image1.jpg" />, so via javascript, I can retrieve this string. Using only return in my php file returns XMLHttpRequest when i'm putting the ajax() function in a variable instead of the string <img>.
Is there a way to do it? Or maybe a better way, as I don't fully understand ajax.
Thank you! Sorry for my bad grammar.
Below is a more precise map of what i'm trying to do.
JavaScript:
var test = $.ajax({
type: "POST",
url: "loadImages12.php",
data: "category=0",
complete: function() {
alert("COMPLETE");
},
error: function (){
alert("NOT LOADED");
}
});
PHP (loadImages.php)
function createThumb() {
if(isset($_POST['category'])) {
$imageQuery = mysql_query("SELECT * FROM t_pictures WHERE p_category = 0");
$thumbHtml = '';
while ($tempImageQueryFetch = mysql_fetch_assoc($imageQuery)){
$thumbHtml .= '<img src="ressources/images/' . $tempImageQueryFetch["p_fileName"] . 'Small.jpg" />';
}
return $thumbHtml;
}
else {
$noCategory = "NO CATEGORY TEST";
return $noCategory ;
}
}
createThumb();
SOLVED
Php File
function createThumb(){
//Mysql request
$someVar = //Result of request
return $someVar
}
echo createThumb()
Javascript
$("#someDiv").load("loadImages.php", {category:0});
An AJAX request to PHP is exactly the same as a normal request for a website. You request data from example.com/foo/bar and in return you receive text. The return statement of PHP has nothing to do with what's returned to the client. Only things you echo or otherwise output will be received by the client. That's the same for normal pages and AJAX requests.
So, to "return" <img src="image/image1.jpg" /> to your Javascript AJAX call, echo that string in PHP.
if you want to use the php file that you already have (loadImages.php) just echo the result of the function:
echo createThumb();
Just make the php script to return the path to thumbnail.
and then do something like this in js
somediv.html('<a href="#" class="thumbnail"><img src="">');
and just use the path returned by the php file for the img src ..
how i can i change the content of a page without refreshing.I know we need to use hidden frames for this but all the tutorials i have come across teach this only for HTML files what if the content is returned from a PHP file how do i do it in such a case? what should the php file echo or return?
You will have to use Ajax for that, have a look at this tutorial:
AJAX Tutorial
If you use a hidden frame, the content won't be displayed (hence "hidden"), I think you just mean to use an iframe. But this doesn't fit your description of "without refreshing", since you have to refresh the frame.
When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It's the same whether the PHP file is loaded inside a frame or not.
I use this method for a lot of my websites and so does Google. If you want to get data from a PHP file and then dynamically update the page you need to "import" the PHP file somehow without the entire page being redirected, or using iframes (which works too but is a lot messier). The way you do this is to import the file as a "javascript" file.
The following code demonstrates a form called "testform" and a text input called "userpost".
When you submit the form, it will import a file, and then update div "outputText" with whatever you entered... and wait for it... all without the page being redirected at all or refreshed!
I have included a lot of extra functions to show how you can access all of your functions on the same DOM unlike if you use frames where you have to use "top.object" or what not
index.html
<html>
<head>
// Get objects by their id. We will use this in the PHP imported file
Get = function(id) {
return (!id) ? null : (typeof id == "object") ? id :
(document.getElementById) ? document.getElementById(id) :
(document.all) ? document.all[id] :
(document.layers) ? document.layers[id] : null;
}
// Formats a string so it does not break in a URL
String.prototype.formatForURL = function() {
var str = escape(this.replace(/ /gi, "%20"));
str = str.replace(/\&/gi, "%26").replace(/\=/gi, "%3D");
str = str.replace(/\//gi, "%2F")
return str;
}
String.prototype.contains = function(str) {
return (!str) ? false : (this.indexOf(str) > -1);
}
Object.prototype.killself = function() {
this.offsetParent.removeChild(this);
}
// Import the script
ImportScript = function(js) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
script.setAttribute("charset", "utf-8");
// we add the is tag so can delete the "js" file as soon as it executes
script.setAttribute("id", "import_" + head.children.length);
script.setAttribute("src", js + (js.contains("?") ? "" : "?") + "&is=" + head.children.length);
head.appendChild(script);
}
// Get and send value to php file
sendInfo = function() {
var file = "js/myFile.php?userpost=";
file += document.testform.userpost.value.formatForURL();
ImportScript(file);
}
</head>
<body>
<div>
<form name=testform onsubmit="sendInfo(); return false">
<input type=TEXT name=userpost />
<input type=SUBMIT value=Go />
</form>
</div>
<div id=ouputText>
This text will be replaced by what you type
and submit into the form above
</div>
</body>
<html>
js/myFile.php
<?php
// Here you can now use functions like mysql_connect() etc. even exec()
// ANYTHING! Save them into variables and output them as text which goes
// Straight into the javascript! e.g. :
// $con = mysql_connect("localhost", "username", "password");
// if($con) {
// ... code to retrieve data and save into $variable
// }
// print "alert(\"$variable\");"; // this alerts the value in variable
if(isset($_GET['userpost'])) {
$userpost = $_GET['userpost'];
?>
Get("outputText").innerHTML = "<?=$userpost; ?>";
<?php
}
?>
// Clear text area
document.testform.userpost.setAttribute("value", "");
// Remove the file from header after info is changed
Get("import_<?=$_GET['is']; ?>").killself();
If I had typed in "Hello World" into text input "userpost" then
div "outputText" would be filled with the words "Hello World"
deleting what was previously there, and the text input will be cleared
Hidden frames is one design pattern that is a part of the overall AJAX design pattern. This is an extreme high-level overview, but this is essentially how it works:
Javascript in your HTML page makes a request to your PHP script by using an XMLHTTPRequest object, or a hidden frame or iframe. This is usually done asynchronously, so you can continue to work with your HTML page while the request is being made.
The data is returned to your Javascript. At this point, you can then manipulate the page, and update data on the page using various DOM methods.