$.ajax & $.post working in Chrome - javascript

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.

Related

Weird behavior under chrome and $.ajax after chrome update

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

How to add data parameter in ajaxSend properly?

In some circumstance I need to add POST parameter programmatically to AJAX request.
I'm trying something like this:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
ajaxOptions.data = "additional_key=additional_value&" + ajaxOptions.data;
ajaxOptions.context.data = "additional_key=additional_value&" + ajaxOptions.context.data;
console.log(ajaxOptions, 'ajaxOptions');
});
But additional_key isn't appear in $_POST array.
You can use ajaxPrefilter for this :
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
if (originalOptions.type !== 'POST' || options.type !== 'POST') {
return;
}
options.data = $.extend(originalOptions.data, { yourdata : yourvalue });
});
See http://api.jquery.com/jquery.ajaxprefilter/ for more infos.
testing your above code gave me an error that ajaxOptions.context was undefined.
First, I'd advise that you check for existence first: (Assuming that context is ever going to be defined)
if(ajaxOptions.context) {
ajaxOptions.context.data = "additional_key=additional_value&" + ajaxOptions.context.data;
} else {
ajaxOptions.data = "additional_key=additional_value&" + ajaxOptions.data;
}
Sending off a mock AJAX request showed me that the data is being passed through when inspected in Firebug.
I tested the code by removing the context line, and it seemed to work:
Code:
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
if(ajaxOptions.context) {
ajaxOptions.context.data = "additional_key=additional_value&" + ajaxOptions.context.data;
} else {
ajaxOptions.data = "additional_key=additional_value&" + ajaxOptions.data;
}
});
$.ajax({
'url': 'test.php',
'data': {'foo':'bar'},
'type': 'POST'
});
Inspection:
Key Value
additional_key additional_value
foo bar
Edit: Tested with JQuery 1.7.1 I've noticed that you're running a lower version of jQuery.
$(document).ready(function() {
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
if (ajaxOptions.extraData) {
ajaxOptions.extraData.additional_key = 'additional_value';
}
});
});
This only work for me (jQuery 1.4.4)

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

Javascript - XMLHttpRequest failing in Internet Explorer

* SOLVED * Answer is in separate post below
This code runs fine in FireFox but it will not run in Internet Explorer 8. It gives me the error of "access denied. Is there something I am missing?
function loadXMLDoc(dname){
if (window.XMLHttpRequest){
var xhttp=new XMLHttpRequest();
}
else{
var xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc=loadXMLDoc("notSchema.xml");
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
It specifically doesn't like the .open() and the .send()
Edited...
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
xmlDoc = http;
alert(http);
x=http.getElementsByTagName("ROOT_NODE_ID");
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Edited the Code once again. What I'm trying to do is load the XML, parse for the tag "ROOT_NODE_ID" and then get that value and store it into an array
When I run that code in firefox, it returns 51, which is the number of ROOT_NODE_ID tags and fills the tree that I am making.
When I run the same exact code in IE8, it does not even alert.
I'm Stumped.
I figured it out. Like I said before, if you run the code above in Firefox, it returns the 'object' and if you run it in IE8, it returns the contents of the object. I solved this problem by loading the content of the object again in IE8, thus turning the content of the object back into an object that will be ready to be parsed. If that makes any sense.
Just to clarify to people that are just visiting this thread. When I called 'alert(http);' in firefox, it would return '[object XMLDocument]', but in IE8 it would return the actual contents of '[object XMLDocument]'.
var treeArray=new Array();
var count = 0;
var x;
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(http){
var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
//Loading the contents of the object 'http' a second time, which turns it into an object again.
xmlDocument.loadXML(http);
x = xmlDocument.getElementsByTagName("ROOT_NODE_ID");
alert(x.length);
},
error: function(html){
alert('failure: ' + html);
}
});
}
loadXMLDoc("notSchema.xml");
for (var i=0;i<x.length;i++)
{
if(x[i].childNodes[0] == undefined) {
treeArray[count]="null";
count++;
}else{
//return ROOT_NODE_ID
treeArray[count]=x[i].childNodes[0].nodeValue;
count++;
}
}
Zack,
You can use jquery to do the ajax call - jquery will do everything properly behind the curtains.
In your case here:
function loadXMLDoc(dname){
var request = $.ajax({
url: dname,
type: "GET",
async: false,
data: {},
success: function(html){
var x=xmlDoc.getElementsByTagName('ROOT_NODE_ID');
},
error: function(html){
alert('failure: ' + html);
}
});
}

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