jQuery Ajax form two submit button in one form - javascript

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,

Related

Send dynamic data to php session after page has loaded

I'm just starting with php and I want to save the value of an HTML input to the php session.
i have tried achieving this using
<html lang="en">
<head>
<title>Log In</title>
</head>
<body>
<?php
session_start();
?>
<input id='email' type='text' placeholder='Email'>
<input type='submit' onclick='logIn()' value='Log In'>
</body>
<script>
function logIn() {
var email = document.getElementById('email')
<?php
$_SESSION['email'] = email;
?>
}
</script>
</html>
but php does not have access to the email variable i created in JavaScript.
I just want to save to the PHP session, data that was entered into an input field of a html site
Use Ajax how suggest from #Jeremy Harris
Script:
function logIn() {
var email = document.getElementById('email');
$.ajax({
url: "session.php",
type: "POST",
data: {
email:email
},
success: function(data){
window.location.href = WHERE YOU WANT;
}
}); }
PHP (session.php):
$email=$_POST['email'];
$_SESSION['email'] = $email;

unable to retrieve $_POST variable in php

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

Can't upload multiple files using ajax

First of all this might be a silly question as there are many topics available on this but seriously I am not being able to get it straight and understand how to make it work.
WHAT I AM TRYING TO DO
I am trying to upload multiple files using AJAX and PHP.
PROBLEM
I cant figure out how to pass the data to the PHP script using AJAX.
I don't want to use a form and a submit button for uploading.
Tried using a form and submitting it using jQuery still couldn't make
it.
HTML
<div id="content">
<div id="heading">Upload your files seamlessly</div>
<a href="#"><div id="upload" class="button" title="Upload your files"><i class="fa fa-cloud-upload fa-align-center" aria-hidden="true"></i>
</div></a>
<a href="view.php"><div id="view" class="button" title="View all files on my cloud"><i class="fa fa-eye fa-align-center" aria-hidden="true"></i>
</div></a>
</div>
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
</form>
JS
<script type="text/javascript">
$(document).ready(function(){
$('#upload').click(function(){
$('input[type=file]').click();
return false;
});
$("#uploadfile").change(function(){
//submit the form here
$('#fileupload').submit();
});
});
</script>
PHP
<?php
if(isset($_FILES['uploadfile'])){
$errors= array();
foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['uploadfile']['name'][$key];
$file_size =$_FILES['uploadfile']['size'][$key];
$file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
$file_type=$_FILES['uploadfile']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
//$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="storage";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}
else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
//mysql_query($query);
}
else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
Any help would be appreciated.
This is a very simple example of what you want to do.
HTML
Wrap your inputs within a form. Why? Because it is the easiest way to do it.
<form action="process.php" method="post">
<input type="file" multiple name="uploadfile[]">
<input type="submit" value="Upload">
</form>
JavaScript
Attach an onsubmit event handler to your form. Use $.ajax() to send a POST request.
Pass your form element i.e. this into the constructor of a FormData object and use it as your data when you send the request as shown below. You need to make sure that you set processData and contentType as false also for this to work.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
// send request
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this), // important
processData: false, // important
contentType: false, // important
success: function (res) {
alert(res);
}
});
});
});
PHP (process.php)
Let's clean up your PHP.
<?php
// always a good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);
$dir = './storage';
$errors = [];
if (isset($_FILES['uploadfile'])) {
$files = $_FILES['uploadfile'];
// create directory if it does not exist
!is_dir($dir) && mkdir($dir, 0700);
// validate & upload files
foreach (array_keys($files['tmp_name']) as $key) {
$file = [
'name' => $files['name'][$key],
'size' => $files['size'][$key],
'tmp_name' => $files['tmp_name'][$key],
'type' => $files['type'][$key],
'error' => $files['error'][$key]
];
// skip if no file was given
if ($file['error'] === UPLOAD_ERR_NO_FILE) {
continue;
}
// get file extension
$file['ext'] = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
// generate a unique name (!)
$file['name'] = uniqid() . '.' . $file['ext'];
// validate
if (!file_exists($file['tmp_name']) ||
!is_uploaded_file($file['tmp_name']) ||
$file['error'] !== UPLOAD_ERR_OK) {
$errors[$key] = 'An unexpected error has occurred.';
} elseif ($file['size'] > 2097152) {
$errors[$key] = 'File size must be less than 2 MB';
// upload file
} elseif (!move_uploaded_file($file['tmp_name'], $dir . '/' . $file['name'])) {
$errors[$key] = 'File could not be uploaded.';
}
}
}
if ($errors) {
print_r($errors);
} else {
echo 'no errors';
}
?>
(!) Do keep in mind that uniqid() is actually not unique.

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);
}
?>

