Illegal invocation error when tranfering file - javascript

//HTML
<td><input type="file" name="product_image" id="product_image" required ></td>
//JavaScript
$(document).on("click", "#submit", function() {
console.log(validproductname, validproductprice, validdescription, validimage);
if (validproductname && validproductprice && validdescription && validimage) {
var send_data = new FormData();
var file_data = $('#product_image').prop('files')[0];
send_data.append("file", productimage.files[0]);
$.ajax({
url: "retrivedata.jsp",
type: "POST",
data: {
pagename: "index",
action: "insert",
productname: productname.value,
productprice: productprice.value,
productdescription: productdescription.value,
productcategory: productcategory.value,
productimage: $('#product_image').prop('files')[0]
},
success: function(data) {
load_data();
}
});
} else {
console.log("Invalid Details");
}
});
I have to trying to send file with data but it will through following error:
I apply one of solution processData:false
but it will send data as a [object Object] which i can't able to access
What i want is that i need to send file as a data parameter and access in a backend side

Related

Validation DropDownList outside grid

I have kendo dropdownlist and button submit. I want if the user not select anything in dropdown(position), there will be validation that inform the user must select one position at least at dropdown. Then, if the user has click the position, so the user can submit the data. I have used some method like "required" but not working.
HTML
<input id="dropdown" style="width:200px;" />
JavaScript for kendoDropDownList (position)
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "./testjson.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: function(e){
console.log(this.value());
// $('#AccountingTree').data('kendoTreeView').homogeneous.read();
homogeneous1.read();
homogeneous2.read();
homogeneous3.read();
homogeneous4.read();
homogeneous5.read();
homogeneous6.read();
homogeneous7.read();
homogeneous8.read();
homogeneous9.read();
homogeneous10.read();
homogeneous11.read();
homogeneous12.read();
homogeneous13.read();
homogeneous14.read();
}
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
For dropdownlist above, i"m using homogeneous data (treeview).
Anyone have any idea or reference on this question?
JavaScript AJAX call for submit button
//AJAX call for button
$("#primaryTextButton").click(function(){
if($("#dropdown").data("kendoDropDownList").value() == ""){
kendo.alert("Please select position.");
}
});
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS")
{
kendo.alert("Data saved");
}else
{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
});
When you click the button, just get the value of the kendoDropDownList and do a
conditional statement. Hope this helps. Happy Coding ;D
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").data("kendoDropDownList").value();
if(test == ""){
kendo.alert("Please select position.");
}
else{
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS"){
kendo.alert("Data saved");
}
else{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
}
});

form name array not working

What could be causing my array from not forming correctly? I get the following result.
array(1) {
["element[119"]=>
array(1) {
["data"]=>
string(1) "0"
}
}
When it the result should look like this.
array(1) {
["element"]=>
array(1) {
["119"]=>
array(1) {
["data"]=>
string(1) "0"
}
}
}
Simplified front end:
<input class="custom-control-input data is-valid" data-parent="0" data-qid="119" name="element[119][data]" id="119-Yes" type="radio" onchange="showTextBox(this)" value="1" checked="">
<script type="text/javascript">
var formData = {};
$(form).find(":input.data:visible, input[type=hidden].data").each(function (index, node) {
formData[node.name] = node.value;
});
console.log(formData);
$.ajax({
url: "index.php?route=form/form/saveSection",
data: { form_id: $("#formRequest").data("formsaveid"), section_id: $("#formRequest").data("currentsectionid"), path: $("#formRequest").data("formpath"), action: "saveSection", data: formData},
dataType: "json",
method: "POST",
beforeSend: function() {
console.log("Saving Section...");
console.log("Section ID: "+$("#formRequest").data("currentsectionid"));
console.log(postData);
},
success: function(data) {
}
});
</script>
Simplified back end:
var_dump($data);exit;
The issue is happening with the way you manipulate the data with
$(form).find(":input.data:visible, input[type=hidden].data").each(function (index, node) {
formData[node.name] = node.value;
});
really you need to serialize the entire form and convert it to json, so replace the above with this:
var formData = JSON.parse($(form).serializeArray());
Then you can:
<?php
var_dump($_POST['data']);
name="[element][119][data]"
Try to encapsulate everything inside array brackets in your name tag in HTML.

