how to get data in the success of ajax - javascript

I have the following ajax function:
reader.onload = function(event){
var fd = new FormData();
var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
console.log("name = " + Name);
fd.append('fname', Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function(data){
//console.log(data);
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName},
success: function(data){
console.log(data);
}
});
}
});
};
first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?
second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?
server-side code:
<?php
$fileName=$_POST["fileName"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;

This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.
var mySuccessVar = null;
...
success: function(data) {
mySuccessVar = data;
}
... // later in the code:
if (mySuccessVar != null) {
yourFunction(mySuccessVar);
}

Related

How can I combine two ajax functions in one function?

I have ajax code which can post name and I have another ajax which can post image I need to combine those two functions in order to have one function which can post both name and image
Below codes used to post image
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
And below codes used to post name
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
$.ajax({
type:"post",
url:"upload.php",
data:
{
'name' :name
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
How can I combine above codes in order to use only one url "upload.php", this means upload.php will insert name in database and save image in folder while click save button, that's why I need to combine the codes
Please anyone can help me
You literally combine them.
You can use your first function and do the following:
var fd = new FormData();
var files = $('#file')[0].files;
fd.append('name', $("#name").val();
that is it. And on the other side (backend) you just ask for this name:
$name = $_POST['name'];

Create PDF with Ajax

I am using FPDF to create my report.
$pdf = new Report('P','mm','A4', $_POST);
$pdf->AddPage();
$pdf->Output('file.pdf','I');
And I use ajax to make requisition to the PHP.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
window.open(data);
})
I want to show the report in a new tab
I think you should success key. So it would be something like this
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id },
success: function(data){
var blob = new Blob([data]);
window.open(URL.createObjectURL(blob));
}
})
Resolved:
I did the different way:
In my report PHP, I generate one temporay file, passing the parameter 'F'.
$pdf->Output('file.pdf','F');
In Jquery Ajax I opne the file, rather than open the data retorned of ajax request.
$.ajax({
type: 'POST',
url: '../reports/report.php',
data: { id: id }
}).done(function(data){
var fileName = "file.pdf";
$('#modalRel').modal('show');
var object = "<object data=\"{FileName}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
object += "If you are unable to view file, you can download from here";
object += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
object += "</object>";
object = object.replace(/{FileName}/g, "../Files/" + fileName);
$("#body-rel").html(object);
})
I hope to have helped who one day to need.

Jquery and AJAX post to php data attribute?

Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});

i can't upload images using Ajax

I've been trying to add a new product using ajax and bootstrap (modal) and when I press the save changes button, I get Undefined index in all the fields.
Here's my ajax code:
$('#save').click(function(){
var nombre = $('#nombre').val();
var desc = $('#desc').val();
var precio = $('#precio').val();
var stock = $('#stock').val();
var tipo = $('#tipo').val();
var data = new FormData();
jQuery.each(jQuery('#imagen')[0].files, function(i, file) {
data.append('file-'+i, file);
});
var datas="nombre="+nombre+"&desc="+desc+"&precio="+precio+"&stock="+stock+"&tipo="+tipo;
$.ajax({
url: "php/newproduct.php",
data: {datas, data},
cache: false,
contentType: false,
processData: false,
type: "POST"
}).done(function( data ) {
$('#info').html(data);
viewdata();
setTimeout(function() {
$('#myModal').modal('hide');
}, 500);
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
});
});
data: {datas, data},
doesn't seem to be proper javascript syntax and I don't think you can mix different data object.
You can't mix FormData and an URL encoded string, which in your case isn't event properly encoded and you will have problems, if any of the values contains &.
The easiest way to upload using AJAX would be, if you initialized the FormData object with your form
var data = new FormData($("#form").get(0));
and then just used
data: data,
in your AJAX call
If you really need to add the fields manually, you need to add them to the FormData object
data.append("nombre", nombre);
data.append("desc ", desc);
data.append("precio ", precio);
data.append("stock ", stock);
data.append("tipo ", tipo);

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

Categories

Resources