Weird behavior under chrome and $.ajax after chrome update - javascript

I've an asp.net mvc5 application that on a loginpage does the following Ajax call
$(document).ready(function () {
var formObj = $(".login-form");
$("form input[name=username]").val("user");
$("form input[name=password]").val("password1!");
formObj.submit(function (event) {
event.preventDefault();
console.log("test");
validator = formObj.validate();
if (validator.checkForm()) {
var form = formObj.get();
var rememberMe = $("input:checkbox[name=remember]:checked").val() ? true : false;
$(form.rememberMe).val(rememberMe);
args = {
form: form,
userName: $(form.username).val(),
password: $(form.password).val(),
remember: rememberMe
}
var url = #Url.Content("~/api/auth");
func = $.ajax({
url: url,
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
#if(Request.Params.Get("redirect") != null) {
<text>
window.location = "#Request.Params.Get("redirect")";
</text>
}
else
{
<text>
window.location = "#Url.Content("~/Home")";
</text>
}
}
}
});
}
});
});
If I put this piece of code
var url = #Url.Content("~/api/auth");
it works, otherwise if I quote the url string (as it should be correct)
var url = "#Url.Content("~/api/auth")";
it hangs the browser.
This only happens under chrome as first iussue was reported with Chrome Version 43.0.2357.65 m
What is wrong?
Thanks
UPDATE #1
I've noticed that the problem is there
$.ajax({
url: "/someurl",
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
window.location = "/someotherurl/";
}
}
});
If I sue ajax it breaks...if I use $.post or $.get it works...

Related

Success message doesn't work [duplicate]

This question already has answers here:
Ajax call is never success
(2 answers)
Closed 5 years ago.
I have a little issue,
I'm working on a contact form,
My problem is that the ajax call doesn't show a success message, it sticks
on "sending"
the call is working because it goes to the PHP page and runs the function from there, so everything works fine expect the success message.
I will really glad for assistance, thanks!
this is the JavaScript page:
var nameRegx = /^[' a-zא-ת]+(\s[' a-zא-ת]+)*$/i,
emailRegx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})$/,
phoneRegx = /^(?:0(?!(5|7))(?:2|3|4|8|9))(?:-?\d){7}$|^(0(?=5|7)(?:-?
\d){9})$/,
td = 'p.text-danger',
sa = '#submitAnimate',
sb = '#submitBtn',
nf = '#name',
ef = '#email',
pf = '#phone',
mf = '#message';
$(sa).hide();
$('#contactForm').on('submit', function (event) {
event.preventDefault();
var isValid = true;
$(td).text('');
$(' input[type="text"], textarea').removeClass('error');
$(sb).attr('disabled', true);
$(sa).show();
var userData = {
name: $(nf).val().trim(),
email: $(ef).val().trim(),
phone: $(pf).val().trim(),
message: $(mf).val().trim()
};
if (userData.name.length < 2 || userData.name.length > 70 ||
!nameRegx.test(userData.name)) {
isValid = false;
setError(nf, 'name');
}
if (!emailRegx.test(userData.email)) {
isValid = false;
setError(ef, 'email');
}
if (!phoneRegx.test(userData.phone)) {
isValid = false;
setError(pf, 'phone');
}
if (userData.message.length < 3) {
isValid = false;
setError(mf, 'message');
}
if (!isValid) {
$(sb).attr('disabled', false);
setTimeout(function(){ $(sa).hide(); }, 500);
} else {
$.ajax({
url: "assets/contact_form/process-contact.php",
type: "POST",
dataType: "html",
data: userData,
beforeSend: function () {
$( sb ).val('Sending...');
},
success: function (response) {
if (response == true) {
successmessage = 'Data was succesfully captured';
$("#gmsg").text(successmessage);//THIS MESSAGE DOESN'T APPEAR
} else {
$( sb ).val('Can not send, please try latter');
}
}
});
}
});
$('input[type="text"], textarea').on('keyup', function () {
$(this).next().text('');
});
function setError(target, field) {
setTimeout(function () {
$(target).val('').addClass('error');
$(target).next().text('* Please enter your ' + field);
}, 500);
}
In success : function(response) the object response is not a Boolean. it is the returned response of the ajax call, it will be a string.
just remove the if(response == true) from your code.
then, it will work fine.

$.ajax & $.post working in Chrome

I've tried both $.ajax & $.post and both are not working in Safari or Firefox. Oddly enough, they are working in Chrome. The 'savemarkup.php' call works fine but the 'sendemail.php' is throwing an error (which comes back to my console as an object). The 'sendemail.php' utilizes PhpMailer to send an email based on selections made in the program.
function generatePDF () {
$("#saving").css("display","none");
var email = generateEmail();
var markup = document.documentElement.innerHTML;
$.post (
'savemarkup.php', {
markup: markup,
email: email
},
function (data,status) {
if (status === 'success') {
$("#saving").fadeIn("fast");
//$.post('sendemail.php');
$.ajax({
url: 'sendemail.php',
type: 'POST',
success: function(res) {
console.log( res );
},
error: function (xhr) {
console.log( xhr );
}
});
var saveDelay = 1000;
if (i > 3) {
saveDelay = 333 * i;
}
$("#saving-image").attr("src","http://quote.hekmancontract.com/images/please-wait-pdf.gif");
window.location = 'savepdf.php';
$("#saving").delay(saveDelay).fadeOut("fast");
$("#saving-image").attr("src","http://quote.hekmancontract.com/images/please-wait-saving.gif");
}
});
}
I can't copy and paste the error log very easily so I've included a snapshot.