Uable to send POST data to JSON file via JQuery/AJAX, Why?

I am learning to process JQuery/Ajax from this video on YouTube, click here..
I'm not having any problem in receiving data from order.json file but when I am trying to POST data. I am always getting Error.
The code structure with screenshot and code is below, please help me.
Project folder screenshot:
HTML code:
<div class="wrapper">
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
JQuery/Ajax code:
$(document).ready(function () {
var $orders = $('#orders');
var $name = $('#name');
var $drink = $('#drink');
function addOrder(order){
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
$('#add-order').click(function(){
var order = {
name: $name.val(),
drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/api/orders.json',
data: order,
success: function(newOrder) {
addOrder(newOrder);
},
error: function(){
alert('Error Adding Orders');
}
});
});
});
JSON: order.json
[{
"id": 1,
"name": "James",
"drink": "Coffiee"
}, {
"id": 2,
"name": "John",
"drink": "Latte"
}]
Client side scripting languages are used to send and retrieve data which resides on server side. We can't use them to write/edit data on server side.
For doing so, we have to use server side scripting languages like PHP or ASP or any other which you prefer.
The video you referred was an API written in Core PHP used for retrieving / writing data from / to a json file which resides on server.
In my below code i have used PHP to write submitted data to a json file via jQuery/AJAX.
Check this out..
api/process.php
if (isset($_POST['params'])) {
$params = $_POST['params'];
$oldData = file_get_contents('orders.json');
$tmp = json_decode($oldData);
array_push($tmp, $params);
$newData = json_encode($tmp);
if (is_writable('orders.json')) {
file_put_contents('orders.json', $newData);
echo $newData;
} else {
echo "file is not writable, check permissions";
}
}
index.html
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
<script src='js/jquery.min.js'></script>
<script src='js/main.js'></script>
js/main.js
let $orders = $('#orders');
let $name = $('#name');
let $drink = $('#drink');
function addOrder(order) {
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$('#add-order').click(function(){
let order = {
name: $name.val(),
drink: $drink.val()
};
$.ajax({
type: 'POST',
url: '/api/process.php',
data: { params: order },
success: function(resp) {
addOrder(resp);
},
error: function(){
alert('Error Adding Orders');
}
});
});
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
api/orders.json
[
{
"id": 1,
"name": "James",
"drink": "Coffiee"
},
{
"id": 2,
"name": "John",
"drink": "Latte"
}
]
Note: Here, i am not writing id to json file for new orders.
Hope, this piece of code works fine for you. :) :)

Ajax firing success event but not getting to the web method

