Php to return value - php

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 ..

Related

POST Ajax data to public PHP function

NOTE - This is a edited snippet. This is testing at the moment and will be improved after.
I'm aiming to learn oop PHP now I got a good understanding of procedural. I'm stuck on sending this Ajax request to my php file.
Html File
<script>
$("#Question").click(function() {
flag = 1;
uid = "<?php echo $uid ?>";
var dataQuestion = {
uid,
flag,
ImageOne: $("#Image1").val()
};
//Post with AJAX
$.ajax({
type: "POST",
url: "../View/class.user.php",
data: dataQuestion,
perform: "QuestionsFunctions",
success: function(Returned){
$(".NotBoxSmall").text("Updated");
$(".NotBox").text("Updated");
flag = 0;
console.log(Returned);
},
error: function(){
$('.NotBox').text("Issue With Site");
$('.NotBoxSmall').text("Issue With Site");
}
});
});
</script>
Php file
<?php
public function QAsk(){
if($_POST['flag'] == 1){
$Image1 = $_POST['ImageOne'];
$uid = $_POST['uid'];
$insertsqlQ = "UPDATE UsersData
SET Image1 = '$Image1'
WHERE uid = $uid";
$resultquestion = mysqli_query($this->db,$insertsqlQ) or die(mysqli_connect_errno().json_encode("Data cannot inserted"));
return $resultquestion;
echo json_encode("Question Updated");
}else{
echo json_encode("Question NOPE");
return false;
}
}
?>
The id sends and iv'e tested this not within the public function and it appears to be fine. The request send back is blank, outside of the function it's the error log.
The issue is it says questions have been updated but no data has been added to the database.
jQuery must be initialized after the DOM ( document object model ).
How should I initialize jQuery?
I'd suggest some tips:
1 - Make the id names lower case #name_of_element
2 - Grab a OO PHP book and try to practice just this, run tests using curl for instance and make your database rules work before going into the client (html, js, css)
3 - Grab a jQuery book and run tests with mock data just printing a array from PHP. At the beginning is easier study stuff separated.
4 - '$Image1' is a varchar rather than the variable $Image1. Remove the quotes

PHP equivalent to jQuery html() or text()

Im trying to print the result of a php function to specific html id or class
the php function is called by a button input
jQuery code:
function myfunction() {
$answer = 'random text <b>' + $radomvar +'more random';
$('#resultline').html($answer);
}
is there an equivalent for the
$('#resultline').html($answer);
in php?
What you're asking doesn't make sense. You can can embed PHP code alongside HTML code and it is processed by the server before the HTTP response is sent back to the client.
Therefore, why not do something like:
<span id="resultline"><?php echo myFunction(); ?></span>
Where myFunction is a PHP function that returns the string you want to embed?
You can write your javascript code in .php file and then use your JavaScript function like this:
function myfunction() {
$answer = 'random text <b>' + '<?php echo myfunc($radomvar); ?>' +'more random';
$('#resultline').html($answer);
}
No there isn't. PHP is server side so after the request is done it can't change the webpage anymore. If you want to do that the only option is an AJAX call with for example JQuery as framework.
You can't do proper DOM Manipulation with PHP. For the purpose of your question, you'd have to use jQuery's ajax function to request the variable value from the backend, and fill the container when you retrieve it.
js script:
jQuery.ajax({
url: 'myfunction.php',
data: {varname: randomvar},
type: 'POST'
}).done(function(response) {
$('#resultline').html(response);
});
myfunction.php
<?php
function myfunction($radomvar) {
$answer = 'random text <b>'. $radomvar .'more random';
return $answer;
}
echo myfunction($_POST['varname']);
Please note that you don't need PHP to interpolate variables in a string. That function doesn't need PHP whatsoever to run. If the only purpose of PHP here is to get $radomvar value, and you're positively sure you want to have PHP in your frontend, then it would suffice to do something like
<script>
function myfunction(radomvar) {
var answer = 'random text <b>' + radomvar +'more random';
$('#resultline').html(answer);
}
var randomvalue='<?php echo $radomvar; ?>';
myfunction(randomvalue);
</script>
Well their is no function equal to that in php, however you can easily achive the same effect rather easy by writing few more lines of code.
<div id="resultline"><?php echo $answer; ?></div>
instead you have to place php echo code where you want printed out on the html page, otherweise you have to use ajax or something else than php.

