Pass second parameter in ajax post request - javascript

I found a solution on internet on how to upload multiple files using ajax and php. In ajax request, I am passing form with files selected to upload, but I need to add one more parameter, but when I am doing it, it is not working. Im not good at php, and I tried pass second parameter in many ways but none worked. How can I pass second parameter so everything will be still working?
html:
<form method="post" enctype="multipart/form-data">
Select files to upload:
<input name="file[]" type="file" multiple>
<input type="button" onclick="upload(this)" value="Upload"/>
</form>
javascript:
function upload(element) {
var formData = new FormData($(element).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
success: function (callback) {
// some code
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
php
<?php
$mysqli = include 'connection.php';
$total = count($_FILES['file']['name']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
for ($i = 0; $i < $total; $i++) {
$name = $_FILES['file']['name'][$i];
$size = $_FILES['file']['size'][$i];
$location = 'uploads/';
$target_file = $location . basename($name);
if (isset($name)) {
if (empty($name)) {
echo 'Please choose a file' . "\n";
} else if (file_exists($target_file)) {
echo 'File already exists.' . "\n";
} else if ($size > 1000000) {
echo 'File is too large' . "\n";
} else {
$tmp_name = $_FILES['file']['tmp_name'][$i];
$statement = $mysqli->prepare("INSERT INTO files (name, subjectId) VALUES (?, ?)");
$str = '1'; // here I would like to set variable using $_POST
$statement->bind_param('ss', $name, $str);
if (move_uploaded_file($tmp_name, $location . $name)) {
if ($statement->execute()) {
echo 'File successfully uploaded :' . $location . $name . "\n";
} else {
echo 'Error while executing sql' . "\n";
}
} else {
echo 'Error while uploading file on server' . "\n";
}
}
}
}
}
So what I would like to get is in javascript add second parameter:
data: formData, mySecondParameter
and then in php when I am binding params for sql, I would like to input there variable that I passed from javascript:
$str = $_POST['contentOfMySecondParameter'];

You can use FormData.append() to add more parameters.
var formData = new FormData($(element).parents('form')[0]);
formData.append('mySecondParameter', contentOfMySecondParameter);
Then use $_POST['mySecondParameter'] in PHP to get this parameter.

Easiest way to do it, add
<input type='hidden' name='contentOfMySecondParameter' value='???' />
to html. You will get $_POST['contentOfMySecondParameter'] in php.

Only one object can be passed there. If you want another variable just append it to formData like this:
var formData = new FormData($(element).parents('form')[0]);
formData.append("mySecondParameter", mySecondParameter);
$.ajax({
...
data: formData,
...

Related

How to only return the value itself from php to javascript?

I've looked around on the internet for answers, but I couldn't find any specific to my situation. As mentioned in the title, i'm trying to retrieve and then display a certain value from mysql database.
Disregarding the security measures which I will add later on, I've managed to retrieve the data, but when I send it back to the javascript and alert it, this value is returned: {"acc_points":"5"}. I would like it it to be just "5", is there any way that I can do this? Thanks!
Here are the codes:
js file
$(document).ready(function() {
$("#viewpoints").click(function() {
{
$.ajax({
type: "GET",
url: "http://127.0.0.1/MP/apppoints.php?callback=?",
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
alert(JSON.stringify(response));
}
})
}
});
});
php file
<?php
header('Content-Type: application/json');
require 'dbcon.php';
session_start();
$acc_id = $_SESSION["acc_id"];
$sql = "SELECT acc_points FROM points WHERE acc_id = '$acc_id'";
$result = mysqli_query($con, $sql);
$acc_points = mysqli_fetch_assoc($result);
if($acc_points != null)
{
$response = $acc_points;
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "Failed. Please try again.";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>

Posting image from php to javascript [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 6 years ago.
I have tried to convert my php code using php to javascript ajax. Could you please correct me what supposed to gone wrong since my php code is still activate.
html code:
<form method="post" enctype="multipart/form-data" action="testadd.php">
<input type="file" name="image" id="image">
<br/>
<input type="submit" name="submit" value="upload" id="submit">
</form>
php:
<?php
if(isset($_POST['submit'])){
if(getimagesize($_FILES['image']['tmp_name']) == false){
echo "Please select an image";
echo "<br/>";
}else{
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
saveImage($name, $image);
}
}
displayImage();
function saveImage($name, $image){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("INSERT INTO images(id, name, image) VALUES(38836929, '$name', '$image') ON DUPLICATE KEY UPDATE image='$image', name='$name'");
$stmt->execute();
}
function displayImage(){
$con = new PDO("mysql:host=localhost; dbname=testimages", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $con->query("SELECT * FROM images");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_OBJ)){
echo '<img height="24" width="24" src="data:image;base64,' . $result->image . '">';
echo '<br/>';
echo $result->name . ' ';
}
}
?>
javascript:
$(document).ready(function(){
$("#submit").click(function(){
var image = document.getElementById("image").value;
alert(" " + image);
if(image == ""){
alert("please select image");
}else{
$.ajax({
type: "POST",
url: "testadd.php",
data: "image=" + image,
success: function(data){
if(data == success){
alert("test");
}else{
alert("fail");
}
}
});
}
return false;
});
});
Could you please check what supposed to be the problem in order to be fixed.
AJAX must have content Type , ProcessData to upload the image files
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
success : function(data){
//Do stuff for ahed process....
}
});

ajax -- add comments asynchronously

I have two php files that handle a commenting system I have created for my website. On the index.php I have my form and an echo statement that prints out the user input from my database. I have another file called insert.php that actually takes in the user input and inserts that into my database before it is printed out.
My index.php basically looks like this
<form id="comment_form" action="insertCSAir.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
<input type="submit" name="submit" value="submit"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
$link = mysqli_connect('localhost', 'name', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
I want users to be able to write comments and have it updated without reloading the page (which is why I will be using AJAX). This is the code I have added to the head tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
However, nothing is happening. The alert() doesn't actually do anything and I'm not exactly sure how to make it so that when the user comments, it gets added to my comments in order (it should be appending down the page). I think that the code I added is the basic of what needs to happen, but not even the alert is working. Any suggestions would be appreciated.
This is basically insert.php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
header("Location:index.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
it also filters out bad words which is why there's an if statement check for that.
<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element)
{
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0)
{
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
if ($result)
{
http_response_code(200); //OK
//you may want to send it in json-format. its up to you
$json = [
'commment' => $newComment
];
print_r( json_encode($json) );
exit();
}
//header("Location:chess.php"); don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
?>
<script>
// this is the id of the form
$("#comment_form").submit(function(e) {
var url = "insert.php"; // the script where you handle the form input.
$.ajax({
type: "GET", //Id recommend "post"
url: url,
dataType: json,
data: $("#comment_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
$('#myElement').append( data.comment );
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
To get a response from "insert.php" you actually need to print/echo the content you want to handle in the "success()" from the ajax-request.
Also you want to set the response-code to 200 to make sure "success: function(data)" will be called. Otherwise you might end up in "error: function(data)".

Can I upload a file using PHP if I ONLY have the absolute path?

What if I have no way of getting the input file:
<input type="file" name="upload" id="upload">
After choosing the file I want to upload, the input field will disappear.
Instead, it will display the absolute path:
C:\users\foo\Desktop\file.zip
C:\fakepath\file.zip
Here's the code I used to get the absolute path:
<script>
$('#upload').on('change',function(){
var filename = document.getElementById("filename").innerHTML;
$.ajax({
type: "POST",
url: "execs/upload.php",
data: { filename: filename},
dataType: "json",
success: function (data) {
alert ("Success")
},
error: function () {
alert ("Failed")
}
});
})
</script>
Will I still be able to upload it in PHP? Most of what I get online is that I will need $_FILES['filename']['tmp_name']. I don't know how I'll get it if I only have the absolute path.
This is the upload.php file:
<?php
$filename = $_POST["filename"]; //C:\users\foo\Desktop\file.zip
$target_dir = "uploads/";
$target_file = $target_dir . $filename;
if(move_uploaded_file($filename, $target_file)){ // $target_file = uploads/file.zip
echo "yes";
}
else echo "no";
?>
When I also checked if the file exists ($filename), it says it does NOT.
Any help would be very much appreciated! Thanks a lot!
You should not use $_POST[] for a file input, use $_FILES[] instead.
For more information check this tutorial.
Please refer to this post:
How to get file name from full path with PHP?
There are two methods:
Using pathinfo.
Using basename.
I prefere pathinfo more.
<?php
$xmlFile = pathinfo('/usr/admin/config/test.xml');
function filePathParts($arg1) {
echo $arg1['dirname'], "\n";
echo $arg1['basename'], "\n";
echo $arg1['extension'], "\n";
echo $arg1['filename'], "\n";
}
filePathParts($xmlFile);
?>
This will return:
/usr/admin/config
test.xml
xml
test
<?php
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"
$file = basename($path, ".php"); // $file is set to "index"
?>
Instead of $_POST use $_FILES as
$filename = $_FILES["upload"];
print_r($filename);
<?php
$uploaddir = "/www/uploads/";
$uploadfile = $uploaddir . basename($_FILES['upload']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['upload']['tmp_name'], $uploadfile)) {
echo "Success.\n";
} else {
echo "Failure.\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
You have $filename = $_POST["filename"]; but change that to:
$filename = $_POST["upload"];
Since you have:
<input type="file" name="upload" id="upload">
So: name="upload"

PHP Ajax returning HTML twice

I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)

Categories

Resources