I'm using ajax to call a server side function. for some reason, the success is firing but it doesn't get to the function
here is the javascript
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "Server.aspx/sendEmail",
data: { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" },
async: false,
success: function (data) {
var a = 3;
},
error: function (a, b) {
alert("error");
var a = 43;
}
});
});
here is the c#
[WebMethod]
public static string sendEmail(string name, string company, string country, string email, string msg)
{
//somecode here
}
the data message(for some reason it is breaking)
<form method="post" action="./sendEmail?%7b%22name%22%3a%22foo%22%2c%22company%22%3a%22bar%22%2c%22country%22%3a%22foo%22%2c%22email%22%3a%22bar%22%2c%22msg%22%3a%22bla%22%7d" id="form1">
<div>
</div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="368A1591" />
Take the following points into account when you are calling an ASP.NET AJAX page methods:
To use ASP.NET AJAX page methods, you need to make a POST request. This is to prevent CSRF
Ensure that the contentType is set to application/json.
Use JSON.stringify to convert the JavaScript object into JSON text.
Your JS code could be something similar to this:
$(document).ready(function () {
var data = { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" };
$.ajax({
url: "Server.aspx/sendEmail",
type: "POST",
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: function (data) {
//Do something
},
error: function (xhr) {
alert('Request Status: ' + xhr.status
+ ' Status Text: ' + xhr.statusText
+ ' ' + xhr.responseText);
}
});
});
If it still doesn't work, check the statusText for the error.

All files are not getting from file upload control using jquery

I am facing a problem during images upload.
I have an input type file control in my form and more input controls can be added using jquery. The problem is this: when I get all those control values, it only return the first value from file control.
How can I get all added files in all control? Here is my code:
Javascript
$(document).ready(function() {
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append(
$("<input/>", {
name: 'file[]',
type: 'file',
id: 'file',
accept: '.jpg, .jpeg, .gif'
}),
$("<br/><br/>")
));
});
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("File Must Be Selected");
e.preventDefault();
} else {
//upload all images
var fileData = $('#file').prop("files")[0];
var form_data = new FormData();
form_data.append('file', fileData);
$.ajax({
url: "myurl.php",
dataType: 'text',
data: form_data,
cache: false,
contentType: false,
processData: false,
type: "post",
error: function() {
alert('error');
},
success: function(ret) {
alert('sucess');
}
});
}
}
});
HTML
<form enctype="multipart/form-data" action="" method="post">
<hr/>
<div id="filediv">
<input name="file[]" type="file" id="file" accept=".jpg, .gif, .jpeg" />
</div>
<br/>
<input type="hidden" value="" id="class" name="class">
<input type="button" id="add_more" class="upload" value="Add More Files" />
<input type="button" value="Upload File" name="submit" id="upload" class="upload" />
</form>
When I get the post from php using $_FILES['file']['name'] and counting it using
count($_FILES['file']['name']) it returns 1.
When I process further, only the first file is uploaded in the corresponding folder.
Something is probably wrong on line var fileData = $('#file').prop("files")[0];.
Your JS Code should be as below :
$(document).ready(function () {
$('#add_more').click(function () {
$(this).before($("<div/>", {
id: 'filediv'
}).fadeIn('slow').append(
$("<input/>", {
name: 'file[]',
type: 'file',
// Id must be unique
// id: 'file',
class: "file_input",
accept: '.jpg, .jpeg, .gif'
}),
$("<br/><br/>")
));
});
$('#upload').click(function (e) {
var boolAreAllFilesSelected = true;
var objFormData = new FormData();
$.each($(":file"), function ( ) {
if (!$(this).val())
{
alert("File Must Be Selected");
$(this).focus();
return boolAreAllFilesSelected = false;
}
else
{
objFormData.append('file[]', $(this).prop("files")[0]);
}
});
if (boolAreAllFilesSelected)
{
$.ajax({
url: "myurl.php",
dataType: 'text',
data: objFormData,
cache: false,
contentType: false,
processData: false,
type: "post",
error: function () {
alert('error');
},
success: function (ret) {
alert('sucess');
}
});
}
});
});
Your PHP Code should be as below :
<?php
function uploadSingleImage($arrSingleFile = array())
{
if (!empty($arrSingleFile))
{
// Here your image uploading code
}
}
if (!empty($_FILES['file']))
{
$arrFile = $_FILES['file'];
foreach ($arrFile['name'] as $intIndex => $strName)
{
$arrSingleFile["name"] = $strName;
$arrSingleFile["type"] = $arrFile['type'][$intIndex];
$arrSingleFile["tmp_name"] = $arrFile['tmp_name'][$intIndex];
$arrSingleFile["error"] = $arrFile['error'][$intIndex];
$arrSingleFile["size"] = $arrFile['size'][$intIndex];
uploadSingleImage($arrSingleFile);
}
}
else
{
die("You have not uploaded any file.");
}

Categories

Resources