Ajax, JQuery & PHP - Passing PHP variable to JQuery - php

I have a page that allows users to upload multiple files and preview them without refreshing the page using jquery. In php I generate a unique file_id for each filename which I would then like to pass back in to JQuery and use it to load up the preview image etc.
I hope I have explained myself clearly.
Thanks for any pointers!
The PHP code:
// php code to upload file and generate unique file id. then...
if (move_uploaded_file($main_image, $file)) {
echo "success";
echo $file_id; // <--- I WANT TO PASS THIS VARIABLE BACK IN TO JQUERY
} else {
echo "error";
}
The J Query Code:
$(function(){
var btnUpload=$('#upload_main');
var mestatus=$('#mestatus');
var button=$('#button');
var files=$('#main_file');
new AjaxUpload(btnUpload, {
action: 'classified-ads/upload-classified-image.php?filenumber=1',
name: 'file1',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|'')$/.test(ext))){
// extension is not allowed
mestatus.text('Only JPG, PNG or GIF files are allowed');
return false;
}
mestatus.html('<img src="extras/ajaxuploader/progress_bar.gif" height="30" width="340">');
button.html('Loading...');
$('#upload_main').removeClass('hover').addClass('upload_button_loading');
},
onComplete: function(file, response){
//On completion clear the status
mestatus.text('Photo Uploaded Sucessfully!');
button.html('Change Photo');
$('#upload_main').removeClass('upload_button_loading').addClass('upload_button');
//On completion clear the status
files.html('');
//Add uploaded file to list
if(response==="success"){
var file2 = file.replace(/\s/g, "_");
var file_id= file_id;
$('<div></div>').appendTo('#main_file').css('background-image', "url(/ht/classified-ads/temp_images/prev1_<?php echo $parsed_user;?>_"+file_id+")").addClass('main_success');
$("#image1_temp").val("main1_<?php echo $parsed_user;?>_"+file_id+"");
$("#thumbnail_temp").val("thumbnail_<?php echo $parsed_user;?>_"+file_id+"");
} else{
$('<li></li>').appendTo('#main_file').text(file).addClass('error');
}
}
});
});

In your PHP:
$response = array('result' => 'success', 'file_id' => $file_id);
echo json_encode($response);
In your jQuery:
var obj = $.parseJSON(response);
You would then check whether the response was a success with if (obj.result == 'success') and you'd get your file_id with obj.file_id

The simplest way is to do this allowing for MULTIPLE values to be returned:
// Make a variable to hold data to send back and keep track of your separator
$data = '';
$separator = 1;
// Put this in a loop, your loop will depend on how many file uploads you have
// I did not do the loop for you
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
if ($separater==1){
$data .= $file_id;
} else {
$data .= ','.$file_id;
}
$separater++;
}
// Now outside the loop echo the results back
echo $data;
With this info echoed back you can manipulate it with Javascript (Jquery). Just use something like spli(','); which gives you an array of the file names you needed.
If you only want one value to come back, meaning you only have one file id to send back foregt everything about the loop and the PHP would be this:
if (move_uploaded_file($main_image, $file)) {
// echo "success"; Take this out
$data = $file_id;
// Now echo the results back
// Its been a while since I've done this but there may be times its ok to use return
echo $data;
} else {
// Handel error here
echo "error";
}
Now based off your code this echoed information should be picked up and processed here:
onComplete: function(file, response){ ... }
Instead of looking for "Success" you need to change your code to look for a file id or something like error instead (which is easier) like so:
if(response!=="error"){
// Now you can use your variable "response" here since it contains the file id
} else {
// Handle the error
}
The reason I gave you a long explanation about getting multiple values back is because that is more common as you start making more advanced forms and it wouldn't hurt to use now. This way you can allow multiple file uploads for example. What I do for example when using AJAX is echo back something like this:
1::value,value,value
Now I just split that into arrays first by :: and then by , this line for example says No Error Happened (1 which as we know is also TRUE) and here is your data: value,value,value which you can now use for things in your Jquery or just print to the document.
You should look at the Jquery AJAX page for in depth examples and explanations, it explains the trouble you ran into getting results back. Look at .done .success .complete especially.

