AJAX failing to upload blob image - ajax

I have a problem with uploading a blob using ajax. I have tried many options and they are not working.
I must say that the same variables (albeit with different names) work when using php in the standard sense but not when using ajax.
Please help
The ajax code is:
$(function() {
$("#upload").click(function() {
// validate and process form here
var username = $("input#username").val();
var title = $("input#title").val();
var image = $("#image").get(0).files.item(0);
var information = tinymce.get('blogcontent').getContent();
var dt = new Date();
// variable for blog date and time
var dateandtime = dt.toLocaleString();
var dataString = 'username=' + username + '&title=' + title + '&image=' + image + '&information=' + information + '&dateandtime=' + dateandtime;
$.ajax({
type: "POST",
url: "functions/insertblogpost.php",
data: dataString,
success: function() {
$('#writeblog').html("<div id='message'></div>");
$('#message').html("<h2>User account created!</h2>")
.append("<p>Please go back to login.</p>")
.hide()
.fadeIn(1000, function() {
$('#message').append("<a href='../../Mobileapptemplate.php'>Back</a>");
});
}
});
return false;
});
});
And the php script is:
$connection = mysqli_connect($dbserver, $dbusername, $dbpassword, $database);
$username = $_POST[ 'username' ];
$blogTitle = $_POST["title"];
$blogContent = $_POST["information"];
$blogpicturename = $_FILES["image"]["name"];
$blogpicdata = mysqli_real_escape_string( $connection, file_get_contents($_FILES["image"]["tmp_name"]));
$blogpictype = $_FILES['image']['type'];
$dateAndTime = $_POST["dateandtime"];
$result = "INSERT INTO ct5006ho_users.$username ( postnumber, user, title,
picturename, picture, blogpost, dateandtime ) VALUES ( '', '$username', '$blogTitle','$blogpicturename',
'$blogpicdata','$blogContent', '$dateAndTime');";
//if (
mysqli_query($connection, $result);
The connection IS established fine and all other data uploads to the phpmyadmin created database. I have omitted those details from the code.

