unable to retrieve $_POST variable in php - javascript

After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?
My javascript
function uploadFile() {
var input = document.getElementById("picture");
file = input.files[0];
newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
console.log(newFileName);
if (file != undefined) {
formData = new FormData();
if (!!file.type.match(/image.*/)) {
formData.append("newFileName1", newFileName);
$.ajax({
url: "upload_file.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {}
});
} else {
alert('Not a valid image!');
}
} else {
alert('Input something!');
}
}
My php
<?php
$dir = "im_ges/";
$file_name = $dir. $_REQUEST["newFileName1"].".jpg";
echo $file_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>

Try this sample code
form.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function (responce) {
alert(responce);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<input name="name" value="First Name"><br>
<input name="file" type ="file" ><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
create post.php
echo "Name Value : ".$_POST["name"]."\n\n";
echo "\n File Details\n";
print_r($_FILES);
This will alert the values from form

If you get the file name in your custom php controller the you can use
$target_dir = "uploads/";
$filename = "phonenumber.png";//Set here the new file name which you passed through ajax
$target_file = $target_dir .$filename;
// test here the file is moved or not,
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
then update db with the $filename
}
or i changed the some code in above mentioed and add a text filed to enter a phone number and the selected file moved to the taget with the value enterd in the
text field with name phone can you check is it usefull for you .
form.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function (responce) {
alert(responce);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<input name="name" value="First Name"><br>
<input name="phone" value=""><br> <!-- new field -->
<input name="file" type ="file" ><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
post.php
<?php
echo "Name Value : ".$_POST["name"]."\n\n";
echo "\n File Details\n";
print_r($_FILES);
$target_dir = "uploads/";
$uploadOk = 1;
$filename = $_FILES['image']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$target_file = $target_dir . $_POST["phone"].$ext; // here we change the file name before uploads
// test here the file is moved or not,
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
}
?>
create a folder in the root with name "uploads" and give full permison

Related

jQuery Ajax form two submit button in one form

I have 2 button in one form. When I click the first or second button, both write example an alert, but the Ajax request doesn't run. I need a form, because i would like to upload images. I don't know what is the problem.
page.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Ajax two submit in one form</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<form id="animal-upload" method="post" enctype="multipart/form-data">
<span>Name:</span>
<input type="text" name="animalname" id="animalname">
<span>Image:</span>
<input type="file" name="imagefile" id="imagefile">
<button type="submit" name="publish" id="publish">Publish</button>
<button type="submit" name="save" id="save">Save</button>
</form>
<script>
$(document).ready(function() {
$('#animal-upload').on('submit', function() {
return false;
});
$('#publish').click(function() {
alert("Test");
});
$('#save').click(function(e) {
e.preventDefault();
$.ajax({
url: "animal-upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
});
});
</script>
</body>
</html>
animal-upload.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
mysqli_set_charset($connect,"utf8");
$status = '';
$animalname = $connect->real_escape_string($_POST["animalname"]);
if ($_FILES['imagefile']['name'] != '') {
$extension = end(explode(".", $_FILES['imagefile']['name']));
$allowed_type = array("jpg", "jpeg", "png");
if (in_array($extension, $allowed_type)) {
$new_name = rand() . "." . $extension;
$path = "animals/" . $new_name;
if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $path)) {
mysqli_query($connect, "INSERT INTO animals (animalname,image) VALUES ('".$animalname."','".$path."')");
$status = 'Successful!';
}
} else {
$status = 'This is not image file!';
}
} else {
$status = 'Please select image!';
}
echo $status;
?>
After trial and errors I found the script work if you change this line :
data: new FormData($("#animal-upload")[0]),
Because that selects the form object.
You may consider some security tips :
Don't divulge your password in public
Don't let your database users connect without passwords
Make a user with strict minimum privileges just for the purpose to connect to your database from PHP scripts (it's called the principle of least privileges)
Rename your uploaded file
For the file upload to work :
Make sure you have the right permissions on the directory pointed by
upload_tmp_dir in php.ini file
You may need to check that your file size doesn't exceed the memmory_limit directive too
good luck,

jquery.ajax, success and done function is not returning anything

I am a wordpress user and try to update the database using jquery.ajax. My code updates the database but the success function doesn't return anything to html div tag. Here are some portions of my code:
PHP Code:
$connect = mysqli_connect(HOST, USER, PASS, NAME);
if(mysqli_connect_errno()){
$msg = "Connection With Database is not Successful. Error: ".mysqli_error();
echo $msg;
die();
}
$nam = $_POST['name'];
$eml = $_POST['email'];
$entry = "INSERT INTO `table` (name, email,) VALUES ('$nam', '$eml')";
if(!mysqli_query($connect, $entry)){
$msg = "Error while submitting Your Data. Error: ".mysqli_error();
echo $msg;
die();
}
$msg = "Your data submitted successfully";
echo $msg;
mysqli_close($connect);
?>
HTML Code:
<form method="POST" id="data_form">
<input type="text" name="name" id="name" placeholder="Full Name" />
<br>
<input type="email" name="email" id="email" placeholder="Email Address" required />
<br>
<button type="submit" id="submit">Submit</button>
</form>
<div id="output"></div>
jQuery Code:
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false,
success: function(result){
$("#output").html(result);
}
});
});
});
I also used 'done' instead of 'success' but didn't work.
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false
}).done(function(result){
$("#output").html(result);
});
});
});
Actually I am trying to print the $msg variable from the php file to the 'output' div tag.
Any help would be greatly appreciated.