Related

Compare user value to database and show result through ajax jquery

Guys m working on my first live project and i am stuck at a point, where i need help with ajax jquery. i can do this with PHP but i wanna do this with ajax.
Here if user enter a product code ,so i want to compare this product code value into my database and show product name in my other form ,which will open after user input value:
Here in first field i want product name:
Here in my table you can see product code and product name:
ok so here is my html code in last option when user enter product code
Here is jquery i am sending user data to 8transectiondata.php to compare
And this is php file and i want $data['product_name']; to show
Here's a generic answer.
JS FILE:
$(document).ready(function () {
$('#myButtonId').on('click', function () {
var code = $('#myCodeInputId').val();
if (code !== '') { // checking if input is not empty
$.ajax({
url: './my/php/file.php', // php file that communicate with your DB
method: 'GET', // it could be 'POST' too
data: {code: code},
// code that will be used to find your product name
// you can call it in your php file by "$_GET['code']" if you specified GET method
dataType: 'json' // it could be 'text' too in this case
})
.done(function (response) { // on success
$('#myProductNameInput').val(response.product_name);
})
.fail(function (response) { // on error
// Handle error
});
}
});
});
PHP FILE:
// I assumed you use pdo method to communicate with your DB
try {
$dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
exit('ERROR: ' . $e->getMessage());
}
$sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
$result = $dbh->prepare($sql);
$result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
$result->execute();
if($result->rowCount()) { // if you got a row from your DB
$row = $result->fetchObject();
echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
// if we use text method in ajax, we simply echo $row
}
else {
// handle no result case
}
I know what you want to do, but without specific code the best I can do is give you a generalized answer.
When a user fills out a field, you want to post that field to the server, look up a product and return some stuff.
The basics are going to look like this.
$(document).ready( function(){
//rolling timeout
var timeout;
$('#field').on('keyup', function(e){
if(timeout) clearTimeout(timeout);
timeout = setTimeout( function(){
var data = {
"field" : $('#field').val()
};
$.post( '{url}', data, function(response){
if(response.debug) console.log(response.debug);
if(response.success){
//open other form
$('{otherFormProductField}').val(response.product);
}
}); //end post
},450); //end timeout
});//end onKeyup
}); //end onReady
Then in PHP, you have to process the request. Pull the field from the $_POST array, look it up in the Database. Then build a response array and send it back to the client as JSON. I like to build responses in a structure something like this.
{
success : "message", //or error : "message"
debug : "",
item : ""
}
Then in PHP I will do this.
ob_start();
..code..
$response['debug'] = ob_get_clean();
header("Content-type:application/json");
echo json_encode($response);
This way, you can still print out debug info (in side the output buffer calls ) when developing it and don't have to worry about it messing up the Json or the header call.
-note- Use a timeout, that you reset on each key press (a rolling timeout). What it does is reset the previous timeout each time the key is released. That way it only sends the request once the user quits typing (instead of sending request on every keypress). I have found 450 milliseconds to be about the perfect value for this. Not too long not too short. Basically once they stop typing for 450ms it will trigger the $.post

Returning Uploadifive Ajax 'Error/Success' data from Codeigniter Controller