File not reaching till handler's method

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
$(document).ready(function () {
$("#Button1").click(function (evt) {
var fileUpload = $('[id$=FileUpload1]')[0].value.split(",");
var data = new FormData();
for (var i = 0; i < fileUpload.length; i++) {
data.append(fileUpload[i].name, fileUpload[i]);
}
var options = {};
options.url = "Handler.ashx";
options.type = "POST";
options.data = data;
options.contentType = false;
options.processData = false;
options.success = function (result) { alert(result); };
options.error = function (err) { alert(err.statusText); };
$.ajax(options);
evt.preventDefault();
});
});
This was my jquery and below is my handler file code ......
till end i am getting value while debugging but in motto of making upload multiple images at a while i am unable to have any value in handle
handler code
public void ProcessRequest (HttpContext context) {
string filePath = "FileSave//";
foreach (string file in context.Request.Files)
{
HttpPostedFile filed = context.Request.Files[file];
filed.SaveAs(context.Server.MapPath(filePath + filed.FileName));
context.Response.Write("File uploaded");
}
}
You can try this way if you would like to.
$(document).ready(function () {
$("#Button1").click(function (evt) {
evt.preventDefault();
var formdata = new FormData();
var fileInput = $('#sliderFile'); //#sliderFile is the id of your file upload control
if ($(fileInput).get(0).files.length == 0)
{ //show error
return false;
}
else
{
$.each($(fileInput).get(0).files, function (index,value) {
formdata.append(value.name, value);
});
$.ajax({
url: 'Handler.ashx',
type: "POST",
dataType: 'json',
data: data,
processData: false,
contentType:false,
success: function (data) {
if (data.result) {
//return true or any thing you want to do here
}
else {
//return false and display error
}
},
error: function (data) {
//return false and display error
}
});
}
});//button click close
});//document.ready close
Try it and let me know
EDIT: Remember but, HTML5 FormData is not available in older browsers and your code will silently fail. If you need to support older browsers you might need to perform progressive enhancement by testing the capabilities of the browser and falling back to a standard form POST if the browser doesn't support FormData:
if(window.FormData === undefined) {
// The browser doesn't support uploading files with AJAX
// falling back to standard form upload
} else {
// The browser supports uploading files with AJAX =>
// we prevent the default form POST and use AJAX instead
e.preventDefault();
...
}
For more information on this you can see answer I have accepted for one of my questions. It's pretty much clear there what is the issue regarding. Here is the link
EDIT : Just adding these LINK1 and LINK2 for those who come looking for the answer.
use HttpContextBase[] instead of just HttpContext

Submiting a form via json/ajax/jquery

Here is my code
function generate_clicked()
{
var txt_text_color = $('#txt_text_color').val();
var url='process.php?';
url+='txt_text_color='+encodeURIComponent(txt_text_color);
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}
This works for my purposes but if I added another form element I would tediousily have to add var example =$('....').val();
and
url+='example'+endcodeU.....
Which I will be having over 100 elements, then I would retreview them on process with
$txt_text_color = $_REQUEST['txt_text_color'];
My question is, how can I serialize this (I think that's what I need to do) so that I don't have to write those two varibles names each time I make a new form object.
I need to save get/post those varibles in process.php to use them.
Sorry if this doesn't make sense, I'm still learning.
Try form.serialize()
http://api.jquery.com/serialize/
Your code would look something like this:
function generate_clicked()
{
var formData = $('#form').serialize();
var url='process.php?';
url+=formData;
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}

jQuery AJAX works on mobile safari, but not a UIWebView?

I have a basic jQuery ajax function to log the user in via a UIWebView. However, for some reason it returns blank when it's in a UIWebView. It works fine in mobile safari, and chrome and firefox on my computer.
Here's my code:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});
The theRetrievedData just returns blank on the alert.
Please help!
PS: The app is called "Dudles" in the app store (it's free) if you want to try to login. You will get a blank message from the alert.
Can you post your PHP code as well?
I refactored the code you wrote into how I would write it just to see if I could spot any bugs, and nothing seemed glaringly incorrect. Here is what I have so far:
$(document.body).on('click', '#login_button', function () {
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: $(this).closest('form').serialize(),
success: function (response) {
var delimiter = "?!?success?!?";
var isSuccessful = response.indexOf(delimiter) !== -1;
if (!isSuccessful) {
// handle error
return;
}
$('#content').fadeOut(500, function () {
location = response.split(delimiter)[1];
});
}
});
});
try to send ajax request with async:true, like this:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
async:true,
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});

Categories

Resources