jQuery string appearing in form - javascript

I am seeing a sporadic issue that is causing me a headache to investigate.
I have a PHP page with a basic form with a few simple text fields.
jQuery is used to send this POST data back to the server which in turn saves a record in MySQL and sends email notifications. This works fine throughout the day but randomly (I cannot recreate it). the server will add the same record 5-10 times in the DB and send the same amount of emails.
The only clue to me which is causing this is that random a random jQuery string is included in some of the returned data (see below)
Comments: Please can you sendjQuery17209552029577380006_1461157696021
this to me.
I am using jQuery 1.7.2 which explains the jQuery172, but not sure what the rest of this is.
Any ideas on where I should go with this? I may upgrade jQuery to see if this resolves it but thought I would ask here also?
jQuery 1.7.2 Code Below:
$(document).ready(function() {
$('#quick_form').submit(function(e) {
e.preventDefault();
$.ajax({
url: baseUrl+'products/send_quote',
dataType: 'json',
type: "POST",
async: true,
cache: false,
data: 'prod_id='+$('input[name="prod_id"]').val() + '&' +
'quote_name='+$('input[name="quote_name"]').val() + '&' +
'quote_email='+$('input[name="quote_email"]').val() + '&' +
'quote_phone='+$('input[name="quote_phone"]').val() + '&' +
'quote_company='+$('input[name="quote_company"]').val() + '&' +
'quote_cols='+$('input[name="quote_cols"]').val() + '&' +
'quote_size='+$('input[name="quote_size"]').val() + '&' +
'quote_qty='+$('input[name="quote_qty"]').val() + '&' +
'quote_comments='+$('#quote_comments').val() + '&' +
'token='+$('input[name="token"]').val(),
success: function(response) {
if(response.success) {
$('#quote').slideUp('fast',function() {
$('#quote').empty().html('<div class="successMessage">'+response.message+'</div>');
}).slideDown('fast');
}
else {
$('.errMess').empty();
$.each(response.messages,function(k,v) {
$('.errMess').append('<div>'+v+'</div>').show();
});
}
}
});
});
});

Related

Parsing BBCode on AJAX success

I am in a spot here trying to parse BBCode upon a AJAX success : item.message object. I am using jQuery 1.11. I have tried passing the var result in place of item.message, and only shows the [object] errors. I have tried wrapping item.message with XBBCODE and same thing.
Im not sure what to do, the script is great otherwise. We must parse bbcode to HTML or a method that can be managed PHP-side, but I don't think this is possible over JSON data.
Currently this is my jQuery code:
$(document).ready(function () {
$.ajax({
url: "/ajax/shoutbox.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
// Object array repeated - not working
var result = XBBCODE.process({
text: 'item.message',
removeMisalignedTags: false,
addInLineBreaks: false
});
/*
currentPost = jQuery(this);
postHTML = bbcodeToHTML(currentPost.html());
currentPost.html(postHTML);
*/
html_to_append +=
'<div class="shoutbox-container"><span class="shoutDate">' +
jQuery.timeago(item.date) +
' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
item.avatar +
'" class="shout-avatar" /></span><span class="shoutText">' +
item.message +
'</span></div><br>';
});
$("#shoutbox").html(html_to_append);
$(".shoutbox-container").filter(function () {
return $(this).children().length == 3;
}).filter(':odd').addClass('shoutbox_alt');
$(".shoutbox-container").each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
}
});
});
As you see, I'm trying to make use of the following javascript:
https://github.com/patorjk/Extendible-BBCode-Parser
I've followed the instructions exactly, before moving into the JS above with no success either way. I get this:
[object][Object]
For each iteration of the message object coming back (its a custom AJAX shoutbox).
Commented, you can see another method I have tried to no success. Any help is appreciated!
Update: Working
Thank you, Quiet Nguyen for the suggestion for replacing item.message with result.html and updating text: object

Why append part does not work in ajax call

