Where my mistake in converting jquery ajax to pure js ajax request - javascript

That's my JQuery code which is currently working ->
$("#newsLetter-form").on('submit',function(event){
event.preventDefault();
email = $('#emailId').val();
console.log(email);
$.ajax({
url: '/subscribes/emailSubscribe',
type:'POST',
data:{
"_token": "{{ csrf_token() }}",
email:email,
},
success:function(response){
console.log(response);
$('#responseFromSub').text("Registred!");
$('#responseFromSub').css('background','lightgreen')
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
error:function(response){
console.log(response);
var val = 'asdasd:111122:123123123';
var response1 = response.responseJSON.message.substring(response.responseJSON.message.indexOf("\"title\":"));
response1 = response1.split(":").pop();
response1 = response1.split(',')[0];
response1 = response1.replace("\"", "");
response1 = response1.replace("\"", "");
console.log(response1);
$('#responseFromSub').text(response1);
$('#responseFromSub').css('background','red');
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
});
});
And this is my converted code which isn't working, it says 400 bad request wrong data. I'm using laravel and mailchimp for newsletter with jquery everything is working but with this pure js code, no ->
function myFunc123() {
var email1 = document.getElementById("emailId").value;
alert(email1);
var data = {
"_token": '{{ csrf_token() }}',
email: email1
};
var boundary = String(Math.random()).slice(2);
var boundaryMiddle = '--' + boundary + '\r\n';
var boundaryLast = '--' + boundary + '--\r\n'
var body = ['\r\n'];
for (var key in data) {
body.push('Content-Disposition: form-data; name="' + key + '"\r\n\r\n' + data[key] + '\r\n');
}
body = body.join(boundaryMiddle) + boundaryLast;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/subscribes/emailSubscribe', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.onreadystatechange = function () {
if (this.readyState != 4) return;
alert(this.responseText);
}
xhr.send(body);
}
I fixed it the problem was here ->
var email1 = document.getElementById("emailId").value;
alert(email1);
var data = {
"_token": '{{ csrf_token() }}',
email: email1
Now it's working..
BUT the page is refreshing after request how can I disable refreshing ?

You forgot event.preventDefault(), which was in the jQuery code. The default behaviour is to refresh the page on submit (which is a very dumb default), you want to prevent this.

Okay, final converted version looks like that.
var ele = document.getElementById("newsLetter-form");
ele.addEventListener("submit", handleEmail, false);
function handleEmail(event) {
event.preventDefault();
var email1 = document.getElementById("emailId").value;
var data = {
"_token": '{{ csrf_token() }}',
email: email1
};
var boundary = String(Math.random()).slice(2);
var boundaryMiddle = '--' + boundary + '\r\n';
var boundaryLast = '--' + boundary + '--\r\n'
var body = ['\r\n'];
for (var key in data) {
body.push('Content-Disposition: form-data; name="' + key + '"\r\n\r\n' + data[key] + '\r\n');
}
body = body.join(boundaryMiddle) + boundaryLast;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/subscribes/emailSubscribe', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.onreadystatechange = function () {
if(xhr.status===200)
{
document.getElementById("responseFromSub").innerHTML="Registered";
document.getElementById("responseFromSub").style.background="lightgreen";
document.getElementById("newsLetter-form").style.display="none";
document.getElementsByClassName("sucsessMessage")[0].style.display="block";
setTimeout(function () {
document.getElementsByClassName("sucsessMessage")[0].style.display="none";
document.getElementById("newsLetter-form").style.display="flex";
}, 3000);
}
else
{
document.getElementById("responseFromSub").innerHTML="Something goes wrong..";
document.getElementById("responseFromSub").style.background="red";
document.getElementById("newsLetter-form").style.display="none";
document.getElementsByClassName("sucsessMessage")[0].style.display="block";
setTimeout(function () {
document.getElementsByClassName("sucsessMessage")[0].style.display="none";
document.getElementById("newsLetter-form").style.display="flex";
}, 3000);
}
}
xhr.send(body);
}

Related

Trying to stringify textbox input data and uploaded images in json format to send through ajax

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

SVG to PNG to AJAX API post

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...

Formdata and XMLhttpRequest not Working on IE 11

I am using formdata and XMLHttpRequest to submit my form using ajax. Now everything works well on other browsers except IE 11 . Note I am uploading a file using this ajax request.
My code is as follows
var form = document.getElementById('chatMessageForm');
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', form.getAttribute('action'), true);
xhr.responseType = "json";
xhr.send(formData);
xhr.onload = function (e) {
var new_message_response = xhr.response; // not responseText
console.log(new_message_response);
if (new_message_response.conversationStatus) {
alert('This Conversation is disabled by Other User');
jQuery('.conversationadd .messagebox #msgbox').attr('disabled',true);
} else {
var downloadLink = '';
if (new_message_response.attachment != '' && new_message_response.attachment != null) {
downloadLink = 'Download Attachment';
}
jQuery('.chatmessageinner').append('<div class="singlemsg right" id=" ' + new_message_response.id + ' ">'
+ '<p> ' + msg + ' </p>'
+ '<div class="messagefooter">'
+ '<span class="time">' + new_message_response.time + '</span>'
+ downloadLink
+ '</div>'
+ '</div>');
var objDiv = document.getElementsByClassName("chatmessageinner")["0"];
objDiv.scrollTop = objDiv.scrollHeight;
}
}
I have used jQuery.ajax instead of XMLhttpRequest now everything works smooth as silk :) Now my code looks like this:
var form = document.getElementById('chatMessageForm');
var formData = new FormData(form);
jQuery.ajax({
url: form.getAttribute('action'),
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
var new_message_response = data;
if (new_message_response.conversationStatus)
{
alert('This Conversation is disabled by Other User');
jQuery('.conversationadd .messagebox #msgbox').attr('disabled', true);
}
else
{
var downloadLink = '';
if (new_message_response.attachment != '' && new_message_response.attachment != null)
{
downloadLink = 'Download Attachment';
}
jQuery('.chatmessageinner').append('<div class="singlemsg right" id=" ' + new_message_response.id + ' ">'
+ '<p> ' + msg + ' </p>'
+ '<div class="messagefooter">'
+ '<span class="time">' + new_message_response.time + '</span>'
+ downloadLink
+ '</div>'
+ '</div>');
var objDiv = document.getElementsByClassName("chatmessageinner")["0"];
objDiv.scrollTop = objDiv.scrollHeight;
}
},
error: function (data) {
alert("error");
}
});

