I have a rather large and complex code of SVG that generates using JavaScript and jQuery dynamically based on the pages information.
I then have an AJAX post save.
What am I failing to do to convert this to post the image data properly?
var canvas = $("#canvas")[0];
var string= canvas.toDataURL("image/png");
base64=string.replace("data:image/png;base64,", "");
var rid = kRid || "";
var fileN = " Product " + rid + ".png";
var req = "";
req += "<qdbapi>";
req += "<field fid='323' filename='" + fileN + "'>" + base64 + "</field>";
req += "</qdbapi>";
$.ajax({
type: "POST",
contentType: "text/xml",
dataType: "xml",
processData: false,
//url altered
url: "https://removed.quickbase.com/db/removedDBID?act=API_EditRecord&rid=" + rid,
data: req,
success: function(responce) {
//auto reload page
var str = window.location.href;
setTimeout(function() {
window.location.href = str;
}, 5000);
}
})
The idea came from this snippet of code that I used else ware to get current PNG files and move them:
$.get(url, function(xml) {
var promises = [];
$("record", xml).each(function() {
var url = $("f#9 url", this).text();
xhr.responseType = "arraybuffer";
xhr.onload = function() {
var arrayBuffer = xhr.response;
var base64 = btoa([].reduce.call(new Uint8Array(arrayBuffer), function(p, c) {
return p + String.fromCharCode(c)
}, ''))
var req = "";
req += "<qdbapi>";
req += "<field fid='6' filename='" + name + "'>" + base64 + "</field>";
req += "<field fid='54' >" + Rid + "</field>";
req += "<field fid='44' >" + comment + "</field>";
req += "</qdbapi>";
... then the AJAX post.
I do not have access to do this via PHP.
(Posted on behalf of the OP).
I forgot to add == to mark the end of the file so:
var string= canvas.toDataURL("image/png");
string+="==";
base64=string.replace("data:image/png;base64,", "");
and huzza it works...
Related
I am trying to stringify textbox input data and uploaded images in json format to send through ajax.but getting error at alert(file[0].name + " is not a valid image file.");
and at this point in ajax part data: '{user: "' + JSON.stringify(user) + '",byteData: "' + byteData + '", imageName: "' + fileName + '", contentType: "' + contentType + '" }',
Given below is the script which is accepting value from textboxes, labels and image upload control and then stringify all the values and passing it through Ajax in json Format.
enter image description here
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
$("#pdfForm").on('change', 'input[name=flImage]', function () {
alert('Thanks for selecting image');
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
$(document).on("click", "[id*=btnFrmSubmit]", function () {
alert("hi");
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
user.REVISION = $("#Revision").text();
user.REVISION_DATE = $("[id*=Revision_Date]").text();
user.P_GROUP = $("[id*=P_Group]").val();
user.PROD_DESC = $("[id*=Prod_Desc]").val();
user.N_I_PRD_STD = $("[id*=N_I_Prd_Std]").val();
user.APPLN = $("[id*=Appln]").val();
user.FRM_SUPP = $("[id*=Frm_Supp]").val();
user.CREATED_DATE = $("#Revision_Date").text();
user.CREATED_BY = $("[id*=lblUserName]").text();
var byteData = reader.result;
console.log(byteData);
byteData = byteData.split(';')[1].replace("base64,", "");
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: '{user: "' + JSON.stringify(user) + '",byteData: "' + byteData + '", imageName: "' + fileName + '", contentType: "' + contentType + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
For ajax file upload, it is better to use Formdata refer the link below
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Hope this helps. Please feel free to ask for any clarifications
I have a C# Webservice which I'm contacting through URL to retrieve data. The Webservice is lying on a local server in our company network. For example: I have a specific function to get street names, the url to webservice is like this :
Request URL:http://10.1.1.32:8080/webportale_ger_webservice.asmx/SelectStreets
This URL is stored in localStorage.
After deleting browsers cache the request URL has changed, which makes absolutly no sense to me:
http://10.1.1.32:8081/nullSelectStreets
The port is wrong and what about that null?
After trying this request several times again, the url value changes to the correct value.
My jQuery ajax Request looks like this:
var UrlToWebservice = window.localStorage.getItem("url_to_webservice");
$(document).on("keyup", "#input_strasse", function () {
var inputStr = $('#input_strasse').val();
var charStr = inputStr.charAt(0).toUpperCase() + inputStr.substr(1);
console.log("buchstabensuppe: ", charStr)
$.ajax({
type: 'POST',
url: UrlToWebservice + 'SelectStreets',
data: { 'charStr': charStr },
crossDomain: true,
dataType: 'xml',
success: function (response) {
$("input_strasse_datalist").empty();
var strassen = new Array;
$(response).find('STRASSE').each(function () {
var strasse = $(this).find('NAME').text();
var plz = $(this).find('PLZ').find('plz').text();
var ort = $(this).find('PLZ').find('ORT').text();
var arstrasse = $(this).find('AR').first().text();
console.log("arstrasse ", arstrasse)
$("#input_strasse_datalist").append('<option data-ar = ' + arstrasse + ' value = "' + strasse + ' (' + plz + ', ' + ort + ')">' + strasse + ' (' + plz + ', ' + ort + ')</option>')
$("#input_plz").val(plz)
$("#input_ort").val(ort)
})
},
error: function () {
window.location.hash = "httperror";
}
})
})
The value in localStorage is: http://10.1.1.32:8080/webportale_ger_webservice.asmx/
What am I doing wrong?
Thanks a lot.
Question I want to be able to submit multiple records with my ajax form submission. This form is a partial and I want to be able to submit multiples of this form each time. This is what I have so far I can't get my textbox.vals anymore using a serialized string. Any help would be greatly appreciated.
Here is my function
function SaveDim() {
$.ajax({
type: "POST",
url: "/sheet/sheet_form_create.html/_dim",
//dataType: "json",
data: $('#form').serialize()
+
"&description=" + $('#id_description').val() +
"&style=" + $('#id_style').val() +
"&target=" + $('#id_target').val() +
"&upper_limit=" + $('#id_upper_limit').val() +
"&lower_limit=" + $('#id_lower_limit').val() +
"&inspection_tool=" + $('#id_inspection_tool').val() +
"&critical=" + $('#id_critical').val() +
"&units=" + $('#id_units').val() +
"&metric=" + $('#id_metric').val() +
"&target_strings=" + $('#id_target_strings').val() +
"&ref_dim_id=" + $('#id_ref_dim_id').val() +
"&nested_number=" + $('#id_nested_number').val() +
"&posistion=" + $('#id_position').val() +
"&met_upper=" + $('#id_met_upper').val() +
"&met_lower=" + $('#id_met_lower').val() +
"&valc=" + $('#id_valc').val() +
"&sheet_id=" + $('#id_sheet_id').val() +
"",
success: function (json) {
console.log(json);
alert(json);
}
});
}
Here is my add_dimension method in views.py
def add_dimensions(request):
if request.method == 'POST':
c_date = datetime.now()
u_date = datetime.now()
description = request.POST.get('description')
style = request.POST.get('style')
target = request.POST.get('target')
upper_limit = request.POST.get('upper_limit')
lower_limit = request.POST.get('lower_limit')
inspection_tool = request.POST.get('inspection_tool')
critical = request.POST.get('critical')
units = request.POST.get('units')
metric = request.POST.get('metric')
target_strings = request.POST.get('target_strings')
ref_dim_id = request.POST.get('ref_dim_id')
nested_number = request.POST.get('nested_number')
met_upper = request.POST.get('met_upper')
met_lower = request.POST.get('met_lower')
valc = request.POST.get('valc')
sheet_id = request.POST.get('sheet_id')
data = {}
dim = Dimension(
description=description,
style=style,
target=target,
upper_limit=upper_limit,
lower_limit=lower_limit,
inspection_tool=inspection_tool,
critical=critical,
units=units,
metric=metric,
target_strings=target_strings,
ref_dim_id=ref_dim_id,
nested_number=nested_number,
met_upper=met_upper,
met_lower=met_lower,
valc=valc,
sheet_id=sheet_id,
created_at=c_date,
updated_at=u_date)
dim.save()
data['description'] = dim.description;
data['style'] = dim.style;
data['target'] = dim.target;
data['upper_limit'] = dim.upper_limit;
data['lower_limit'] = dim.lower_limit;
data['inspection_tool'] = dim.inspection_tool;
data['critical'] = dim.critical;
data['units'] = dim.units;
data['metric'] = dim.metric;
data['target_strings'] = dim.target_strings;
data['ref_dim_id'] = dim.ref_dim_id;
data['nested_number'] = dim.nested_number;
data['met_upper'] = dim.met_upper;
data['met_lower'] = dim.met_lower;
data['valc'] = dim.valc;
data['sheet_id'] = dim.sheet_id;
return HttpResponse(json.dumps(data), content_type="application/json",)
else:
dim_form = DimForm()
return render(request, 'app/_dim.html', {'dim_form': dim_form})
Just do it this way
function SaveDim() {
$.ajax({
type: "POST",
url: "/sheet/sheet_form_create.html/_dim",
//dataType: "json",
//make sure you give your form an id of "dim_form"
data: $('#dim_form').serialize()
success: function (json) {
console.log(json);
alert(json);
}
});
}
You need to concat correctly your data string like:
data: $('#form').serialize() + "&description=" + $('#id_description').val() + "&style=" + $('#id_style').val(); // ...
I am trying to pass a value from Javascript to ASP pages. But it can't run properly.
This is my Javscript:
function btn_upgrade_onclick() {
var dlr = document.getElementById("<%txt_sapcode.ClientID%>").value;
var dlrname = document.getElementById('<%=tex_dealername.ClientID %>').value;
var addr1 = document.getElementById('<%=txt_addr1.ClientID %>').value;
var addr2 = document.getElementById('<%=txt_addr2.ClientID %>').value;
var addr3 = document.getElementById('<%=txt_addr3.ClientID %>').value;
var mobno = document.getElementById('<%=txt_mob.ClientID %>').value;
var stat = document.getElementById('drp_state').value;
$.ajax({
async: false,
type: "POST",
url: "DealerDetails.aspx/UpdateDealer",
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr + "',DlrName:'" + dlrname + "',Dlrad1:'" + addr1 + "',Dlrad2:'" + addr2 + "',Dlrad3:'" + addr3 + "',DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
$.each(msg.d, function (index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function () {
sprtengId = $(this).val();
});
},
error: function () {
alert("Error");
}
});
}
And the value are passed to the function
region update
[WebMethod]
public static DataSet UpdateDealer(Int32 DlrId,Int32 DlrCode,string DlrName,string Dlrad1,string Dlrad2,string Dlrad3,Int16 Dlrddd,Int32 DlrLan,Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update=obj.UpdateDealerDetails(DlrId,DlrCode,DlrName,Dlrad1,Dlrad2,Dlrad3,DlrMob);
}
catch {}
return update;
}
#endregion
When I press the Update button, it will call the Javascript function and then it passes the value in the text boxes to the ASP code UpdateDealer();
Before am writing this function in Javascript all other functions worked properly but now it's not working properly
There is a bug in your first line of js.
var dlr = document.getElementById("**<%**txt_sapcode.ClientID%>").value;
Fix this (= missing) and check.
Where have you defined, dealerID
data: "{DlrId:'" + dealerID + "',DlrCode:'" + dlr
also, i dont' think your stat variable is initialized with following line of code just confirm.
var stat = document.getElementById('drp_state').value;
Make sure you debug and variables you have defined are initialized.
remove static from
public DataSet UpdateDealer(Int32 DlrId, Int32 DlrCode, string
DlrName, string Dlrad1, string Dlrad2, string Dlrad3, Int16 Dlrddd,
Int32 DlrLan, Int32 DlrMob)
{
DataSet update = new DataSet();
try
{
update = obj.UpdateDealerDetails(DlrId, DlrCode, DlrName, Dlrad1, Dlrad2, Dlrad3, DlrMob);
}
catch { }
return update;
}
function btn_upgrade_onclick() {
var dealerID = "1";
var dlr = "1";
var dlrname = "abc";
var addr1 = "india";
var addr2 = "delhi";
var addr3 = "delhi";
var mobno = "1234567890";
var stat = "";
var DlrLan = "123";
var Dlrddd = "1123";
$.ajax({
type: "POST",
url: "AutoComplete.asmx/UpdateDealer",
data: "{DlrId:'" + dealerID + "', DlrCode:'" + dlr + "', DlrName:'" + dlrname + "', Dlrad1:'" + addr1 + "' , Dlrad2:'" +
addr2 + "', Dlrad3:'" + addr3 + "', Dlrddd:'" + Dlrddd + "', DlrLan:'"
+ DlrLan + "', DlrMob:'" + mobno + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#drp_support").get(0).options.length = 0;
$("#drp_support").get(0).options[0] = new Option("--Select--", "0");
$("#drp_support").unbind("change");
alert(data);
$.each(msg.d, function(index, item) {
$("#drp_support").get(0).options[$("#drp_support").get(0).options.length] = new Option(item.Display, item.Value);
});
$("#drp_support").bind("change", function() {
sprtengId = $(this).val();
});
},
error: function() {
alert("Error");
}
});
}
I need var order to give me xml and in the onclick function I want to pass this xml to matte_design_change(). Right now when I do, what outputs when I call console.log it gives me "[object Object]" with nothing else.
I have the following code:
function matte_design_change_design_type(element)
{
var selected_type = element.options[element.selectedIndex].value;
$(document).ready(function()
{
$.ajax({
type: "GET",
url: SITE_URL + "/system/components/xml/" + selected_type,
dataType: 'xml',
success: function(xml) {
var output = [];
$('component', xml).each(function(i, el) {
var thumb = $("thumb", this).text();
var cid = $("cid", this).text().replace("[DEFAULT_MATTE_CID]", "");
var order = $("Order", this); //I want this to be xml
output.push('<img id="cid_' + cid + '" src="' + SITE_URL + '/system/components/compimg/' + thumb + '/flashthumb" alt="' + cid + '" onclick="matte_design_change(\'' + cid + '\', \'' + thumb + '\', \'' + order + '\');" />'); // I want to pass order as xml to matte_design_change
$('#matte_designs_strip_wrapper').html(output.join(''));
});
}
});
});
}
function matte_design_change(cid, thumb, order)
{
$( "#frame_window" ).empty();
var imageObj = new Image();
imageObj.onload = (function()
{
document.getElementById("frame_window").appendChild(imageObj);
});
imageObj.id = "matte_" + cid;
imageObj.src = SITE_URL + '/system/components/compimg/' + thumb + '/full_thumb';
console.log(order);
}
You should be able to easily convert the XML to a string, and then pass it as a parameter. Many examples around; this one might serve:
http://jonahacquah.blogspot.it/2012/03/convert-xmldocument-to-xml-string-in.html