I'm setting up a system for users to upload profile pictures to the server. These profile pictures are cropped with Croppie, then sent with a POST request for processing to a PHP file.
This PHP file receives a response from the server if the image was accepted, or if there was an error.
I'm having difficulty passing this JSON response back to an AJAX variable, so I can show it to end-users.
I've set up a with the ID of "json" where the response should be shown. However, all that is being displayed is 'undefined'.
When displaying the 'response' variable without .msg, it displays the image URI - so it doesn't appear to be taking the requests made in the PHP script.
Here's what I've tried:
AJAX
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
});
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">'
+ response.msg + '</div>');
})
});
PHP (start of script)
# Mechanism to upload image
if (isset($_POST['image'])) { # Check if image data is being sent by POST
$c_finalCheck = true;
$cropped_image = $_POST['image']; # Assign cropped_image from data received
$image_array_1 = explode(";", $cropped_image); # Create image with correct encoding
$image_array_2 = explode(",", $image_array_1[1]);
$cropped_image = base64_decode($image_array_2[1]);
$c_imgValid = getimagesize($c_fileCheck); # Set result of image validity and size check
if ($c_fileCheck == false) { # Run image validity check with response
$response['msg'] = 'Sorry, your image isn\'t valid. Please try again.';
$c_finalCheck = false;
header("Content-Type:application/json");
echo json_encode($response);
}
you are sending the Ajax Post to your Server, but you are not using the Ajax response. Instead you are displaying the response of your croppie call.
You need to do something like this:
$('.crop_image').on('click', function(ev) {
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response) {
$.ajax({
type: 'POST',
url: "core/account-mechanisms/push-profile-test.php?action=upload",
data: {
"image": response
},
}).done(function(data) {
$("#json").html('<div style="margin-top:15px;" class="alert alert-success">' + response + '</div>');
});
})
});
I did not try it but it should give you the right direction.
Here the jquery Api reference: Ajax
Related
I am trying to post a file (will be of type pdf or image), uploaded by the user in a form. The file will be taken by an AngularJS directive set 'onChange', sent through 'myPostr' function which is supposed to post my file to 'api/' so it can be received by PHP. Atm, PHP echoes empty arrays, atleast having the headers - 200 OK.
This my HTML:
<input name="file" class="form-control-file" my-directive type="file" accept="application/pdf">
This my simplified AngularJS script:
application.directive('myDirective', function(myPostr){
return{
restrict: 'A',
scope: true,
link: function(scope, element){
element.bind('change', function(){
if (element[0].files[0].type == 'application/pdf') {
var form = new FormData();
form.append('form', element[0].files[0])
myPostr(form, function(callback){
console.log(callback);
}) //or imagetype to be implemented
application.factory('myPostr', function($http){
return function (data, callback) {
$http.post('api/', {
data: data,
headers: {'Content-type':undefined}
})}
});
'myPoster' works fine for json data (form variables)
This are the multiple ways I've tried in PHP to display the received data:
//isset($_FILES['file']) returns false
$response = json_decode(file_get_contents('php://input'),true);
header('Content-Type: application/json');
echo json_encode($response); //or
//echo json_encode($_FILES);
All return this in the network console
Extra info: these are the console logs of the uploaded files
I am having some issue on accessing Ajax Post data on server side. I have
var data = {
ox:'A',
oy:'B',
dx:'C',
dy:'D',
method:null
};
I have a jQuery event hamdler like
$("#route").on("click", function(){
var request = $.ajax({
type: "POST",
url: "assets/app.php",
data: data,
cache: false,
dataType: "JSON",
beforeSend: function() {
console.log(data);
}
});
request.done(function( data ) {
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
I am able to send the data correctly as it is logging out at beforeSend
{ox: A, oy: B, dx: C, dy: D, method: null}
On PHP side I have
$method = $_POST['method'];
$ox = $_POST['ox'];
$oy = $_POST['oy'];
$dx = $_POST['dx'];
$dy = $_POST['dy'];
now only accessing to one of the $_POST[] data is working like echo $ox; but when I try to access all $_POST[] data like
echo $ox;
echo $dy;
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
I am getting Request failed: parsererror error on .fail()
From the docs:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So, your response isn't a valid JSON.
What you can do is to create an array, like you are doing:
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
Then encode into json and echo it
echo json_encode(['startPoint' => $startPoint, 'endPoint' => $endPoint]);
On the frontend (javascript) you will get and JSON like
{
'startPoint' : ['ox','oy'],
'endPoint' : ['dx','dy'],
}
the values of ox, oy, dx and dy, of course, will be the values sent before.
I am a new Angularjs user.I am facing a problem,when i submit a signup form,I have applied validation using AngularJs. At the same time if all the input fields are valid then i have send an $http Ajax call to check the email address,already exist or not.The issue is my php file did not receive email data.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data: { email: $scope.user.email }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
My Php file code:
$email = $_POST['email'];
$sql = "SELECT * FROM user where username = '".$email."'";
$result = mysql_query($sql);
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
....
....
....
....
....
}
I have checked and found that php file did not receive email value at all.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data : $.param($scope.user), // this will definitely wor
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
Try removing http://localhost from url and then see it may be CORS.
Just a guess: your url is pointing to localhost but has no port number, this is unusual, maybe you forgot it?
data: $.param({
email:$scope.user.email
})
Or this way: (modify the php)
Angular HTTP post to PHP and undefined
I have just found that in php file,
$_POST or $_GET will not work, to receive data.
Use the following:
$data = file_get_contents("php://input");
$objData = json_decode($data);
$email = $objData->email;
In my case it works.
I have the following code on my PHP page which gets a message from the client and stores it into a log file on the server. This function is called by a jquery AJAX function(given below). The AJAX request sends the data properly and the PHP code works fine. However when the response to the AJAX request is sent back the page suddenly redirects to index.php(my main page):
PHP Code
function store_chat_msg_function()
{
//Check if session is active
if(isset($_SESSION['NAME']))
{
$data = $_POST;
$text = $data["message"];
$filepath = $data["filepath"];
$fp = fopen($filepath, 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['NAME']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
//Push data array to be sent into array
$json = array();
$bus = array(
'message' => "1"
);
array_push($json, $bus);
//Encode to JSON format
$jsonstring = json_encode($json);
//Specify type of data being sent
header("content-type:application/json"); //<-----(error:line 179)
//Finally send the data
echo $jsonstring;
}
else
{
}
}
And the AJAX function is:
//On submit message
$("#submitmsg").click(function(){
var ptarget = $(this).html();
//get some values from elements on the page:
//Set parameters...
var clientmsg = $("#usermsg").val();
//Clear the text box
$("#usermsg").val("");
var data = {
"action": "send_chat_msg",
"message": clientmsg,
"filepath": globalrefreshfile
};
data = $(this).serialize() + "&" + $.param(data);
//Send the data using post and put the results in a div
$.ajax({
url: "post.php",
type: "POST",
data: data,
datatype: "json",
success: function(data) {
if(data[0].message!="1"){
alert("Message was not sent.");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(errorThrown);
$("#chatbox").html('There was an error updating chat window');
$("#chatbox").fadeIn(1500);
}
});
});
I removed header("content-type:application/json"); and datatype: "json" in the AJAX function and found that the data is muddled by error data sent by the ZEND server i'm debugging on. The error is:
"Warning: session_start(): Cannot send session cache
limiter - headers already sent in C:\Program Files
(x86)\Zend\Apache2\htdocs\ChatServer\post.php on line 2Warning: Cannot modify header information - headers
already sent in C:\Program Files
(x86)\Zend\Apache2\htdocs\ChatServer\post.php on line
179[{"message":"1"}]
So i understand that I think i may have messed up the headers based on the ZEND debugger error which is interfering with my JSON data(seen appended at the end of the error)? What gives? Thank you for your time and patience.
Add ob_start(); as the first line in your script if you can't move the header("content-type:application/json"); to the top of the page for some reason.
You cannot modify headers, so move your code to top of page:
header("content-type:application/json");
Top means top of proccessed page, Not a top of function.
Regards
Using mobile apllication here, I am sending image encoded data to php file using post method and getting the image url from the php file. The problem here is, I am not getting proper image while am sending string using ajax. When I place the image data manually, I am able to view the image, but when sending the image data using ajax call, unable to view the image.
<?php
//$image = $_POST['uploadedfile'];//not working if an ajax call is made what is the issue here
$image ="base64 string of an image here";//working if i place base 64 string here
$binary = base64_decode($image);
$fileName = time() . ".jpeg";
file_put_contents('images/' . $fileName, $binary);
if (file_exists('images/' . $fileName)) {
$myjson12 = "[";
$myjson12.='{';
$myjson12.='"Certificate":"http://domain/demo/images/'.$fileName.'"';
$myjson12.='}';
$myjson12.="]";
echo "$myjson12";
} else {
echo 'FAILURE';
}
?>
When I am accessing the file url and sending the parameter value the output is coming as url is too long: www.domain.com/getdata.php?uploadedfile=base64stringvalue;
here is my ajax call
$.ajax({
type: "POST",
url: "www.domain.com/getdata.php",
data: { "uploadedfile": c.toDataURL("image/jpeg") },
// dataType: "json",
success: function (response) {
console.log(response + "Sri");
$("#loadImg").hide();
alert("Success");
},
error: function (data) {
$("#loadImg").hide();
alert("Connection Failed");
}
});