Using HTML tags with Javascript / jQuery

I have some code that is working but I would like to add two things to it that I don't know how to do.
It's a simple form that send data to my database (jQuery / AJAX) and then display the data on the web page.
Problem 1:
When I refresh the page, all the message are displayed on separate lines (which is what I want) but when I add new messages and click on the submit button, all the new messages get displayed on the same line. Is there a way I could put a or force the comment to be displayed on a new line ?
Problem 2:
When I refresh index.php, only 10 messages are displayed and that's good because I used a "LIMIT 0, 10" on my query. When I type a new message and click on the button to submit to the database, the message list is "updating" by itself but ADD a new message to the list instead of replacing the 10th message by the new one.
index.php
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
<title>Untitled Document</title>
<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function sendMessage()
{
$.ajax({
url: "ajax.php",
type: "POST",
data: {comment : document.getElementById('message').value},
dataType:"html",
success: function(data, textStatus, xhr) {
$("#output").append(document.getElementById('message').value);
document.getElementById('message').value = "";
}
});
}
</script>
</head>
<body>
<form name="addComment">
<input type="text" name="message" id="message" />
<input type="button" name="submitBtn" id="submitBtn" value="Envoyer" onclick="sendMessage();" />
</form>
<div id="output">
</div>
<?php
include("class.php");
$object1 = new Shootbox();
try {
$object1->showMessage();
}
catch(Exception $e) {
echo "Exception : ".$e->getMessage();
}
?>
</body>
</html>
ajax.php
<?php
mysql_connect("localhost", "root", "root");
mysql_select_db("PFtest");
$message = $_POST['comment'];
if (strlen($message) > 0)
{
mysql_query("INSERT INTO comments VALUES ('NULL', '".$_POST['comment']."', CURRENT_TIMESTAMP)");
echo "Message enregistré !";
}
elseif(strlen($message) < 0)
{
echo "Nothing here";
}
?>
class.php
<?php
class Shootbox {
public function showMessage() {
mysql_connect("localhost", "root", "root");
mysql_select_db("PFtest");
$query = mysql_query("SELECT * FROM comments ORDER BY date DESC LIMIT 0 , 10");
if(mysql_num_rows ($query)>0){
while($result = mysql_fetch_object($query)){
echo $result->message."<br />";
}
}
else{
throw new Exception("Aucune donnée dans la base de données");
}
}
}
?>
Just some speculation on what the issue might be for each of your problems.
Problem 1 - The reason the messages are shown on separate lines only on refresh is because you're adding the break tag on the server side in your showMessage function on page load only.
You're missing the break tag in your JS for when you add a new message on submit.
So for your JS which is what you use when adding a new message after the AJAX call put the break tag on the end.
$("#output").append(document.getElementById('message').value + '<br>');
Problem 2 - It's not replacing the 10th message on submit because you're appending to the output. So you need to remove the oldest message after appending.
You could simply append a line break. However, to make better html, add a p (paragraph) element around your new message. Its display defaults as block, so no need for new lines:
The jquery:
$("#submitBtn").click(function () {
$("#output p:last-child").html($('#message').val());
$.ajax({
url: "ajax.php",
type: "POST",
data: {
comment: document.getElementById('message').value
},
dataType: "html",
success: function (data, textStatus, xhr) {
$("#output").append(document.getElementById('message').value);
document.getElementById('message').value = "";
}
});
});
The body:
<body>
<form name="addComment">
<input type="text" name="message" id="message" />
<input type="button" name="submitBtn" id="submitBtn" value="Envoyer" />
</form>
<div id="output">
<?php
include("class.php");
$object1 = new Shootbox();
try {
$object1->showMessage();
}
catch(Exception $e) {
echo "Exception : ".$e->getMessage();
}
?>
</div>
</body>
</html>
For the second problem, the php should change slightly:
if(mysql_num_rows ($query)>0){
while($result = mysql_fetch_object($query)){
echo "<p>" . $result->message."</p>";
}
}

Categories

Resources