i found this code to upload profile image,
http://www.phpdevblog.eu/2011-04/combined/jquery-ajax-and-php-based-profile-image-upload-without-reloading-the-page.html#comments
everything are fine. but i want to set a name file = user_id
how i pass the input hidden user_id value to the php upload file process?
var uploadURL = "processupload.php";
$(document).ready(function(){
$('a#uploadFile').file();
$('a#delete').click(function(){
$('input#profileImageFile').val("");
$('img#profileImage').attr("src","/images/styles/profileBlank.jpg");
$('div#messageBox').html("Image deleted !");
$('div#messageBox').attr("class","success");
$('a#delete').hide();
});
$('input#uploadFile').file().choose(function(e, input) {
input.upload(uploadURL, function(res) {
if (res=="invalid"){
$('div#messageBox').attr("class","error");
$('div#messageBox').html("Invalid extension !");
}else{
$('div#messageBox').attr("class","success");
$('div#messageBox').html("Imagen cargada !");
$('img#profileImage').attr("src","/images/avatars/"+res);
$('input#profileImageFile').val(res);
$('a#delete').show();
$(this).remove();
}
}, '');
});
});
html
<div class="imageContainer">
<img alt="" src="/images/avatars/<?php echo $row_rs_user['user_image']; ?>" width="150" height="150" id="profileImage">
<img alt="" src="/images/styles/upload.jpg">
<img alt="" src="/images/styles/delete.jpg">
<input type="hidden" name="user_id" value="<?php echo $row_rs_user['user_id']; ?>">
<div id="messageBox"></div>
</div>
PHP upload process
if(isset($_POST))
{
.
.
.
.
I'm not familiar with the plugin you are using to handle the uploads, but if the form elements are hitting the PHP as they should, you simply can call
$fileId = $_POST['user_id'];
This will set a variable in your PHP Process equal to the hidden value. Make sure you include it within the ISSET conditional as not to cause any errors.
Just pass the information through the uploadURL:
input.upload(uploadURL + "?user_id=" + $("input[name=user_id]").val(), function(res) {});
Make sure the name of the hidden input holding the user id is 'user_id'.
Server side in PHP you can read the value of the variable with isset($_REQUEST['user_id']).
Related
I have a page where one can upload an image and crop it (to do so i've used this plugin), the result of this crop is then saved in a server.
After looking at the documentation i tried this:
JQUERY
var zis = //some div where i uploaded the image;
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
zis.find('#img_val').val(imageData);
zis.find('.salvaImmagine').click();
});
PHP
public function immagine_profilo(){
if (isset($_POST['crop'])){
var_dump($_POST['img_val']);
// Get the base-64 string from data
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// Decode the string
$unencodedData = base64_decode($filteredData);
// image new name
$newfilename = 'images/immProf' . $_SESSION['auth'] . '.png';
file_put_contents($newfilename, $unencodedData);
// saves the path into a database
$query = "UPDATE users SET pic = '{$newfilename}'
WHERE id = {$_SESSION['auth']}";
$result = mysqli_query($_SESSION['connessione'], $query);
return // function to retrive the image;
}
}
So far so good, the images is saved in the server, its path is saves aswell, only one problem remains: the page needs to be reloaded in order to see the image change, ok we can do better: update the image without a page reload.
So i searched the web to find out about ajax, after some time i've come up with this:
JQUERY
$('.export').click(function() {
var imageData = $('.image-editor').cropit('export');
zis.find('#img_val').val(imageData);
lightbox(false);
zis.find('.salvaImmagine').click();
});
$('.salvaImmagine').on('click', function(event) {
event.preventDefault();
var imageData = $('.cop').cropit('export');
$.ajax({
url: 'lib/ottieniCose.php',
type: 'POST',
dataType: 'html',
data: {
crop: 'Salva',
crop_cop: 'Salva',
img_val: imageData
},
})
.done(function(response) {
console.log("success");
$(".copertina").css('background-image', 'url(' + response + ')');
})
.fail(function() {
console.log("error");
})
});
PHP (lib/ottieniCose.php)
//rquire bla bla bla
if (isset($_POST['crop']) || isset($_POST['crop_cop'])) {
var_dump("test");
//calls the function to save the image
$login->immagine_profilo();
}
Now, i get absolutely no result, the images isn't saved, the path isn't saved, the php page doesn't seem to be called at all (althoug there are no 404 errors) but the image is being cropped, i know that by looking into the code.
I also tried changing the POST method to GET method in ajax, but i get error 414, any help?
the HTML
<div id="lightbox">
<div class="image-editor">
<div class="scegliImm">
<p>Scegli un'imagine</p>
</div>
<input type="file" class="cropit-image-input">
<div class="cropit-image-preview-container">
<div class="cropit-image-preview" style="background-image: url(<?php print $login->get_profile_pic() ?>)"></div>
</div>
<div class="image-size-label">
<p>Nessuna immagine selzionata,<br> seleziona un'immagine.<br>P.S. Puoi trascinare l'immagine<br> nuova sopra quella vecchia</p>
<div class="esci">
<p>Esci</p>
</div>
</div>
<div class="neh">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div>
<input type="hidden" name="img_val" id="img_val" value="">
<input type="submit" name="crop" value="Salva" class="salvaImmagine">
</div>
</form>
<div id="salvaImma">
<input type="range" class="cropit-image-zoom-input">
<button class="export">Salva</button>
</div>
</div>
</div>
</div>
Try to give absolute path to that ajax call or if your lib folder at the root of your website then use backslash before the lib
so your url will be :- /lib/ottieniCose.php
It may help you.
I have a php script that fetches items from database and allows users to vote for them, I give each one of those fetched items a (html form) with one (input text field) and a (submit button) to submit an entered score when clicked, and I have a jQuery script in the very same page that inserts the score via that form to the database without refreshing the page, everything seems to be working just fine except the script has one.
This script allows only the very first (html form) in the loop to submit and this first (html form) affects item that does not follow it in the loop, how to make every form attributed to its item?
Alongside this I also want the script to return a notification for the user who submits the score to inform them whether the data is successfully inserted or failed and when success I want to the score that the user submitted to appear for them after the submission
Any help is appreciated, here is my code:
<body>
<div id="items-wrapper">
<?php //function where i fetch items/records from database $items=g et_items_function($page_id); if(!$items){ echo 'There are no items in this page yet!'; }else{ ?>
<div id="item">
<?php //looping the fetched items/records foreach($items as $item){ $_itemid=$ item[ 'item_id']; $_name=$ item[ 'item_name']; $item_file='path/to/items/name-' .$_name. '-id-'.$_itemid. '.jpg'; ?>
<ul id="responds">
<!--i want to append data here-->
</ul>
<img src="<?php echo $item_file; ?>" />
<form action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
<input type="text" name="content_txt" id="contentText" placeholder="Enter score" />
<button id="FormSubmit">Add Score</button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</form>
<?php } ?>
</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
//Ajax request to setItemScore.php
$("#FormSubmit").click(function(e) {
e.preventDefault();
if ($("#contentText").val() === '') {
alert("Please enter some text!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var myData = 'score_value=' + $("#contentText").val();
jQuery.ajax({
type: "POST",
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
dataType: "text",
data: myData,
success: function(response) {
$("#responds").append(response);
$("#contentText").val('');
$("#FormSubmit").show();
$("#LoadingImage").hide();
},
error: function(xhr, ajaxOptions, thrownError) {
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});
});
</script>
</body>
Issue #1
You should always use the .submit() method when a form is being submitted rather than the submit button onclick() for two reasons. 1) When using inputs you can hit enter and submit the form bypassing the entire method. 2) .submit() uses the form allowing you to get children items for that form.
With that in mind I would add a class name to the forms that you know are being submitted through ajax like:
<form class="ajax-form" action="setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>" method="POST">
...
</form>
Then instead of using .onclick() you can use:
$('.ajax-form').submit(function(e){
...
});
Issue #2
In your AJAX request you are using the following line:
url: "setItemScore.php?itemPass=<?php echo $_itemid.'&pagePass='.$_pageid; ?>",
This is always going to set $_itemid to the last iteration from your above foreach() loop instead of the action from the form.
If you use the method mentioned above in issue #1 then you could simply use the forms action property:
url: $(this).prop('action')
Whereas $(this) is the form.
I would like to update session variable.
Let me introduce this in simple example. We get a div with input fields printed out by PHP script, with some values etc...
Example PHP code:
echo '
<div id="few-input-fields">
<input id="Name" size="20" value="' . $_SESSION['name'] . '" />
<br />
<input id="Lastname" size="20" value="' . $_SESSION['lastname'] . '" />
</div>
<span id="save">save</span>
</div>
';
Let's say user edit this input field (id=Name) and type name "Mark" inside it and then press save text.
On click it should save/update session variable, without reloading page AND refresh input fields.
Is that possible? Perhaps with ajax / jquery? And most importantly how ?
Yes, just do a simple AJAX request. With jQuery it would be:
$("#formid").submit(function(){
$.ajax({
type: "POST",
url: "someFileToUpdateTheSession.php",
data: $(this).serialize(),
success: function(){
// Do what you want to do when the session has been updated
}
});
return false;
});
And your PHP:
<?php
session_start();
$_SESSION["name"] = $_POST["name"];
// Add the rest of the post-variables to session-variables in the same manner
?>
Note
You need to add name-attributes to your input-fields.
I am trying to get the value of the hidden field to the next page using PHP's $_POST and submit the function via jQuery, but it does not work.
Part of CSS OOP
<ul>
<li class="selectable" id="cakeType-<?= $cake->id ?>">
<a href="?cakeType=<?php echo ($cake->id); ?>" title="Selecteer">
<?php if ($cake == $order->cakeType){?><span class="checked"></span><?php } ?>
<img src="data/<? echo $cake->id ?>.jpg" alt="" width="50" height="50" /></a>
</li><?php } ?></ul>
My form
<form id="formhide" method="post">
<input name="img" type="text" value="" id="hiddenimg" action="stap2.php"/>
</form>
jQuery
$(function(){
$('a img').click(function(e) {
var photo=$(this).attr('src');
$("#div1 img:last-child").remove()
$('#div1'). append('<img src="' + photo + '" />') ;
$('#hiddenimg').val(photo);
console.log( $('#hiddenimg').val() );
e.preventDefault();
});
$('a.nextStep').click(function() {
if (debug) { alert('submit!') };
$('#formhide').submit();
});
Next page as the form gets submited
$img=$_POST['img'];
echo $img; // the value of my hidden field does not show up i get error msg
$_SESSION['img']=$img;
What's wrong with the above code?
http://api.jquery.com/jQuery.noConflict/
jQuery.noConflict()
This is almost identical problem which I faced a few days ago. I fixed it then, but now it's not working any more. Well, some of it works.
I'm using AjaxFileUpload Plugin to upload files in my WP plugin. This plugin calls uploader.php to process the upload form.
I am able to get the filename (and other data) using $_FILES['uploadFile'], but I'm not able to retrieve $_POST['current_path'] data.
I have a theory though. When I load the interface to upload data, the hidden input field 'current_path' is empty (as is hould be). As I navigate through my folders, the hidden input field is updated using jQuery.
When I hit the upload button, the Ajax File Upload plugin takes the data in the upload form and passes the data to uploader.php through $_POST and $_FILES.
But why am I able to get data from $_FILES and not from $_POST?
Here is my code:
Javascript
//File upload functions
// Remove feedback message on upload click
jQuery('.uploadImage').live('click',function() {
ajaxFileUpload();
});
(...)
//Lets upload the file by using Ajax uploader plugin
function ajaxFileUpload() {
alert(jQuery('input[type=hidden][name=current_path]').val()) //Shows me the correct current path
jQuery.ajaxFileUpload ( {
url:'../wp-content/plugins/wp-filebrowser/uploader.php',
secureuri:false,
fileElementId:'uploadFile',
dataType: 'json',
success: function (data) {
if(data.error != '') {
alert(data.error);
} else {
alert(data.respons);
}
},
error: function (e) {
jQuery('#uploadOutput').addClass('error').html('Error: ' + e).show();
},
complete: function() {
// Update file list
}
}
)
return false;
}
HTML
<form id="uploadForm" enctype="multipart/form-data" action="" method="POST">
<input type="hidden" id="current_path" name="current_path" value="<?php echo $fb->relative_url; ?>" />
<input id="uploadFile" name="uploadFile" type="file" />
<input type="button" class="button uploadImage" value="<?php _e('Upload File') ?>" /> <br />
</form>
PHP
$this->current_path = $_POST['current_path'];
$this->data['error'] = $_FILES['uploadFile']['name']; //Just for testing
$this->data['respons'] = "Filename: ".$_POST['current_path'];
echo json_encode($this->data);
But why am I able to get data from $_FILES and not from $_POST?
Because you are not submitting the form, only the file input element.
It seems to be the plugin's behaviour by design:
In this hacked version, it submits the specified file type of input element only rather than an entire form
The jQuery form plugin can do both, maybe that helps.