Dynamically adding picture using php - javascript

I am having trouble getting a picture stored on a server and its path in my database, then i want to retrieve and showe it on the same page. So far I have the add photo button which onchange triggers the photo to a series of checks then stores it. However, because of this set up the page changes, but there's other info on the page that needs to be inputted. I am assuming I have to create some ajax function, which I have below, but it doesn't work. Here's what I have so far.
<div class="step1-container">
<h3 class="steps-detail">Step 1:</h3>
<p>Upload a picture for you new friends</p>
<form action="../Controllers/fileupload_controller.php" method="post" enctype="multipart/form-data">
Select image to upload:
<label class="upload-cov">
<input type="file" name="fileToUpload" id="fileToUpload">
<span>Add Photo</span>
</label>
<input type="submit" id="photoSubmit" style="display:none">
</form>
</div>
<div class="profile-pix">
</div>
php:
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$_POST['UserId'] = $_SESSION['logname'];
$_POST['ProfilePix'] = $target_file;
if (storeData($_POST, $table, $cxn)) {
$result = $target_file;
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
js:
$("#fileToUpload").change(function() {
$('#photoSubmit').click();
});
ajax:
$('#fileToUpload').on('change', 'input', function(e) {
e.preventDefault();
var str = $('#fileToUpload').serialize();
$.ajax({
type: 'POST',
url: '../Controllers/fileupload_controller.php',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});

Since you want to send a file as multi-part/form-data to the server using ajax, the easiest way will be to send the form data of the form.
Example code:
//from within the on change event listener
$.ajax({
//pass the form element to the form data object
data: new FormData($(this).parents('form'))
})

Related

multiple file upload using same form but different input fields using jquery php

I have searched for this thing on stack overflow, I was unable to find a relevant answer to my issue. Please have a look at the code I am using to fetch data and throw it to a php file and upload files to the respective folders and store their link to database. But I am not able to store data. It shows "unable to upload data."
Jquery file:
$(document).on('click','#modalMenu', function(){
var pagename = $("#pagename").val();
var page = 'modalMenu';
var menuname = $("#menuname").val();
var nav = $("#nav").val();
var content = CKEDITOR.instances['content'].getData();
var form_data = new FormData();
var file_data = $('#file').get(0).files[0];
var logo = $('#logo').get(0).files[0];
form_data.append('file', file_data);
form_data.append('logo', logo);
form_data.append('pagename', pagename);
form_data.append('menuname', menuname);
form_data.append('content', content);
form_data.append('nav', nav);
form_data.append('page', page);
$.ajax({
url: 'insert.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
method: 'POST',
success: function(data){
alert(data);
location.reload();
}
});
});
form on some page
<form method="post" role="form" enctype="multipart/form-data" action="javascript:;">
<input type="text" class="form-control" placeholder="Page Name" id="pagename" name="pagename" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Nav Name" id="nav" name="nav" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Menu Name" id="menuname" name="menuname" style="max-width:25%; display:inline" />
<input type="file" name="logo" id="logo" title="Menu Logo" class="form-control" style="max-width:20%; display:inline"/>
<input type="text" class="form-control" placeholder="Summery Part.. Please make it crisp" id="content" name="content" style="max-width:30%; display:inline" />
<script>
var editor = CKEDITOR.replace( "content", {
uiColor: "#ffffff",
filebrowserBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html",
filebrowserImageBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Images",
filebrowserFlashBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Flash",
filebrowserUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files",
filebrowserImageUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images",
filebrowserFlashUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash"
});
CKFinder.setupCKEditor( editor, "../" );
</script>
<input type="file" name="file" id="file" class="form-control" style="max-width:25%; display:inline"/>
<input type="submit" id="modalMenu" name="modalMenu" class="btn btn-success" align="right" value="+" />
</form>
insert.php file
$pageName=$_POST['page'];
if($pageName=='modalMenu'){
$pagename=$_POST['pagename'];
$menuname=$_POST['menuname'];
$nav=$_POST['nav'];
$content=$_POST['content'];
$error=$_FILES['file']['error'];
if($error!=0)
{
echo "Error with File data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$fname=$_FILES['file']['name'];
$ftype=$_FILES['file']['type'];
$fsize=$_FILES['file']['size'];
$ftname=$_FILES['file']['tmp_name'];
$target="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target);
if($ans)
{
$error=$_FILES['logo']['error'];
if($error!=0)
{
echo "Error with Image Data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$logo_name=$_FILES['logo']['name'];
$logo_type=$_FILES['logo']['type'];
$logo_size=$_FILES['logo']['size'];
$logo_tname=$_FILES['logo']['tmp_name'];
$target2="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target2);
if($ans)
{
//save info to database
$con=mysql_connect("localhost","root","");
mysql_select_db("rcg_db",$con) or die (mysql_error());
$target=addslashes($target);
$query="INSERT INTO `modalmenu`(`pagename`, `nav`, `menuname`, `menulogo`, `content`, `readmore`) VALUES ('$pagename','$nav','$menuname','$target' ,'$content','$target2');";
$n=mysql_query($query);
if($n==1)
{
echo "File upload successful! Data is added. Please wait while page reloads";
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait..";
}
}
}
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait.";
}
}
}
Thank you in advance. In case I am not using a good way of coding please do recommend and resolve the issue.
From what I understand you want to send the ajax into PHP but PHP cant save it?
Ill give you an example
jQuery
$(#modalMenu).on('click',function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var age = $("#age").val();
$.ajax({
url: 'insert.php', //point to server-side PHP script
dataType: 'json',
type: "POST",
data:{
"fname" : fname,
"lname" : lname,
"age" : age,
"save" : true
},
success: function(yes){
if(yes.success == true){
window.location.reload(true);
}
}
});
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "INSERT INTO beneficiary (fname, lname, age)
VALUES ('$fname','$lname','$age')";
$result = mysql_query($sql);
echo json_encode(array(
"success" => true,
));
refer the below link, i think this is useful for you
http://www.codexworld.com/upload-multiple-images-using-jquery-ajax-php/

How to extract URL and store it to MySQL?

I have a textarea in which user enter url and link is extracted successfully and appended to a div. How can I store that extracted data into database as the extracted data is in a div not in any input?
<textarea id="get_url" placeholder="Enter Your URL here" class="get_url_input" spellcheck="false" ></textarea>
<input type="button" value="Share">
<div id="results">
</div>
Extracted data is shown in result div, do I need to store the response into any hidden input and check if it is empty while clicking on share button?
There are several ways to do this but I would recommend using:
Ajax and JQuery
In your JavaScript file add:
var data = $('#div id').text();
$.ajax ({
url: "www.websitename.com/addurl.php",
type: 'POST',
data: { urltoadd: data},
success: function (response){
If (response = 'successful'){
return true;
}else {
return false;
}
}
});
Now in your addurl.php file:
<?php
$urltoadd = $_POST ['urltoadd'];
... add Code to save $urltoadd in your database.
If (file was added successfully){
echo 'successful';
}else {
echo 'failed';
}
? >
On form submit you can bind a function and in that functiom
using jquery you can do $('#result').text()

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

How to use jQuery AJAX with PHP to submit a form into a mySQL database with using an <a> tag?

What I am trying to do is create a "save" button for my website which saves specific posts and comments, exactly like the "save" button on Reddit. For now I am trying to self teach jQuery AJAX and attempting to figure out how to submit data to the database without having to reload the whole page. What I am attempting to do here is save a string by submitting it to a table called "Saved" when I click on "save".
HTML
<div id="message1">
<div id="pmessage"><p><?php echo $myComment;?></p></div>
Save
Edit
Hide
</div>
<form action="ajaxexample.php" method="post" style="display: none" id="1234">
<input type="hidden" name="message" id="message" value="<?php echo $myComment; ?>">
</form>
jQuery
$('a.Save').click(function () {
if ($(this).text() == "Save") {
$("#1234").ajax({ url: 'ajaxexample.php', type: 'post', data: 'message' });
$("a.Save").text("Unsave");
} else {
$("a.Save").text("Save");
}
});
PHP5.3
$message = $_POST['message'];
$query = "INSERT INTO saved (comment) VALUES (?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $message);
$statement->execute();
$statement->store_result();
$submissionWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($submissionWasSuccessful)
{
header ("Location: index.php");
}
$myComment = "This is my message!";
As of now all I am trying to do is submit the message "This is my message!" into the database table "Saved". What is wrong with my code? Why can I not submit the data to the table and how can I fix it? Thanks in advance!
Submit form when someone clicks on a.Save
$('a.Save').click(function (e) {
e.preventDefault();
$("#1234").submit();
});
submit handler on form#1234
$("#1234").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajaxexample.php',
data: $("#1234").serialize(),
success: function(data)
{
// data stores the response from ajaxexample.php
// Change the html of save by using $("a.Save").html("Unsave");
}
});
});
Serialize automatically makes a query string.
$(".save").bind("click",function(e){e.preventDefault();
$.ajax({
url : $("#1234").attr("action"),
type : "POST",
data : $("#1234").serialize(),
success : function(data){},
fail : function(data){},
});
});

image button - no page change

I'm trying to call a php file without refreshing the page. The code executes the php file, but the value toid is not being passed along. If i manually query the page then it works fine. The other issue im having is the button needs to be an image with the path src="{ROOT_PATH}mchat/quote.gif"
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo {mchatrow.MCHAT_USERNAME}; ?>">
<div id="button_block">
<input type="submit" id="button" value="Enter">
</div>
</form>
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
$.ajax({
type: "POST",
url: "randomquote.php",
data: "toid=" + toid,
});
});
});
</script>
Any ideas?
When you say "if i manually query the page then it works fine", does that mean hitting the endpoint directly like
http://yoursite.com/randomquote.php?toid=239439
Have you tried sending the data as an object (like this):
$.ajax({
type: "POST",
url: "randomquote.php",
data: { toid: toid }
});
That may do the trick.

Categories