I'm using the Uploadifive upload plug-in. It works as it should. However, I'm having a hard time passing error and success messages from my controller back to my view via the plug-in. I'm logging console and log errors. But can't seem to return any controller errors back to the Uploadifive call to display in my view.
In short, I want to output either an error or success message from my controller (via the $result var) back to my ajax function to embed into my view.
The alert, alert(data.result) outputs "undefined".
JS function:
$('#file-upload').uploadifive({
...
'onUpload': function(file) {
console.log('upload complete!');
},
'onUploadComplete' : function(file, data) {
console.log('The file ' + file.name + ' uploaded successfully.');
// returned error/success message here
alert(data.result);
},
'onError': function(errorType) {
console.log(errorType);
}
});
CI Controller method:
function add_document() {
// If Ajax request, proceed:
if(isset($_POST['is_ajax'])) {
if (!$this->upload->do_upload()) {
// If file upload failed or is invalid,
// display error notification
$result = array('error' => $this->upload->display_errors());
echo json_encode($result);
}
else {
// If file upload was successful
$result = 'success!';
echo $result;
...
}
}
// if not, redirect to upload page
else {
redirect('upload');
}
}
I figured out how to get this to work with my controller code. Uploadifive is not well documented, so it's been a shaky ride. But none the less, here's how I got it to function the way I wanted. Hopefully this helps others.
In my controller, I replaced the echo json_encode($result); line with the below. Specifying the array key I want to use (i.e. error) and the outputting of the result as html.
echo html_entity_decode($result['error']);
In my javascript function, all I simply needed to do was output the data... .result was not needed in the alert. Note, I decided to attach the result to some html versus an alert.
// Display Error/Success Messages
$('.status').html(data);

Quick suggestion on php multiple file uploading

I'm using thid code this basically helping me getting file which user drops on browser and then post it to php and echoing file name but the problem is with the array in php when ever i drop 2 files and call the php file and try to echo the count of files it gives me 5 always and it echos the 2 file names and + othes as undefined index.... and if i upload 5 files it show all 5 with no problem....plz help me why this is happing...
Here is my jquery code:
function handleFiles(droppedFiles) {
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) {
// checks if any files were dropped
for(var f = 0; f < droppedFiles.length; f++) {
// for-loop for each file dropped
alert(droppedFiles[f]['name']);
uploadFormData.append("files[]",droppedFiles[f]);
// adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "try.php?size="+s, // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
return false;
}
Here is my php code :
if(isset($_FILES["files"])) {
for ($i=0;$i<count($_FILES['files']);$i++) {
echo $_FILES['files']['name'][$i];
echo "\n";
}
}
It doesn't work this way. $_FILES is an associative array containing the uploaded files, indexed by the field name. Each entry has exactly five elements: name,tmp_name,size,type and error. Each of these elements is an array containing as many elements as the uploaded files.
So if you count($_FILES['files']), the result will always be 5. But if you count($_FILES['files'][$xyz]) where $xyz is any of the above keys, that will be the number of uploaded files.
So your code would work like this, for example:
if(isset($_FILES["files"]))
{
for ($i=0;$i<count($_FILES['files']['name']);$i++)
{
echo $_FILES['files']['name'][$i];
echo "\n";
}
}
or better yet (for readability, if nothing else):
if(isset($_FILES["files"]))
{
$filenames=$_FILES['files']['name'];
for ($i=0;$i<count($filenames);$i++)
{
echo $filenames[$i];
echo "\n";
}
}

sending javascript variable (from knockout.js) to php and return result

How can I go about accomplishing the following behavior.
upon getting an input from a knockout.js form send the variable to a page to be handled. The page uses PHP
The PHP page receives the input from the knockout.js form and runs some calculations and then returns the result
The variable is then received back on the original page and is then displayed via knockout
For example, say I have the following
//knockout_form.js
self.addItem = function() {
var itemNum = self.newItem; //variable received from knockout form
var returnedVariable = ???? **send itemNum to processing.php which will then return it**
self.itemNumbers.push(new ItemEntry(retunredVariable, "$20.00")); //
}
I know that jQuery/Ajax can be used to post to processing.php, but how do I return the calculated data from processing.php back to the javascript page?
edit below. The data appears to be sent to processing.php (shows up in the network tab) but the alert isn't showing.
// Operations
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum),function(data) {
alert(data); //this does not appear
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
}
}
Here's the php
//$result = $_GET['itemNum'];
$result = "test"; //set it just to be sure it's working
echo json_encode(array("result" => $result));
Knockout doesn't have any special way of doing ajax calls itself, typically you would use jQuery. See http://knockoutjs.com/documentation/json-data.html.
So something like:
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum,function(data) {
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
});
}
This assume that your PHP script is outputting valid JSON. Something like:
<?php
$result = doCalculations($_GET['itemNum']);
echo json_encode(array("result" => $result));
?>
This is untested, but you get the idea.

