Receiving Data from AJAX to PHP - php

I have read a lot of Q&As on here and can't seem to figure out what I am doing wrong...
Here is AJAX
var color = $('#fontcolor').val();
var size = $('#fontsize').val();
var text = $('#imagetext').val();
var fileToUpload = $('#fileToUpload').val();
var placement = $('#placement').val();
$.ajax({
type: "POST",
url: 'upload.php',
data: {color:color, size:size, text:text, fileToUpload:fileToUpload},
success: function(data)
{
window.alert(data);
},
cache: false,
contentType: false,
processData: false,
error: function()
{
window.alert('error');
}
});
And then php, I am just trying to simply see my data from now, but it shows empty...
<?php
$fontSize = $_POST['size'];
echo $fontSize;
echo "Test";
?>
I know that data is coming from form, I have tested variables after data is received, but just can't get it to post... I was using FormData object originally, but decided to simplify for troubleshooting purposes... Still nothing, seems very straightforward, but have been on this for a few days now...

So it seems I might not be able to pass the image alongside the other parameters, though perhaps there is a way I cannot find. Instead, I will pass image to upload.php, then in response return the image path. Then I will have it trigger success function that passes other parameters to another function that modifies the image accordingly. Works for me.

Related

Passing Back multiple PHP variables after a ajax Form Call

I am passing a file to a php file via ajax and i am returning only 1 $ variable using die($var) in the php file after a sucsessfull run...
the problem i am now facing is passing more than 1 variable back to the ajax sucess function . i have tried using json encode but it has failed to work. im thinking maybe to do with the ajax being form data.
im hoping there is a simple way top pass multiple varibles back to the sucess function.
Any help is greatly appreciated
var form_data = new FormData(); // Creating object of FormData class
form_data.append("image", file , newimagesrc) // Appending parameter named file with properties of file_field to form_data
form_data.append("oldimagesrc", oldimagesrc) // to re-write over with new image
form_data.append("email", email)
form_data.append("imagext", fileNameSub)
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){
//how do i pass back from php these variables
var out1=out1;
var out2=out2;
alert(out1 , out2);
//help appreciated
var newimagesrc = newimagesrc;
//alert(newimagesrc); alert recieved message
imagename=input.files[0].name;
$('#imageupdate').css('color','green');
$('#imageupdate').text(newimagesrc);
var refreshimage = "Profileimagerefresh.php?avatar="+newimagesrc+"&email="+email;
$('#imagerefresh').load(refreshimage);
}//success 1 messagereturn1
});//ajax1
PHP FILE ('UploadProfileImage.php')
if(file_exists($oldimagelocation) && is_readable($oldimagelocation)){
$new=$rnd.$accountname.".".$extension;
if ($stat->execute(array("$new","$email"))){
unlink($oldimagelocation);
die($oldimagesrc); //HERE I PASS 1 $ BACK - I NEED TO RETURN MORE
exit();
}
else{
die("Failed replace image with image and rename");
exit();
}
}
Using JSON encode is the best choice. I would recommend something like this:
if (file_exists($oldimagelocation) && is_readable($oldimagelocation)) {
$new = $rnd.$accountname.".".$extension;
if ($stat->execute([$new, $email])) {
unlink($oldimagelocation);
echo json_encode([
'out1' => $oldimagelocation,
'out2' => $oldimagesrc,
], JSON_FORCE_OBJECT);
} else {
die("Failed replace image with image and rename");
}
}
Then in JS just parse the response as JSON
$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){
let jsonObj = JSON.parse(newimagesrc);
console.log(jsonObj.out1);
}
});
I have encountered a similar issue recently and solved this using JSON.
With PHP you can put the variables into an array and then use json_encode: and then return that onto the webpage.
Now, using your jQuery, you can use $.parseJSON which then makes it an array in jQuery.
Here's an example:
PHP:
die(json_encode(array('Hello', 'world!')));
jQuery:
$.ajax({
type: 'POST',
url: 'test.php',
}).done(function(result){
var array = $.parseJSON(result);
alert(array[0]);
});

PHP - renaming a file before uploading

I am trying to build off a question I asked yesterday.
I am able to pass the file over to PHP using the ajax method. But I need to be able to change the file name to the booking number. For some reason, the booking was not being passed over to the PHP script. So I attempted the following:
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
$.post('process/fileUpload.php', {booking:booking, partner:partner}, function(data)
{
// Wasn't sure if I needed anything here
console.log(data);
});
$.ajax({
url: 'process/fileUpload.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data){console.log(data);},
error: function(jqHHR, textStatus, errorThrown){console.log('fail: ' + errorThrown);}
});
});
As you will notice above, I had to use the $.post method to send the booking and partner over to the php script.
I then used $.ajax to send the form_data over to the same script.
(I could not achieve this in one motion from yesterday's question I asked. So this is my second attempt to complete this. If there is a way to send all of the info in one motion, please refer to the question I linked above.)
So over in the PHP script, I am able to get all of the items I needed with a couple of functions:
<?php
// from the $.post method
if(isset($_POST['booking']))
{
$booking = $_POST['booking'];
$partner = $_POST['partner'];
getInfo($booking);
}
// from the $.ajax method
if($_FILES['file'])
{
$file = var_dump($_FILES['file']);
getFile($file);
}
function getInfo($booking)
{
return $booking;
}
function getFile($file)
{
return $file;
}
?>
I know it's not pretty, but I am able to get the booking (I don't need the partner right now), and I am also able to get the file information.
What I need to do is rename the file to the booking, and then finally upload it to the necessary directory.
I wasn't sure if I had to combine the functions, but I did try to no avail.
With that said, I am able to get the booking and file info within the PHP script. Now how would I go about renaming the file to the booking?
As you used form_data.append() to add the file data to the formdata. did it not occur to you to also use that to add the booking and partner values to it as well?
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
form_data.append('booking', $('#bookingNum').val());
form_data.append('partner', $('#partnerCode').val());
$.post('process/fileUpload.php', form_data, function(data)
{
console.log(data);
});
});
To fix your ajax request (especially the illegal invocation), use the following javascript code
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
form_data.append('booking', $('#bookingNum').val());
form_data.append('partner', $('#partnerCode').val());
$.ajax({
type: "POST",
url: 'process/fileUpload.php',
data: form_data,
processData: false,
contentType: false,
success: function(data) { console.log(data); }
});
});
Notice the use of processData: false and contentType: false

Take html and variable with AJAX

I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});

Jquery Javascript Variable

Hello i have searched the whole website for a soltution found something but didnt get it to work.
-I have the main function on the head area of the page. (This will return Data from a PHP)
-This Data i need as a variable but dont know how to handle.
function note(content,usern){
note = Function("");
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern }, success: function(data){ var myneededvar = data; }, }); }
Ok thats works and also data is given out
Now im calling the function in the script like this
note(token,notename);
and i need the result myneededvar
but cant get it to work.
Firstly, your variable myneededvar is local to the success handler function and will not be available outside.
Secondly, your AJAX call is asynchronous and you cannot expect to immediately get the AJAX return data in a variable right after the AJAX call statement.
i.e., you cannot do:
note(...); // call your method
alert(myneededvar); // this won't work as the AJAX call wouldn't have completed
Thirdly, not sure why you have that note = Function(""); statement there. You should remove that.
Something like this should work:
var myneededvar;
function note(content, usern){
$.ajax({
type: "POST",
url: "note.php",
data: {'token': content, 'user': usern },
success: function(data){
myneededvar = data;
// use it here or call a method that uses myneededvar
}
});
}

Sending back multiple results from PHP via AJAX

i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});

Categories