Sending a file from form to email

I am trying to figure out how to send a file that containts things like images to text files, etx from a form submission through ajax to my php file to send into an email. I am trying to format it the way I have my other data in ajax and php email, but I can tell the form stops right away in my ajax. It doesn't even send through to my php, but I am not sure if I have the email part right either.
This is what I tried so far. I tried to delete as much obsolete code as possible, but still include enough to give a good feeling for what I am trying to do.
How can I make this file attach/send into an email from a form through AJAX to my php email
<form action="" autocomplete="on" method="POST" id="project-information-form" enctype="multipart/form-data">
<input type="text" class="input-borderless" id="project-name" name="name" placeholder="Your Name">
<input type="email" class="input-borderless" id="project-email" name="email" placeholder="Email Address">
<input type="number" class="input-borderless" id="project-number" name="phone" placeholder="Phone Number">
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple>
<label for="file"><span id="file-upload-image"><img src="/icons/white-upload.png" height="25px" width="25px"></span>File Upload</label>
<input type="submit" id="submit-project" class="submit-project-button" value="Send Project Inquiry">
</form>
AJAX
$("#submit-project").on("click", function(event) {
// event.preventDefault();
var project_name = $("#project-name").val();
var project_email = $("#project-email").val();
var project_number = $("#project-number").val();
var uploaded_file = $("#file").val();
submitHandler: function(form) {
console.log(form);
$.ajax({
url: "email-project.php",
type: "POST",
data: {
"project_name": project_name,
"project_email": project_email,
"project_number": project_number,
"file": project_file
},
success: function(data) {
//console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to send email!");
alert(data);
} else {
}
},
PHP Page for email
ini_set('display_errors', 1);
error_reporting(E_ALL);
$project_name = $_POST['project_name'];
$project_email = $_POST['project_email'];
$project_number = $_POST['project_number'];
$project_file = $_POST['file'];
$to = '';
$subject = '';
$message = '
<html>
<head>
<title>Project Inquiry Form Sent</title>
</head>
<body>
<p>There has been a Project submitted. Here are the details:</p><br>
<p>Name: '. $project_name .'</p>
<p>Email: '. $project_email .'</p>
<p>Phone Number: '. $project_number .'</p>
<p>The client uploaded a file ' .$project_file.'.</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' .$project_email . "\r\n";
if (!empty($project_email)) {
if (filter_var($project_email, FILTER_VALIDATE_EMAIL)) {
//Should also do a check on the mail function
if (mail($to, $subject, $message, $headers)) {
echo "Your email was sent!"; // success message
} else {
echo "Mail could not be sent!"; // failed message
}
} else {
//Invalid email
echo "Invalid Email, please provide a valid email address.";
}
} else {
echo "Email Address was not filled out.";
}
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method sends the form data to the server, then a script on the server handles the upload.
Here's an example using PHP. Take a look at this example.
Credit goes here -> jQuery AJAX file upload PHP
$('#submit-project').on('click', function() {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'email-project.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,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});

How to call output of a php page in an html page in a specific div?

This is my html code
<html>
<body>
<form name="form1" action="php1.php" method="post">
<input type="text" name="text1">
<input type="submit" name="submit1">
</form>
<div id="div1">
</div>
</body>
</html>
This is my php1.php code
<?php
if(isset($_POST['submit1']) && ($_POST['text1'])=="text"){
echo "hello";
}
?>
If I want to call the output of php1.php i.e., hello, in html div1 what to do ?
#Uzumaki, I've edited my html code like this, but its not working, here is my code.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
$("form#postit").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "hello.php",
type: 'POST',
data: formData,
async: false,
success: function (data)
{
// $("#div1").append(data); // or
$("#div1").html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
</head>
<body>
<form name="form1" method="post" id="postit">
<input type="text" name="text1">
<input type="submit" name="submit1">
</form>
<div id="div1">
</div>
</body>
</html>
Since you didn't mention via jquery or ajax I am assuming you are going with a simpler old fashioned way So here is the code
SEND YOUR MESSAGE BACK TO HTML PAGE LIKE THIS
$msg = "hello"
header("Location: your_html_page.html?msg=".$msg);
IN HTML DO THIS
<div id="div1">
<?php
error_reporting(0);
echo $_GET['msg'];
?>
</div>
USING JQUERY :
Post the data to php
$.post("your_php_page.php",{data:data},function(returned_data_from_php){
$("#div1").append(returned_data_from_php); // or
$("#div1").html(returned_data_from_php);
});
Using Ajax
$("form#postit").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: "your_php_page.php",
type: 'POST',
data: formData,
async: false,
success: function (returned_data_from_php)
{
$("#div1").append(returned_data_from_php); // or
$("#div1").html(returned_data_from_php);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
PHP
what ever you want to return from php it should be echo and there are many ways to do that
(Single string) echo "Success";
(Multiple Strings) echo $msg1.$msg2;
(Array data)
for example ...
$data = array();
$i = 0;
while($numbs = mysql_fetch_array($result))
{
$row_numb = $numbs['id'];
$data[$i] = $row_numb;
$i++;
}
echo json_encode($data);
// this will pass a json type object to the java script
When you get to javascript you want to access all the elements of the array one by one well that's easy too
JAVASCRIPT
parsed_it = JSON.parse(data); // data is the json type you got from your php
so parsed_it[0],parsed_it[1],parsed_it[2] and so on you can access all the data
hope it helps !!
Put the PHP into your HTML file where you want the result. Be sure your file is named something.php and that you have a PHP processor on the server.
<html>
<body>
<form name="form1" action="php1.php" method="post">
<input type="text" name="text1">
<input type="submit" name="submit1">
<div id="div1">
<?php
if(isset($_POST['submit1']) && ($_POST['text1'])=="text"){
echo "hello";
}
?>
</div>
</body>
</html>
You may use AJAX to dynamically load script output:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get
You may also consider using jQuery to simplify your code:
http://api.jquery.com/jquery.get/

html how to send user field input as a json object

I am having a form in which two input's are defined username and password, but i want to send this input as a json object to server, here is my html form
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="MY Form" action="Login" method="post">
userid<input type="text" name="username" id="username"> <br>
password<input type="password" name="password" id="password">
<br> <input type="submit" name="button1" value="login">
</form>
</body>
</html>
now how can i send this data as a json object, i have searched that i can use jquery or ajax but i am finding difficult to implement it, can anyone please tell me how can i send it as a json.
You could send your data using .serialize() method.
$(function() {
$('input[name="button1"]').click(function() {
$.post(your_url, $(this).closest('form').serialize(), function(data) {
console.log(data);
});
});
});
It is the same effect with using an object as data:
$(function() {
$('input[name="button1"]').click(function() {
var data = {
username: $('#username').val(),
password: $('#password').val(),
};
$.post(your_url, data, function(data) {
console.log(data);
});
});
});
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
// do submit part here
});
As memory serves you can only send data back to the server via POST or GET using javascript. You would probably have to serialize the JSON before sending.
see https://stackoverflow.com/a/912247/1318677 for an example on how to serialize a JSON object.
Assuming you have JSON2 and Jquery included, The code may look like this
// create a listener on the submit event
$('form').on('submit', function (e) {
e.preventDefault();
// gets the data that will be submitted
var data = $(this).serializeArray(),
// the ajax url
url = './request/url';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data), //stringify
dataType:'json',
complete : function () {
// do what you want here
}
});
return false;
});
Be aware, untested script. Also make sure DOM exists before calling the script above. Which can be achieved by adding your scripts just before the </body> closing tag or use $(document).ready(/*script here*/);
use this one
add id button1
html
<form action="Login" method="post" name="MY Form">
userid<input id="username" name="username" type="text" /><br />
password<input id="password" name="password" type="password" /><br />
<input id="button1" name="button1" type="submit" value="login" />
</form>
javascript
$("#button1").click(function() {
formData = {
username: username,
password: password
}
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "http://localhost/login.php",
dataType: "json",
data: formData,
success: function(data) {
console.log(data);
//success handler
},
error: function(data) {
//error handler
}
});
});
php
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_POST["username"]) && isset($_POST["password"])) {
$username = $_GET['username'];
$password = $_GET['password'];
// get a product from products table
$result = mysql_query("SELECT *FROM users WHERE username = '$username' AND password = '$password' ");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$user = array();
$user["userId"] = $result["userId"];
$user["name"] = $result["name"];
// success
$response["success"] = 1;
// user node
$response["user"] = array();
array_push($response["user"], $user);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>

Categories

Resources