JQuery Do something when data returned from .post

I have a site that is sending off using the .post function in JQuery to run a php script. This script adds some data to a database but if the data already exists in the database it doesn't add the data. Depending on whether the data is added or not I want the javascript to do different things. I don't know how to get the php to return a value that says "data entered" or "data not entered" so the javascript can use that value to decided upon it next action.
Here is the javascript, I only want the append to happen if the php returns that the data was entered into the database.
$('#addpios').click(function() {
var scopesheetidvalue = $("#scopesheetid").val();
var piovalue = $("#pioselected").val();
$.post("addpio.php", { scopesheetid: scopesheetidvalue, pionumber: piovalue },function(data){
$('#pioslist').append("<li><input class='removepio' type='submit' value='"+piovalue+"' /><span class='listitem'>PIO "+piovalue+"</span></li>");}
);
});
Here is the PHP
$scopesheetid = $_POST['scopesheetid'];
$pionumber = $_POST['pionumber'];
$alreadyexisitssql = "SELECT * FROM [ScopesheetPIO] WHERE [ScopesheetID]='$scopesheetid' AND [PIONumber]='$pionumber'";
$alreadyexisits=odbc_exec($connection,$alreadyexisitssql);
if(odbc_fetch_row($alreadyexisits)){
//retrun a value that says the data already exists
}
else{
$addpiosql = "INSERT INTO [ScopesheetPIO] ([ScopesheetID], [PIONumber]) VALUES ('$scopesheetid', '$pionumber')";
$addpioresult=odbc_exec($connection,$addpiosql);
//retrun a vlaue that the data was added
}
What I really want is a way to pass a value from the PHP script back into the Jquery
I would modify your jQuery to the following:
$.post('addpio.php', { ... }, function(data) {
if (data.result) {
$('#pioslist').append(...);
}
}, 'json');
In your PHP file, use this when the data is inserted:
echo json_encode(array(
'result' => TRUE
));
Use this when the data already exists:
echo json_encode(array(
'result' => FALSE
));
Build an array in PHP and output it as JSON. Then inspect the returned JSON in your script.
if(odbc_fetch_row($alreadyexists)){
// Return a value that says the data already exists
$result = array(
"error" => "Data already exists"
);
} else {
// Database stuff goes here...
// Return a value that the data was added
$result = array(
"success" => 1
);
}
echo json_encode($result);
JavaScript $.post callback:
function(data) {
if(data.success) {
// Append element to HTML
} else {
// An error occurred, inform the user
// Don't actually use alert(), this is just for demonstrating purposes
alert(data.error);
}
}
Later on, you can then create more complex responses with extra data by simply adding them to the $result array and reading them from data in your JavaScript.
Write anything in your PHP that you'll test in your callback function :
PHP
if(odbc_fetch_row($alreadyexisits)){
echo "ko";
}
else{
$addpiosql = "INSERT INTO [ScopesheetPIO] ([ScopesheetID], [PIONumber]) VALUES ('$scopesheetid', '$pionumber')";
$addpioresult=odbc_exec($connection,$addpiosql);
echo "ok";
}
JS
$.post("addpio.php", { scopesheetid: scopesheetidvalue, pionumber: piovalue },function(data){
if( data == 'ok' ) {
$('#pioslist').append("<li><input class='removepio' type='submit' value='"+piovalue+"' /><span class='listitem'>PIO "+piovalue+"</span></li>");
}
});
You can easily pass data from a script to jQuery. IMO I think its best to use JSON as its much more neater.
PHP (for example):
$arrayOfData=array("val1"=>"value","val2"=>"value");
//encode it
$arrayOfData=json_encode($arrayOfData);
//print it on screen
echo $arrayOfData;
And then get it in jQuery using the .getJSON.
$.getJSON("url_of_php_fle",function(myData){
//now use myData as the array:
alert(myData.val1);//which will give you "value" as what you set in PHP
}):
It really is that easy.

Categories