I'm trying to upload an image with some other variables and on the form submit, do my php code to save the image to the users profile_picture table.
I want to make my image upload in the same form as saving my data changes.
This is a picture of what it looks like so you can have a better understanding :
I did it before where I used the POST method, but for AJAX i'm not sure how to do it.
My Javascript code is (note that this doesn't work, I just tried having a go - It returns Illegal invocation in the console.log) :
<script>
function updateMyAccount() {
var fd = new FormData($("#fileinfo"));
var password = document.getElementById("myAccountNewPassword").value;
var profilePicture = document.getElementById("myAccountNewProfilePic").value;
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: {
SaveAccountChanges: true,
securePassword_Val: password,
fd
},
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
});
return false;
}
</script>
My PHP code is :
//My account AJAX POST
if(($_POST['SaveAccountChanges']) == true & isset($_POST['securePassword_Val']))
{
$member_config->doUpdateAccountInfo($con);
}
Then my function to upload the image and save it to the database :
function doUpdateAccountInfo($con)
{
//Upload users image to our /uploads directory
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
$save_to_database = ("uploads/" . $_FILES["fileToUpload"]["name"]);
$normalPassword = mysqli_real_escape_string($con, $_POST["securePassword_Val"]);
$pwd = password_hash($normalPassword, PASSWORD_DEFAULT);
$username = $_SESSION["username"];
if(!empty($_FILES['fileToUpload']) & !empty($_POST['securePassword_Val']))
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {} else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
$query = "UPDATE users SET password = '$pwd', profile_picture = '$save_to_database' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password and profile picture</i></b>!</p></div>';
//echo '1';
}
else if (empty($_FILES['fileToUpload']) & empty($_POST['securePassword_Val']))
{
$query = "UPDATE users SET password = '$pwd' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>profile picture</i></b>!</p></div>';
//echo '1';
}
else if (empty($_POST['securePassword_Val']) & !(empty($_FILES['fileToUpload'])))
{
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { echo 'Successfully uploaded image'; } else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
$query = "UPDATE users SET profile_picture = '$save_to_database' WHERE username='$username'";
$result = mysqli_query($con, $query) or die('error');
echo '<div class="panel -success"><div class="panel-body"><p>You have successfully updated your <b><i>password</i></b>!</p></div>';
//echo '1';
}
else if (empty($_POST['securePassword_Val']) & empty($_FILES['fileToUpload']))
{
$result = mysqli_query($con, $query) or die('error');
//echo '<div class="panel -danger"><div class="panel-body"><p>You have failed to update your <b><i>password and profile picture</i></b>!</p></div>';
echo '0';
}
else
{
//echo '<div class="panel -danger"><div class="panel-body"><p>An error occured!</p></div>';
echo '0';
}
}
I have looked a the link that was posted and now have this code :
<script>
function updateMyAccount() {
var fdata = new FormData($("#data"));
fdata.append("securePassword_Val",$("#myAccountNewPassword").val());
fdata.append("SaveAccountChanges",true);
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data:
//SaveAccountChanges: true,
//securePassword_Val: password,
fdata
,
async: false,
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
How would I go about making the image upload through this method ?
Normally, I wouldn't answer this question because it gets asked many times. But I see few issues in your code, so I'm going to make an attempt.
JavaScript
(1) Ensure that you have included jQuery script
(2) Ensure that you have a form element (preferrably give it an ID attribute e.g. myform for referencing) and all your inputs have name attributes.
(3) Pass the native form element (not jQuery object) into FormData constructor. This will allow you to pass all the input elements with name attributes from your form -- so you don't need to manually add them. Exception is your SaveAccountChanges field that you want to pass, here you need to use FormData.append().
(4) Set $.ajax data option to only the FormData object. Set contentType and processData options to false.
function updateMyAccount() {
// document.getElementById('myform') === $("#myform")[0] === myform
var fd = new FormData($("#myform")[0]);
fd.append('SaveAccountChanges', true);
$.ajax({
type: "POST",
url: "includes/form_submit.php",
data: fd,
contentType: false,
processData: false,
success: function(msg){
if(msg == 1) {
update_myAccount_success();
} else {
general_error_forms();
}
},
});
return false;
}
And this should be the minimum that you need on the client-side. When debugging, use your browser's web tools.
PHP
(6) Turn on your PHP error reporting.
(7) Learn the difference between && and & -- they are not the same.
(8) Because you are uploading using FormData, you need a stronger validation for your upload fields. $_FILES['fileToUpload'] will not be empty even when you don't select a file.
Related
I am trying to access a database and delete a review of a user, I have a method that I pass the user's ID and the ID of the review. This method functions properly using both the SQL command as well as when I call hard-coded variables, however, when I pass the code via AJAX my code says it completed successfully but does not actually do anything. Is there something special about the variables that are passed via AJAX?
This is my method:
public function deleteRating($userid, $reviewID)
{
echo "this is idUsers(IdUsers) = ".$userid." this is reviewID (ID)".$reviewID;
$conn = $this->connect("ratings");
$sql = "DELETE FROM ratedmovies WHERE IdUsers=? AND ID=?";
if(!$stmt = $conn->prepare($sql))
{
echo "False";
}
else
{
$stmt->bind_param("ss", $userid, $reviewId);
if(!$stmt->execute())
{
echo "Failed to delete";
}
else
{
echo "Sucessfull Deletion";
}
}
}
This is the code that calls the method:
<?php
session_start();
include "../Model/Includes/autoLoadCont.inc.php";
$reviews = new Review;
$ratingID = json_decode($_POST['ratingID']);
$user = $_SESSION['userId'];
$reviews->deleteRating($user, $ratingID);
?>
and this is the ajax that calls that function:
var deleteBtns = document.querySelectorAll(".deleteRating");
deleteBtns.forEach(function(button)
{
button.addEventListener("click" , function()
{
$.ajax({
type: "POST",
url: "Controller/deleteReview.php",
data: {ratingID:button.id},
success: function(result)
{
alert(result);
}
});
});
button.id;
});
I'm running a script which is supposed to send a user ID number to a database. The database grabs a bunch of image IDs from whichever row has the matching user ID, then goes to a different table and grabs the image URLs which match the image IDs. Then it returns the URLs.
The PHP script runs fine on its own, it returns the correct URL in either straight text or JSON, as requested.
As for the jQuery, the AJAX call does indeed get to the success function, because I can ask it to document.write something there and it will do it. When I ask it to print out the data, however, the AJAX call runs forever (I think it is repeatedly calling the success function? Based on the browser telling me that it is either waiting or transferring data repeatedly). Regardless, nothing is printed to the screen despite the repeating script.
Oh, also, no errors are returned to the console.
I am not sure why it is doing this and so here I am. I've browsed through the other posts here and randomly on the internet, with no luck. Any help is appreciated!
Here is the PHP:
<?php
header('Content-type: text/plain; charset=utf-8');
// define variables and set to empty values
$servername = "localhost";
$username = "root";
$password = "Wolf*6262";
$dbname = "Game";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$id = $_GET["id"];
}
$query1 = mysqli_query($conn, "SELECT imageids FROM users WHERE id = $id");
// Start user session
if ($imageIds = mysqli_fetch_array($query1)) {
fetchUrls($imageIds, $conn);
} else {
echo "Fail";
}
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = '1'");
$array = mysqli_fetch_assoc($query2);
$url = $array["url"];
exit($url);
}
$conn->close();
The jQuery:
function getUrls (userId) {
$.ajax({
type: 'GET',
data: {id:userId},
URL: 'fetchChar.php',
async: false,
dataType: 'text',
success: function (data) {
document.write(data);
document.write(userId);
}
});
}
Aaand here's where I define userId and call getUrls, it's in a separate HTML file:
var userId = <?php echo $_SESSION["id"]; ?>;
$(document).ready(getUrls(userId));
Can you please modify your script: as standard way what prefer from jQuery:
1. Change URL to url
2. Please avoid async defining
Like this
$.ajax({
type: 'GET',
data:{ id: userId },
url: 'fetchChar.php',
// async: false,
dataType: 'text',
success: function (data) {
console.log(data);
//document.write(data);
//document.write(userId);
}
});
I added console log to show the return data, so that you can make sure that your data is returning correctly from fetchChar.php file using console log.
Ended up doing the following, question solved:
Javascript file:
$.ajax({
type: "POST",
dataType: "json",
url: "fetchChar.php",
data: {id:userId},
success: function(data) {
document.write(JSON.stringify(data));
}
});
PHP file, near the end:
function fetchUrls($imageIds, $conn) {
$query2 = mysqli_query($conn, "SELECT url FROM charimages WHERE id = 1");
$array = mysqli_fetch_assoc($query2);
$url = $array['url'];
$url = json_encode($url);
echo $url;
exit();
}
This has probably been answered already, but I can't seem to find a solution. I'm pretty sure I've been all over the internet.
I'm trying to send a mail from a form using AJAX. The AJAX script seems to be working fine. Here's the code:
$("#order").submit(function(e) {
e.preventDefault();
$(".loading-text").fadeIn("500");
var title = $("input#title").val();
var price = $("input#price").val();
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var address = $("input#address").val();
var urgency = $("input#urgency").val();
$.ajax({
url: "assets/order.php",
type: "POST",
dataType: "json",
data: {
title: title,
price: price,
name: name,
email: email,
phone: phone,
address: address,
urgency: urgency
},
cache: false,
processData: false,
success: function(data) {
$(".loading-text").fadeOut("300");
$(".success-text").fadeIn("500").append(data);
},
error: function(data) {
$(".loading-text").fadeOut("300");
$(".failure-text").fadeIn("500").append(data);
}
});
});
It returns undefined_index for all the variables however. Here's the PHP script:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$title = htmlspecialchars($_POST['title']);
$price = htmlspecialchars($_POST['price']);
$phone = htmlspecialchars($_POST['phone']);
$address = htmlspecialchars($_POST['address']);
$urgency = htmlspecialchars($_POST['urgency']);
$to1 = "jerryasih#gmail.com";
$to2 = "shalomdickson#yahoo.com";
$subject = "New order received!";
$msg_stalker = "Hello STALKER! New order received.\n\n"."Here are the details:\n"."Name: $name\n\nAddress: $address\n\nEmail: $email\n\nPhone number: $phone\n\nItem: $title\n\nPrice: $price\n\nThis customer needs their service/product in $urgency hours.";
$msg_owner = "Hello! Your store on STALKER! has a new order.\n\n"."Details:\n"."Item: $title\n\nPrice: $price\n\nThis customer needs their service/product in $urgency hours."."You may contact us on hoodstalker#yahoo.com if item is unavailable or for any other query.\n\nExpect us soon.\n\nWe've got your back! ;)";
$from = "Order form at (stores.neighbourhoodstalker.com)";
if (empty($name) || empty($address) || empty($phone)) {
http_response_code(400);
echo "Error! Please check that all required fields have been filled and try again.";
exit;
}
if(mail($to1, $subject, $msg_stalker, 'From: '.$from) && mail($to2, $subject, $msg_owner, 'From: '.$from)) {
http_response_code(200);
echo "Order placed successfully.";
}
else {
http_response_code(500);
echo "Something went wrong. Check your internet connection and try again.";
}
}
else {
http_response_code(403);
echo "There was a problem with your submission. Please try again.";
}
?>
I'm not sure where the problem is now because I used a similar code for a file uploader and it worked perfectly.
The problem is because of this setting in AJAX,
processData: false,
From the documentation,
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
Since you're not sending any DOMDocument or non-processed data, remove this setting processData: false from your AJAX request.
You're using wrong dataType. Use dataType: "json".
http://api.jquery.com/jquery.ajax/
I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.
Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.