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.
Related
Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!
Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..
Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.
Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.
If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.
When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify
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();
});
}
}
});
});
});
I am making my registration page for my service. I need to check either Google's Recaptcha successfully verified or not. I decided to use an jquery.ajax.
I have created a function "checkCaptcha()" which sets isCAPT (if captcha valid or not) either true (FLD_VALID) or not (FLD_EMPTY):
function checkCaptcha() {
alert("1");
var captcha_response_text = grecaptcha.getResponse();
var request = $.ajax({
url: "ajax/registrationA.php",
type: "post",
data: { captcha: true, captcha_response: captcha_response_text }
});
request.done(function (response, textStatus, jqXHR) {
alert("2");
if(response) {
isCAPT = FLD_VALID;
}
else {
isCAPT = FLD_EMPTY;
}
});
}
I have to say that "registrationA.php" works fine. No problems there.
After this function, I am checking my submit button handling "onclick" event:
apply_button.onclick = function () {
checkCaptcha();
alert("3");
//alert("Капча " + isCAPT + " Логин " + isLOGIN + " Почта " + isMAIL + " Пароль " + isPASS + " Соответствие " + isPAS2);
return false;
};
You can see three "alert(...)" operators. The problem is that when I press submit button (apply_button) I get three alerts: 1, 3, 2. How can I fix this problem. I need to wait until "requiest.done" executes and only than go to "alert("3")". It is essential because now this function checks fields before checking captcha state which leads to an error because in this case isCAPT equals false.
Please help me with this problem. Maybe there is a better way to check if captcha verified or not (maybe there is a function like "grecaptcha.isVerified").
You need to check deferred.promise() method to work with asynchronous data. Check JQ documentation for that. In a few words it does exactly what you need. It allows to wait until the 2nd asynchronous request is finished and starts the 3d function.
I have my contact form ready to go but for some reason when i gulp it with uglify it returns an error and won't minify. My javascript seems correct and it will uglify when I remove the ajax call but with the ajax call it breaks. Any insight? Here's my js:
$('.contact-form').on('valid.fndtn.abide', function() {
var name = $(".contact-form input#name").val();
var email = $(".contact-form input#email").val();
var message = $(".contact-form textarea#message").val;
// Data for response
var dataString = 'name=' + name +
'& email =' + email +
'& message =' + message;
//Begin Ajax Call
$.ajax({
type: "POST",
url: "php/mail.php",
data: dataString,
success: function() {
$('.contact-form').html("<div id ='success'></div>");
$('#success').html("<h2>Thanks!</h2>")
.append("<p>Dear" + name + "!, I look forward to working with you.</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
JsLint throws error on this code. Removing the trailing comma seems to clear it up:
.fadeIn(1500);
}, /* <-- remove this comma */
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()+"'}"