My code looks like this
var data = new FormData();
var ids = file[f].name._unique();
data.append('file',file[f]);
data.append('index',ids);
data = data + "&moredata=morevalue" ; //when I am uncommenting this line everything is working
$(".dfiles[rel='"+ids+"']").find(".progress").show();
$.ajax({
type:"POST",
url:this.config.uploadUrl,
data:data,
cache: false,
contentType: false,
processData: false,
success:function(rponse){
$("#"+ids).hide();
var obj = $(".dfiles").get();
$.each(obj,function(k,fle){
if($(fle).attr("rel") == rponse){
$(fle).slideUp("normal", function(){ $(this).remove(); });
}
});
if (f+1 < file.length) {
self._uploader(file,f+1);
}
}
});
} else
console.log("Invalid file format - "+file[f].name);
}
I want to add key and values to the POST array moredata and morevalue you can see this in 5th line,when I am uncommenting that line I am able to send the data via post but I am not getting why my code is not working by adding moredata and morevalue:
data = data + "&moredata=morevalue" ;
Here is the project folder for reference:
https://www.dropbox.com/sh/4fc78os0j0t9b8j/kayiL1DkgI/arulsir
From the last line in the question I assume, it is not working when you uncomment the line data = data + "&moredata=morevalue";
So you need to add additional data to data using
data.append('moredata', 'morevalue');
Related
//ADDING NEW ITEM INTO THE ITEM TABLE
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];
var i=0;
//Put the datatable rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
url:'item_action.php',
method:"POST",
data:{
btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
$('#product_form')[0].reset();
$('#productModal').modal('hide');
$('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
$('#action').attr('disabled', false);
$('#item_data').DataTable().ajax.reload();
},
error : function () {
$('<div>').html('Found an error!');
}
})
});
That's my java code and I'm trying to call a php page and save all data in my DB. I got an error:
TypeError: 'insertCell' called on an object that does not implement interface HTMLTableRowElement.
That's happening when I insert data into the table "it_det"
Look the picture:
If I don't insert new rows into the table I don't get error!
What's wrong with that? Why I'm getting this error???
I found the solution changing the "processData" key to false
$.ajax({
processData: false, //The default value of ProcessData is true so changing in false I don't get any error.
url:'item_action.php',
method:"POST",
I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code
i have a question regarding with this situation
I have two forms which consist of #1 Form is an image uploader form and the #2 Form is consist of user data which i want to fire with a one button only using ajax.
Here my problem is about passing the values. How can i make this var formData = new FormData($('#form-upload')[0]);
and
#frm_patientreg
to be something like this: $('#form-upload, #frm_patientreg').serialize(),
Here is my ajax:
var inputFile = $('input[name=file]');
// var uploadURI = $('#form-upload').attr('action');
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
JSFIDDLE :https://jsfiddle.net/ny3rvowo/1/
The reading works.
However I got a syntax error in the firefox console (which is tiresome when I read 30 files).
The files are annotation files like (time \t value) with no headers like :
0.0 5.2
0.5 5.6
1.0 6.3
...
This is the ajax code :
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
async: false,
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata}
And with d3:
d3.text(filename, function(text) {
var data = d3.tsv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
console.log(data);
});
}
It seems that I could use one of those code, but I got a syntax error in both cases (with firefox 33.1).
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be used
function doOpen(evt) {
var files = evt.target.files,
reader = new FileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on
jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url
var jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>
To keep it simple, I'm just wanting to know how I'd go about and if else statement against my ajax to print new data out once if it finds it and not the same data over and over again. Amd how can I possibly store the last id as a variable to reuse it when searching for more new records?
Someone mentioned to me also I could save the new notification idea as a return so when the ajax restarts it uses this to find the next new set of results.
Has anybody got any ideas how to achieve these?
<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>
Regarding to store the last id, you could use:
window.localStorage.setItem('key', 'value');
Then when you want to get it again you'll should use:
var lastId = window.localStorage.getItem ('key');
And regarding the duplicates issue, well, you should have a internal storage in order to handle the recieved data. May be an array can help as storage, also you can also store this array in local storage.
Once you handle this data storage, you could apply something like this to verify that your data has no duplicates:
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
UPDATE
var notification_id = window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler(response);
if(response.num){
window.localStorage.setItem('lastId', response.num);
}
});
},20000);