Posting Image Event on javascript facebook api

Ok I'm stuck, I want to create an event in facebook, using javascript facebook api, and I want to load an image on the event cover. I can not figure out how I can do it.
I create an image in a canvas and I can upload to facebook using an sendAsBinnary function
from: https://stackoverflow.com/a/5303242/945521
And this function
Facebook.prototype.postImageToFacebook = function(authToken, filename, mimeType, imageData, message){
try {
showMessage("Creating post...");
// this is the multipart/form-data boundary we'll use
var boundary = '----------RaNdOm_crAPP' + getBoundary();
// let's encode our image file, which is contained in the var
var formData = '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="source"; filename="' + filename + '"\r\n';
formData += 'Content-Type: ' + mimeType + '\r\n\r\n';
for (var i = 0; i < imageData.length; ++i)
{
formData += String.fromCharCode(imageData[ i ] & 0xff);
}
formData += '\r\n';
formData += '--' + boundary + '\r\n';
formData += 'Content-Disposition: form-data; name="message"\r\n\r\n';
formData += message + '\r\n';
formData += '--' + boundary + '--\r\n';
//var xhr = new XMLHttpRequest();
var xhr = null;
if (window.XDomainRequest) {
xhr = new XDomainRequest();
}
else if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onload = function() {
window.alert("The photo was published successfully!!");
};
showMessage("Sending request...");
xhr.open("POST", "https://graph.facebook.com/me/photos?access_token=" + authToken, true);
if (xhr.setRequestHeader)
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
xhr.sendAsBinary(formData);
} catch (ex) {
stopWaitingSpin();
debugLog(ex);
}
};
and with this
FB.api("/me/events", "POST", {
"name": name,
"start_time": start_time,
//"end_time":end_time,
"description": description,
"location": location,
//"location_id":location_id,
"privacy_type": privacy_type
},
function(response) {
if (response && !response.error) {
var event_id = response.id;
console.log(response);
}
});
I can create a event.
But what need to call to send the image to the cover on event???
Thank's to all
Actually its nowhere mentioned in the documentation yet, but to publish a cover photo on an event you need to call \POST /{event-id} with param cover_url:
{event-id} could be obtained as a result when you created an event.
FB.api("/{event-id}", "POST", {
cover_url: {image-url}
},
function(response) {
console.log(response); // you'll get the response as 'true' or 'false'
});

How to pass values to asp pages from javascript?

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");
}
});
}

Categories