Here is the answer:
$(function() {
$("#upload").click(function() {
// validate and process form here
tinyMCE.triggerSave();
var form = $('form')[0]; //
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "functions/insertblogpost.php",
data: formData, // Data sent to server, a se
contentType: false,
cache: false, // To unable request pages to be cached
processData:false,
success: function() { ....................
If anybody has a similar issue please use this experience to help you.
Note - tinyMCE.triggerSave(); - sends the tinyMCE data. and this was my original issue with the - data: formData,
Ah well, shoot me down for asking!

Related

Django: correct way to pass AJAX

I've a view that recives parameters from the frontend via AJAX.
I've passing AJAX parameters in a maner, but this time my way didn't work.
I've asked a friend for help, and he send me another way of sending AJAX data. To my untrained eyes they both work equal. So I don't know why mine does not work:
Why?
My friend's AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/?d_name=" + val_d + "&p_name=" + val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
</script>
My AJAX:
<script>
$("#id_shipping_province").change(function () {
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
d_name: val_d,
p_name: val_p
}).done(function (result) {
$("#id_shipping_district").html(result);
});
});
});
</script>
View
def get_district(request):
d_name = request.GET.get("d_name")
p_name = request.GET.get("p_name")
data = Peru.objects.filter(departamento=d_name, provincia=p_name).values_list("distrito", flat=True)
# data = Peru.objects.filter(provincia=p_name).values_list("provincia", flat=True)
return render(request, "accounts/district_dropdown.html", {
"districts": set(list(data))
})
You need to pass the the d_name and p_name properties in a separate object specified by data. Currently you're passing them as top level properties of the ajax settings object, which won't have any effect.
var val_d = $("#id_shipping_department").val()
var val_p = $("#id_shipping_province").val()
$.ajax({
url: "/district/",
data: { // Pass parameters in separate object
d_name: val_d,
p_name: val_p
},
}).done(function (result) {
$("#id_shipping_district").html(result);
});
The data object is converted into a query string and appended to the URL.
In your friend's case, they are building up the query string manually when they create the URL - hence their version works.

Return multiple strings from AJAX

With AJAX post i'm sending a data and on other page, according to this data i'm retrieving two different column values of mysql database by query. And i need to get back these two different values as a result of AJAX and show in two different inputs.
var mus_barkod = document.getElementById('mus_barkod').value;
var dataString = "mus_barkod="+mus_barkod;
$.ajax({
type: "POST",
url: "musteri_indir.php",
data: dataString,
success: function(result){
$("#indirim").val(result.mus_indirim);
$("#mus_isim").val(result.mus_isim);
This is the part of AJAX and below the (OLD) query for fetching data:
$mus_barkod = $_REQUEST['mus_barkod'];
$mus_cek = mysql_query("SELECT * FROM musteriler WHERE mus_barkod =
'".$mus_barkod."' AND sub_id = '".$per_sube."' ");
while ($mus_al=mysql_fetch_array($mus_cek)){
$mus_isim = $mus_al['mus_isim'];
$mus_indirim= $mus_al['mus_indirim'];
}
$mus_isim1 = 'Kayıtlı Müşteri Değil';
$mus_indirim1 = '0.00';
if($mus_barkod == '10' || $mus_barkod == '100090'|| $mus_barkod ==
'100237')
{
echo
$mus_indirim,$mus_isim;
}else{
echo
$mus_indirim1,$mus_isim1;
}
So how can i get back mus_indirim and mus_isim seperately and show in different inputs?
NOTE: Don't mind mysql_, this is an old system. PDO Forever :)
Fixed it by checking my codes more carefully. Here is the result for those need the same solution:
var mus_barkod = document.getElementById('mus_barkod').value;
var dataString = "mus_barkod="+mus_barkod;
$.ajax({
type: "POST",
url: "musteri_indir.php",
data: dataString,
dataType: "json", => the little thing i forgot to write :)
success: function(result){
$("#indirim").val(result.mus_indirim);
$("#mus_isim").val(result.mus_isim);
The Old PHP:
$mus_barkod = $_REQUEST['mus_barkod'];
$mus_cek = mysql_query("SELECT * FROM musteriler WHERE mus_barkod =
'".$mus_barkod."' AND sub_id = '".$per_sube."' ");
while ($mus_al=mysql_fetch_array($mus_cek)){
$mus_isim = $mus_al['mus_isim'];
$mus_indirim= $mus_al['mus_indirim'];
}
if($mus_barkod == '10' || $mus_barkod == '100090'|| $mus_barkod ==
'100237')
{
echo json_encode(array("mus_indirim" => $mus_indirim, "mus_isim" =>
$mus_isim));
}else{
echo json_encode(array("mus_indirim" => '0.00', "mus_isim" => 'Kayıtlı
Müşteri Değil'));
}

Php FormData is null

I have a form with id: formC, on submit i call ajax:
var datiForm = new FormData();
var pos = [];
var i = 0;
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
pos[i] = $(this).find("input[type=checkbox]").data("id");
i++;
}
});
datiForm.append("nome",nome.val());
datiForm.append("cognome",cognome.val());
datiForm.append("email",email.val());
datiForm.append("telefono",telefono.val());
datiForm.append("dataNascita",dataNascita.val());
datiForm.append("titolo",titolo.val());
datiForm.append("ruolo",ruolo.find(":selected").data("ruolo"));
datiForm.append("sede",sede.find(":selected").data("sede"));
datiForm.append("posizione",pos);
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
$.ajax({
type: "POST",
data: {datiForm: datiForm},
url: "saveCandidate.php",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var position = data;
}
});
I have a problem, on server $datiForm = $_POST["datiForm"]; is null why?
Moreover i have input file where i can select file pdf. I put it in FormData:
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
You specified the data field incorrectly, it should be just the form data object
data: datiForm,
also the way you add posizione is not going to work, each entry in yrh array has to be added individually
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
datiForm.append("posizione["+i+"]", $(this).find("input[type=checkbox]").data("id"));
i++;
}
});
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
Yes
You'll need to specify the 'contentType' attribute to 'multipart/form-data' in order to upload files.

In Codeigniter when insert data in db alert message is not displaying, directly it is redirecting

i am using codigniter .when i am inserting or updating data in mysqldb data is inserting.my form is in popup.then alert is getting but redirecting was not working..issue is redirected is displaying in popup not to page .can you please tell the alternate solution ..i am using ajax update to my form
This is my code of controller
$testid=$this->objTests->updateTest();
echo "<script> alert('sucessfully updated');</script>"
redirect(base_url().'tests');
this is my following code of model:
$testData = array('simulationId' => $this->input- >post('simulationId'),
'testTitle' => $this->input->post('testTitle'),
'description ' => $this->input->post('description')
);
$this->db->where('id',$this->input->post('tid'));
$this->db->update('tests',$testData);
return $this->input->post('tid');
$(function(){
$( "#frmActiontest" ).submit(function( event ) {
var url = $(this).attr('action');
$.ajax({
url: url,
data: $("#frmActiontest").serialize(),
type: $(this).attr('method')
}).done(function(data) {
//window.location.href="http://neuronguru.com/MedAdmin/tests/";
window.location.reload();
/*$('#result').html(data);
$('#frmActiontest')[0].reset();*/
});
event.preventDefault();
});
$( ".test" ).on("click",function(event) {
var url = $(this).data('url');
var actionUrl = $(this).data('actionurl');
console.log(actionUrl);
$("#frmActiontest").attr('action',actionUrl);
$.ajax({
url: url,
type: "GET",
dataType: 'json'
}).done(function(data) {
data=data[0];
$("#myModalTestLabel").html("Update Test");
$("#simulationId").val(data.simulationId);
$("#testTitle").val(data.testTitle);
$("#description").val(data.description);
//$("#contents").val(data.contents);
$("#tid").val(data.id);
$("#testModal").trigger("click");
console.log(data);
});
event.preventDefault();
});
});
this is my ajax function for the above question

RecorderJS uploading recorded blob via AJAX

I'm using Matt Diamond's recorder.js to navigate the HTML5 audio API, and feel this question probably has an apparent answer, but i'm unable to find any specific documentation.
Question: After recording a wav file, how can I send that wav to the server via ajax? Any suggestions???
If you have the blob you'll need to turn it into a url and run the url through an ajax call.
// might be nice to set up a boolean somewhere if you have a handler object
object = new Object();
object.sendToServer = true;
// You can create a callback and set it in the config object.
var config = {
callback : myCallback
}
// in the callback, send the blob to the server if you set the property to true
function myCallback(blob){
if( object.sendToServer ){
// create an object url
// Matt actually uses this line when he creates Recorder.forceDownload()
var url = (window.URL || window.webkitURL).createObjectURL(blob);
// create a new request and send it via the objectUrl
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "blob";
request.onload = function(){
// send the blob somewhere else or handle it here
// use request.response
}
request.send();
}
}
// very important! run the following exportWAV method to trigger the callback
rec.exportWAV();
Let me know if this works.. haven't tested it but it should work. Cheers!
#jeff Skee's answer really helped but I couldn't grasps it at first, so i made something simpler with this little javascript function.
Function parameters
#blob : Blob file to send to server
#url : server side code url e.g. upload.php
#name : File index to reference at the server side file array
jQuery ajax function
function sendToServer(blob,url,name='audio'){
var formData = new FormData();
formData.append(name,blob);
$.ajax({
url:url,
type:'post',
data: formData,
contentType:false,
processData:false,
cache:false,
success: function(data){
console.log(data);
}
}); }
Server side code (upload.php)
$input = $_FILES['audio']['tmp_name'];
$output = time().'.wav';
if(move_uploaded_file($input, $output))
exit('Audio file Uploaded');
/*Display the file array if upload failed*/
exit(print_r($_FILES));
I also spent many hours trying to achieve what you are trying to do here. I was able to successfully upload the audio blob data only after implementing a FileReader and calling readAsDataURL() to convert the blob to a data: URL representing the file's data (check out MDN FileReader). Also you must POST, not GET the FormData. Here's a scoped snippet of my working code. Enjoy!
function uploadAudioFromBlob(assetID, blob)
{
var reader = new FileReader();
// this is triggered once the blob is read and readAsDataURL returns
reader.onload = function (event)
{
var formData = new FormData();
formData.append('assetID', assetID);
formData.append('audio', event.target.result);
$.ajax({
type: 'POST'
, url: 'MyMvcController/MyUploadAudioMethod'
, data: formData
, processData: false
, contentType: false
, dataType: 'json'
, cache: false
, success: function (json)
{
if (json.Success)
{
// do successful audio upload stuff
}
else
{
// handle audio upload failure reported
// back from server (I have a json.Error.Msg)
}
}
, error: function (jqXHR, textStatus, errorThrown)
{
alert('Error! '+ textStatus + ' - ' + errorThrown + '\n\n' + jqXHR.responseText);
// handle audio upload failure
}
});
}
reader.readAsDataURL(blob);
}
Both solutions above use jQuery and $.ajax()
Here's a native XMLHttpRequest solution. Just run this code wherever you have access to the blob element:
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, "filename");
xhr.open("POST","upload.php",true);
xhr.send(fd);
Server-side, upload.php is as simple as:
$input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav"; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
move_uploaded_file($input, $output)
source | live demo

Resources