How to make XMLHttpRequest work over HTTPS on google chrome? - ajax

I researched about this a lot, but couldn't find the magic.
Actually I want to populate a list of city pin code no. using JQuery autocomplete UI. It's a https page. It's working in Firefox but not in Google Chrome. Can anyone help me to resolve this issue. Thanks in Advance.
In the following is my code:
function zipAutoCompletet(prefix) {
jQuery("#" + prefix + "_zip").autocomplete({
source: function(request, response) {
jQuery.ajax({
url: "http://ws.geonames.org/postalCodeSearchJSON",
dataType: "jsonp",
data: {
style: "full",
maxRows: 12,
postalcode_startsWith: request.term
},
success: function(data) {
response(
jQuery.map(data.postalCodes, function(item) {
return {
label:
item.placeName +
(item.adminCode1
? ", " + item.adminCode1
: "") +
", " +
item.postalCode +
", " +
item.countryCode,
value: item.postalCode
};
})
);
jQuery(".ui-autocomplete").css("width", "188px");
}
});
},
minLength: 2,
select: function(event, ui) {
var myString = new String(ui.item.label);
var address = myString.split(",");
jQuery("#" + prefix + "_city").val(address[0]);
jQuery("#" + prefix + "_city").addClass("activated");
jQuery("#" + prefix + "_city").trigger("change");
jQuery("#" + prefix + "_city")
.parents(".row")
.removeClass("error-row");
jQuery("#" + prefix + "_city")
.parents(".row")
.addClass("ok-row");
var countryCode = address[3] ? address[3] : address[2];
countryCode = jQuery.trim(countryCode);
var countryName = jQuery(
"#" +
prefix +
'_country option[value="' +
jQuery.trim(countryCode) +
'"]'
).text();
jQuery("#countryContainer .jqTransformSelectWrapper span").html(
countryName
);
jQuery("#countryContainer .jqTransformSelectWrapper").addClass(
"selected-jqtranform"
);
jQuery("#" + prefix + "_country")
.parents(".row")
.addClass("ok-row");
jQuery("#" + prefix + "_country")
.parents(".row")
.removeClass("error-row");
jQuery("#" + prefix + "_country").val(jQuery.trim(countryCode));
var stateCode = address[2] ? address[1] : "";
stateCode = jQuery.trim(stateCode);
if (countryCode == "US") {
var base = base_url;
base = base.replace("https", "http");
jQuery.ajax({
url: base + "/getStateName",
dataType: "jsonp",
data: { stateCode: stateCode },
success: function(data) {
stateName = data;
jQuery("#jc_state").val(stateName);
jQuery("#jc_state").addClass("activated");
jQuery("#jc_state")
.parents(".row")
.removeClass("error-row");
jQuery("#jc_state")
.parents(".row")
.addClass("ok-row");
jQuery("#jc_state").trigger("change");
formValidate();
}
});
} else {
stateName = stateCode;
jQuery("#jc_state").val(stateName);
jQuery("#jc_state").addClass("activated");
jQuery("#jc_state")
.parents(".row")
.removeClass("error-row");
jQuery("#jc_state")
.parents(".row")
.addClass("ok-row");
jQuery("#jc_state").trigger("change");
formValidate();
}
jQuery("#" + prefix + "_zip")
.parents(".row")
.addClass("ok-row");
jQuery("#" + prefix + "_zip")
.parents(".row")
.removeClass("error-row");
},
open: function() {
jQuery(this)
.removeClass("ui-corner-all")
.addClass("ui-corner-top");
},
close: function() {
jQuery(this)
.removeClass("ui-corner-top")
.addClass("ui-corner-all");
},
change: function(event, ui) {
if (ui.item === null) {
jQuery("#" + prefix + "_zip")
.parents(".row")
.removeClass("ok-row");
jQuery("#" + prefix + "_zip")
.parents(".row")
.addClass("error-row");
$("#" + prefix + "_zip").val("");
}
}
});
}

If you are on https page, browser will block requests to non-secure resources (http).
Regularly you should see some notification about that. Looks like other browsers does not block non secure AJAX requests on secured pages by default, but google chrome does.
In your code, you have hardcoded URL:
url: "http://ws.geonames.org/postalCodeSearchJSON",
If that is cross domain request and it supports HTTPS, you can change it like this:
url: "//ws.geonames.org/postalCodeSearchJSON",
As you can see, protocol is not specified there. Browser will take page default protocol (http or https) and use it to request data.

Related

My jquery and ajax call is not responding and showing unexpected error in console

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

SharePoint 404 Error When Calling workflow.asmx Web Service