How do I pass PHP variable names to Javascript function

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.

How to call $_SESSION in javascript

I have two separate pages, one page is where it uploads the file and the other page displays the information.
In the imageupload.php page, I have this session below:
$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];
I also have a javascript function which calls back to the javascript functiom:
<script language="javascript" type="text/javascript">window.top.stopImageUpload();</script>
Now on a seperate page (QandATable.php), I have a javascript function, but my question is how can I call the $_SESSION code above in the javascript function so I can append it to $('.list')?
Below is javascript function:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
You cant, because $_SESSION is a server side variable but you can access it by.
For the entire session variable
<script type="text/javascript" >
var session = <?php echo json_encode($_SESSION); ?>;
</script>
For a particular variable in session.
<script type="text/javascript" >
var session_var = <?php echo json_encode($_SESSION['VAR_NAME']); ?>;
</script>
Now you have js variable called session with that information. However it is not advisable in most situation to output all that info to public pages.
Session variables are stored on the server. JavaScript is executed on the cliend side, so it knows nothing about the server side. It know only as much as you pass to it.
To pass a variable to javascript, use an ajax request, or simply output the values:
<script>
var sesionValue = <?=json_encode($_SESSION['value']);?>;
</script>
You should look into using JQuery, as it makes these AJAX-like tasks much easier.
See my function I wrote just today to do something similar to what you're asking.
This takes some PHP output (returned in the success part of the call to ajax(). The format it takes is in JSON, which is compatible by both PHP and JavaScript (JSON: JavaScript Object Notation).
function viewClientDetails(id) {
var clientParams;
clientParams.clientID = id;
$.ajax({
url: BASE_URL + '/clients/get-client-details.php',
type: 'POST',
data: clientParams,
dataType: 'JSON',
success: function(myClient) {
var name = myClient.name;
$('td#name').html(name);
},
error: function(e) {
console.log(e.responseText);
}
})
}
In my PHP file (called /clients/get-client-details.php) I have something like this:
<?php
...
$myClient = array('name' => 'Mr Foobar');
print json_encode($myClient);
?>
This simply writes my PHP object to JSON format.
In the JS code above, the code inserts a part of the JSON data into an HTML table-data element whose CSS selector ID is #name, with the line: $('td#name').html(name);
Apologies if this confuses you more, I thought I'd show an example of what you can try some time..
This may help you a bit along the way...keep trying things, you'll get there :)
You can't. $_SESSION is a PHP variable, and that code runs server-side.
You'll need to store the value as a Javascript variable in the output from your PHP file, then access that variable in your Javascript.

Pass two parameters in $.ajax success function

I have a little problem. I want to pass two variables from PHP to $.ajax success function
I have this code written in JS:
$.ajax({
type:"POST",
url:path,
data: "value="+info,
success:function(data,data1)
{
if(data==1)
{
$(id).css("backgroundColor","green");
$(id).attr("readonly","readonly");
$(image).attr("src",data1);
}
else
{
$(id).css("backgroundColor","red");
}
}
});
And my PHP code is :
if(isset($_POST['value']) and !empty($_POST['value']))
{
$result=0;
$image="src/photo1.jpg";
$value=trim($_POST['value']);
if($value=="Abracadabra" or strcmp($value,"Abracadabra")==0)
{
$result=1;
$image="src/abracadabra.jpg";
}
else
{
$result=0;
$image="src/photo1.jpg";
}
echo $result;
echo $image;
}
There, I want to "echo" two variables simultaneously to pass to $.ajax success function.
It is possible ? I don't refer to JSON, I refer only PHP with POST method.
Thank you
the response from php code will be something like:
0src/photo1.jpg
and you will have to parse it with the javascript (probably with regex or substring)
success:function(data,data1) {
var result = data.substring(0,1);
var image = data.substring(1);
// ... your code
}
keep in mind that it could cause you trouble if the $result variable is more than one character long :)
have PHP echo a string like "value1|value2|etc" (or whatever other character(-sequence) is unlikely to wind up in the actual data)
then on the javascript side do a string.split('|') to break the returned string up into a neat little array. you could even do key1:value1|key2:value2
and then use the solution presented here to split the key:value pairs up into an object.

Categories