In the code below after I upload my document I wrote a loop which is supposed to add some images into a division called Divnavigation, but this part doesn't work.
Also when I make it uncommented even my documentViewer can not be loaded. Am I allowed to add something to my division from AJAX call?
function navigate(target) {
$.ajax({
url: '#Url.Action("Download", "Patient")',
type: 'GET',
async: true,
dataType: 'json',
cache: false,
data: { 'filepath': target },
success: function (results) {
// documentViewer.loadDocument(results);
documentViewer.uploadDocumentFromUri(results[results.length -1]);
documentViewer.addEventListener(gnostice.EventNames.afterDocumentLoad, function (eventArgs) {
document.getElementById("TotalPage").textContent = documentViewer.viewerManager.pageCount;
document.getElementById("pageNumber").value = documentViewer.viewerManager.currentPage;
$("#Divnavigation").empty();
//Get all images with the help of model
for (var i = 0; i < results.length; i++) {
$("#Divnavigation").append(" <ul> " +
"<li>" +
"<img src=" + results[i] + ">" + "</img>" +
"" + "" +
"</li>"
+ "</ul>");
}
});
//showImages();
},
error: function () {
alert('Error occured');
}
});
}
Hi Answer to your question first:
Am I allowed to add something to my division from .ajax call?
you are 100% allowed to add something to your division from .ajax call. there is no doubt in that. I done personally many times
This time you are not getting because of some other reason.
Now my suggestion is try using $("#Divnavigation").html().
Official doc: https://api.jquery.com/html/
so first as first step try by putting simple html like this $("#Divnavigation").html("<p>test</p>) and see whether you get the output. if you get then change, html string whatever you want ,that can be hardcoded string or even you can get that string from the action method.
Hope above information was helpful. kindly share your thoughts
Thanks

Javascript url 404 error

I'm have a problem loading a site. Using this code:
$.ajax({
type: "POST",
//url: '#Url.Action("/TellFriendPopup")',
url: '/Property/TellFriendPopup',
data: { "SenderName": SenderName, "senderMail": senderMail, "receiverMail": receiverMail, "comments": comments, "urlLink": urlLink, "subjectId": subjectId },
success: function (data) {
$("#result").html("<ul><li>Name: " + data.nameret + "</li><li>Email: " + data.emailret + "</li><li>Message: " + data.messageret + "</li></ul>");
$(".dialog").dialog("close");
},
The problem is that I had to move the code to a JavaScript file, instead of the MVC4 View, where i could use the #Url.Action method. But it is not working in JavaScript. It Just gives me this error POST http://localhost:54717/Property/ContactPopup 404 (Not Found). The reason as I can see is that it's the Globalization that it's missing. Because the url should look like this http://localhost:54717/da/Property/ContactPopup or http://localhost:54717/en/Property/ContactPopup
You could get the first folder of the pathname. As long as that is where the language code is on every page.
var language = location.pathname.split("/")[1];
url: language + '/Property/TellFriendPopup'
You can have language in hidden field.
var language = document.getElementById('language`).value;
url: '/' + language + '/Property/TellFriendPopup'
Can you try changing this: url: '/Property/TellFriendPopup',
to this url: '../Property/TellFriendPopup',

$ajax is not working with ASP.Net

I am debugging my solution on localhost and this piece of code is not hitting the server
var cartInfo = $j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&date=' + date.val() + '&cart=' + cartInfo;
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
What am I missing here?
the are 2 potential problems
the url
the data
aspx assumes webforms, the page life cycle, etc. when all you want is to send response and get a reply. instead try targeting either a
web service (asmx)
generic handler (ashx)
a static pagemethod think ajax server hanlders embedded within a page object
second is the data. instead of passing a string as the data try passing a json object
data = {
name: "john",
email: "john#email.com",
...
}
Since you are passing the cartInfo as an html, it should be url encoded before it is posted. I think this is wat causing this issue. Try this
var cartInfo =
$j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val()
+ '&email=' + email.val()
+ '&phone=' + phone.val()
+ '&date=' + date.val()
+ '&cart=' + encodeURIComponent(cartInfo);
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
As suggested by in other answer you can also pass data as a key/value pair object to ajax method, jQuery will take care the rest but you still have to encode the html content.
Url Doesnt call any method ?
url: "LightBoxContactSender.aspx",
If yoy are trying to call a WebMethod inside aspx
url :"LightBoxContactSender.aspx/callStaticMethod",
Try to form Data as
dataString = "{'name=' + '"+name.val()+"'}"

Post Forms Using Javascript URL

I'm trying to submit a form to a website not my own (salesforce.com with their web-to-lead function) and I'm doing it through a javascript modal window.
Basically once all the entries are tested and made sure there are no errors, I use this:
if(error_count == 0) {
$.ajax({
type: "POST",
url: "[salesforce url]",
data: "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other,
error: function() {
$('.error').hide();
$('#sendError').slideDown('slow');
},
success: function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
}
});
}
If tested the form without using javascript and the url works, so I'm thinking maybe the way javascript handles the url is the issue?
The issue: the data is not getting successfully submitted to Salesforce. Again, regular HTML form works, javascript doesn't. So I've identified it as a javascript issue.
You cannot make a XHR cross domain request unless the receiving server has allowed it and the browser supports CORS. You can however do a blind submit like this which will assume success:
var $form = $("<form>", {
method: "POST",
action: "[salesforce url]",
target: "my-iframe"
}).appendTo("body");
var $iframe = $("<iframe>", {
name: "my-iframe"
}).bind( "load", function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
$iframe.remove();
$form.remove();
}).appendTo("body");
$.each(("first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other).split("&")), function (index, value) {
var pair = value.split("=");
$form.append("<input>", {
type: "hidden",
name: pair[0],
value: pair[1]
});
});
$form.submit();
+1 for Jim Jose. This sort of thing could be interpreted as an XSS attack against the user, so most likely the browser will not allow it.
You could check out your browser's error logs, see if there's any security errors when you try to run your script. If that doesn't do anything, try to install a tool like Firebug and see if it can pinpoint the problem.
You could also improve your error handling by trying a different sort of method signature for the error function, like this:
error: function(jqXHR, textStatus, errorThrown) {...}
This way you can check what sort of error is being thrown from the Ajax call.

Categories