With the following code I receive a 404 (Not Found) error. I can see that the workflow.asmx URL is correct and I can access it through a browser. I've used similar code in the past on other projects.
function StartExpenseReportToPdfWorkflow(itemId) {
var targetUrl = "../_vti_bin/workflow.asmx";
var listName = "Expense Reports";
var itemUrl = getUrlForListItemId(listName, itemId);
var soapEnv = [];
soapEnv.push("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
soapEnv.push("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
soapEnv.push(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"");
soapEnv.push(" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
soapEnv.push("<soap:Body>");
soapEnv.push("<StartWorkflow xmlns=\"http://schemas.microsoft.com/sharepoint/soap/workflow/\">");
soapEnv.push("<item>" + itemUrl + "</item>");
soapEnv.push("<templateId>" + expenseReportWorkflowTemplateId + "</templateId>");
soapEnv.push("<workflowParameters><data>");
soapEnv.push("</data></workflowParameters>");
soapEnv.push("</StartWorkflow>");
soapEnv.push("</soap:Body>");
soapEnv.push("</soap:Envelope>");
//get web service url:
var spsdiscoUrl = $("head link[rel='alternate']:eq(0)").attr("href");
var spWSUrlPrefix = spsdiscoUrl.substr(0, spsdiscoUrl.length - 13);
$.ajax({
cache: false,
url: targetUrl, //spWSUrlPrefix + "workflow.asmx",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction",
"http://schemas.microsoft.com/sharepoint/soap/workflow/StartWorkflow");
},
type: "POST",
dataType: "xml",
data: soapEnv.join(""),
complete: function (msg) {
if (msg.status === 200) { } else {
//Failure
jsUtil.throwError("Well, this is awkward. Something went wrong and we're really sorry. " + msg.statusText, "Error calling Published Workflow: " + msg.statusText);
}
},
contentType: "text/xml; charset=utf-8"
});
}
function getUrlForListItemId(listName, itemId) {
var domain = document.domain;
var spsdiscoUrl = $("head link[rel='alternate']:eq(0)").attr("href");
var webPrefix = spsdiscoUrl.substr(0, spsdiscoUrl.length - 22);
return window.location.protocol + "//" + domain + webPrefix + "Lists/" + listName + "/" + itemId + "_.000";
}
The problem was caused by an incorrect list name. The correct name is "ExpenseReports" without the space. The 401 error led me to believe that there was a problem accessing the workflow.asmx web service itself. After several hours of checking and rechecking, I finally spotted the error.

how ajax site wide browsing works on phpfox?

i'm trying to use ajax wide browsing on phpfox but i dont understand how it works,
any idea please ?
i found in static/jscript/main.js this code :
$Core.ajax = function(sCall, $oParams)
{
var sParams = '&' + getParam('sGlobalTokenName') + '[ajax]=true&' + getParam('sGlobalTokenName') + '[call]=' + sCall;
if (!sParams.match(/\[security_token\]/i))
{
sParams += '&' + getParam('sGlobalTokenName') + '[security_token]=' + oCore['log.security_token'];
}
if (isset($oParams['params']))
{
if (typeof($oParams['params']) == 'string')
{
sParams += $oParams['params'];
}
else
{
$.each($oParams['params'], function($sKey, $sValue)
{
sParams += '&' + $sKey + '=' + encodeURIComponent($sValue) + '';
});
}
}
$.ajax(
{
type: (isset($oParams['type']) ? $oParams['type'] : 'GET'),
url: getParam('sJsStatic') + "ajax.php",
dataType: 'html',
data: sParams,
success: $oParams['success']
});
};
I'm trying to fix a module of chat while browsing on my site
Any idea plz ?
To make a link for site wide ajax browsing you do it just like usual, phpfox will figure it out for you.
If you want to make an ajax call in phpfox you do:
$.ajaxCall('module.function', 'param1=value1&param2=value2');
for example:
$.ajaxCall('ad.recalculate', 'total=' + iTotal + '&location=' + sLocation + '&block_id=' + sBlockId + '&isCPM=' + $Core.Ad.isCPM);
Calls the function recalculate in the file /module/ad/include/component/ajax/ajax.class.php and passes the params: total, location, block_id and isCPM

JQGrid Reload Error

I am new to JqGrid. I have a problem with reload JqGrid. Not getting any errors also.
jQuery("#gridData").jqGrid("setGridParam",
{ type: "POST",
url: "TablesCoolView.aspx/GetTableData",
data: "{TableName :'" + "Test" + "'}",
contentType: "application/json",
dataType: "json"
}).trigger("reloadGrid", [{ current: true }]);
The Code will go here,
onPaging: function (pgButton) {
//debugger;
var pagerId = this.p.pager.substr(1); // get paper id like "pager"
var currentPage = jQuery("#gridData").jqGrid("getGridParam", 'page'); //get current page
var lastPage = jQuery("#gridData").jqGrid("getGridParam", 'lastpage'); //get last page
if (currentPage - 1 == lastPage - 1)
jQuery("#gridData").jqGrid("setGridParam", { page: lastPage }).trigger("reloadGrid"); // set the requested page to the last page value – then reload
var currentRecordCount = jQuery("#gridData").jqGrid("getGridParam", 'reccount'); //get the record count
var recordsPerPage = jQuery("#gridData").jqGrid("getGridParam", 'rowNum'); // get the records per page
var newValue = 0; // new value
if (pgButton === "user") {
newValue = $(".ui-pg-input").val();
}
else {
if (pgButton.indexOf("next") >= 0)
newValue = ++currentPage;
else if (pgButton.indexOf("prev") >= 0)
newValue = --currentPage;
else if (pgButton.indexOf("last") >= 0)
newValue = jQuery("#gridId").jqGrid("getGridParam", 'lastpage');
else if (pgButton.indexOf("first") >= 0)
newValue = 1;
}
alert(pgButton);
//alert(newValue);
jQuery("#gridData").jqGrid("setGridParam", { page: newValue }).trigger("reloadGrid"); // set the requested page to the last page value – then reload
currentRecordCount = jQuery("#gridData").jqGrid("getGridParam", 'reccount'); // read the current page records
//alert('RecordCount: ' + currentRecordCount + ' RecordsPerPage: ' + recordsPerPage);
if (currentRecordCount < recordsPerPage) {
startRange = 1;
endRange += endRange;
alert("Grid Reload test Start");
//jQuery("#gridData").jqGrid("setGridParam", { type: "POST", url: "TablesCoolView.aspx/GetTableData", page: 1, async: true, loadOnce: true, data: "{TableName :'" + "Test" + "'}", contentType: "application/json", dataType: "json" }).trigger("reloadGrid");
jQuery("#gridData").jqGrid("setGridParam", { type: "POST", url: "TablesCoolView.aspx/GetTableData", data: "{TableName :'" + "Test" + "'}", contentType: "application/json", dataType: "json" }).trigger("reloadGrid", [{ current: true }]);
alert("Grid Reload test End");
//jQuery("#gridData").jqGrid("setGridParam", { datatype: "json", data: "{TableName :'" + tableName + "', \"PageSize\" :\"" + recordsPerPage + "\", \"PageNumber\" :\"" + newValue + "\"}", url: "TablesCoolView.aspx/GetNextSetOfRecords" }).trigger("reloadGrid");
//data: "{TableName :'" + tableName + "', \"PageSize\" :\"" + recordsPerPage + "\", \"PageNumber\" :\"" + newValue + "\"}",
}
}
Dont know where am doing wrong.
Please help me out of this.
Try changing data: "{TableName :'" + "Test" + "'}", to postData: "{TableName :'" + "Test" + "'}",

ajax type:"GET" works for firefox and chrome but not for IE

Hey guys this works for Firefox and Chrome in that it passes the data fine and shows the confirmationpage
but when i run it on IE it just refreshes the page and the data is all NULL while passing
var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&areacode=' + areacode + '&phonenumber=' + phonenumber + '&emailaddress=' + emailaddress + '&confirmemail=' + confirmemail + '&password=' + password + '&streetaddress=' + streetaddress + '&streetaddress2=' + streetaddress2 + '&city=' + city + '&state=' + state + '&zipcode=' + zipcode + '&month=' + month + '&day=' + day + '&year=' + year + '&services=' + services + '&agreement=' + agreement;
//alert(dataString);
// alert(services);
//var d = new Date();
$.ajax({
// cache: false,
type: "GET",
url: "http://www.vectorcreditsolution.com/js/process.php",
data: dataString,
// dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
window.location.href ="thankyou.html";
}
});
return false;
});
1) Have you verified what is arriving at your server (maybe populate a session variable) to ensure your $.ajax() is sending what you think it is?
2) Have you tried
var dataString = $("#formId").serializeArray();
(assuming <form id="formId"...)? And then use that for your data:dataString, element
3) I would expect you would want code something on the server when it is done processing to respond back to your calling page, and then in the success:function(retData) evaluate retData to interpret the server's response. If you simply don't care what happens and just want the browser page to march blindly forward to your thankyou.html upon completion of the ajax call, you don't need to include an argument variable in the function:
success: function() {...},

Resources