Menu
  • HOME
  • TAGS

Agnostic scheme / protocol ajax call

Tag: ajax,http,https,xmlhttprequest,xdomainrequest

I would like to do an ajax call that adapts to current scheme (http/https). What would be a really valid approach to this situation (both to xhr and xdr)?

var xhr = new XMLHttpRequest(); // Or var xdr = new XDomainRequest
...
xhr.open("get", "//mydomain.com/api/v1/etc", true);
...

Or

var xhr = new XMLHttpRequest();
...
xhr.open("get", window.location.protocol + "//mydomain.com/api/v1/etc", true);
...

Or.. anything else?

Note: The question Making a protocol agnostic jquery ajax call does not mention the both cases XMLHttpRequest and XDomainRequest nor it provides a validated solution.

Best How To :

This approach definitely will not work:

xhr.open("get", "//mydomain.com/api/v1/etc", true);

as this will send the request on the relative url, as there is no protocol mention here.

This approach works on XMLHttpRequest:

xhr.open("get", window.location.protocol + "//mydomain.com/api/v1/etc", true);

Important note that the XDomainRequest is obsolete and should not be used in your application as it will work only in IE 8-9.

Great example of handling the various type of requests can be found here:

if(window.XDomainRequest){
    if(protocol == "http:"){
        if(RequestHelper.Busy){
            setTimeout(function(){
                RequestHelper.sendRequest(url,success,$);
            },50);
        } else {
            RequestHelper.Busy = true;
            $("body").append("<iframe id="ajaxProxy" style="display: none;" src="&quot;+RequestHelper.GatewayURL+&quot;" width="320" height="240"></iframe>"); 
            $("#ajaxProxy").load(function(){ 
                ajaxProxy.postMessage(url,"*"); 
                //...
            }); 
        } 
    } else { 
        var xdr = new XDomainRequest(); 
        xdr.open("get", url); 
        //...
    } 
} else { 
    $.ajax({ 
        type: "GET", 
        url: url, 
        dataType: "html", 
        async:true, success: 
        function (response){ 
            success(response); } 
        }); 
}

Is there a way to fire an event every time an ajax call in made in AngularJS?

javascript,ajax,angularjs,express

In Angular this can be solved with an interceptor. See Angular-loading-bar as example.

Disable 2 buttons after click of a button

javascript,php,jquery,html,ajax

You can achieve this by disabling the buttons before you make the AJAX request, and then enabling them again in the complete handler of the request. Try this: var onSubmit = function(e) { var txtbox = $('#txt').val(); var hiddenTxt = $('#hidden').val(); $('.botleftbtn, .botrightbtn').prop('disabled', true); // < disable the buttons $.ajax({...

Automatically calling server side class without

javascript,html,ajax

Trigger the click event like this: $('._repLikeMore').trigger('click'); ...

Getting a collection via Ajax to show in view

jquery,ruby-on-rails,ajax

Your partial (currently named: _followup.html.erb in your example) should just be the code to produce a single row, Rails will iterate over it for you, and you should name it after the model it represents, ie. # app/views/assessments/_assessment.html.erb <%= assessment.name %> Then in your app/views/assessments/followups.html.erb view you'd use that partial...

Updating View in Angular js on ajax success callback

ajax,angularjs

Your code correctly performs a GET request to inactivate the offer, however you do not "tell" Angular that the offer has been inactivated. What you need to do is remove the offer from the offers list $scope.offers once the offer is successfully inactivated (ie. when the inActivateOffer promise is resolved)....

Using $.ajaxStop() to determine when page is finished loading in CasperJS

javascript,jquery,ajax,phantomjs,casperjs

I would do something like this in include.js: (function(){ window._allAjaxRequestsHaveStopped = false; var interval; $(document).ajaxStop(function() { if (interval) { clearInterval(interval); interval = null; } interval = setTimeout(function(){ window._allAjaxRequestsHaveStopped = true; }, 500); }); $(document).ajaxStart(function() { if (interval) { clearInterval(interval); interval = null; } }); })(); This sets a (hopefully unique)...

How to use ajax response JSON data?

javascript,jquery,ajax,json

As data is array of objects, use data[0].title: $('#myModalLabel').text('Review:' + data[0].title); // ^^^ ...

How to simulate $.ajax array POST request with Java

java,javascript,php,ajax

If you want PHP to automatically recognize the data as array, you have to sent multiple parameters with the same name, each ending in []. For example: foo[]=1&foo[]=2 will be accessible in PHP as $_GET['foo'], returning the array array(1,2). More information can be found in Variables From External Sources and...

How to load two PHP scripts simultaneously using jQuery?

php,jquery,ajax

It sounds like your computer is not handling multiple connections. I have found a similar question on superuser.stackexchange - XAMPP apache not handling multiple requests His solution is: Starting and stopping the session every time I want to write to the session works though. Without him supplying any code, I...

How to transform $.post to $.ajax?

javascript,jquery,ajax,json,servlets

$.post("../admin-login", { dataName:JSON.stringify({ username:uname, password:pass, }) }, function(data,status){ console.log("Data:"+data); answer = data; } ); becomes function getResult(data) { // do something with data // you can result = data here return data; } $.ajax({ url: "../admin-login", type: 'post', contentType: "application/x-www-form-urlencoded", data: { dataName:JSON.stringify({ username:uname, password:pass, }) }, success: function (data,...

Server initiated requests

http,go,http2

Before websockets we had polling. This literally means having the client periodically (every few seconds, or whatever time period makes sense for your application), make a request to the server to find out the status of the job. An optimization many people use is "long" polling. This involves having the...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

When is the cookie set by AJAX available in javascript?

javascript,ajax,cookies

Cookies are passed as HTTP headers, both in the request and in the response. When you do an ajax call and set a cookie, that cookie will only be available in the browser after a reload / redirect happens, and new headers are gotten from the server containing the newly...

How to calculate values of a drop down menu with PHP/ JS?

javascript,php,ajax

I am not sure by your question if you want to add it to the db on the selection... that would require a simple but different code. This will accomplish what you are asking. You do not need a form... just the selection boxes. If you notice I encased each...

.NET wep api won't accept %2E or . in api request uri

c#,jquery,asp.net,ajax,json

Have a look at this answer MVC4 project - cannot have dot in parameter value? Try changing the Web.Config file <system.web> <httpRuntime relaxedUrlToFileSystemMapping="true" /> </system.web> ...

How to trigger ajax loading with an observable varariable in knockout?

ajax,knockout.js

You can use the subscribe method of an observable: vm.currentTab.subscribe(function(newValue) { //currentTab has just changed value, to newValue //You can fire your Ajax call here. }); ...

file input type not being included in jquery FormData for AJAX send

javascript,php,jquery,ajax

Your needs use enctype='multipart/form-data'. <form id="business-form" enctype='multipart/form-data'> </form> ...

jquery - add header request to specific ajax request

javascript,jquery,ajax

This is what you are looking for I believe. $( document ).ajaxSend(function( event, jqxhr, settings ) { if ( settings.url == "someURL" ) { jqxhr.setRequestHeader(key,value); } }); ...

Unable to upload file to Sharepoint @ Office 365 via REST

javascript,ajax,rest,sharepoint,office365

To me it just seems a bit light, visit this link https://msdn.microsoft.com/en-us/library/office/dn769086.aspx on technet, and compare your upload function to this: // Add the file to the file collection in the Shared Documents folder. function addFileToFolder(arrayBuffer) { // Get the file name from the file input control on the page....

How to dynamically add a row without “Requested unknown parameter” error

javascript,jquery,ajax,datatables

Use the code below instead: table.row.add({ "college_abbrev": ca, "college_name": cn, "college_id": college_id }).draw(); You're getting "Requested unknown parameter" error because you're passing array of objects to row.add(), where you should pass simple object instead, see row.add() for more information. Also you don't need to construct a button in a call...

How use jquery getJSON with a local variable

javascript,jquery,ajax,json,ace-editor

JSON is JavaScript Object Notation, so this: [] or {} is JSON. I guess you only need: getCompletions: function(editor, session, pos, prefix, callback) { if (prefix.length === 0) { callback(null, []); return; } callback(null, wordList.map(function(ea) { return {name: ea.word, value: ea.word, meta: "optional text"} })); } $.getJSON will call the...

Parameters from f:param not submitted with AJAX request when form enctype is multipart/form-data

ajax,jsf,jsf-2,jsf-2.2,wildfly

This is a bug in Mojarra. I've just reported it as issue 3968. For now, one work around is to pass them as EL method arguments instead. <h:form enctype="multipart/form-data"> <h:commandButton value="Submit" action="#{bean.action(true)}"> <f:ajax execute="@this" render="@this"/> </h:commandButton> </h:form> public void action(boolean myparam) { // ... } ...

Very weird behavior when using “var” keyword in an ajax request

javascript,ajax,variables,var

Cool, you discovered hoisting. MDN explains it as good as anyone: Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be...

Check with jquery if result/echo from PHP starts with “abc”

php,jquery,ajax

Don't use string matching for this task. Use HTTP response codes - that's what they're there for! The http_response_code function in PHP is designed for this exact purpose: <?php if ( /* error condition */ ) { http_response_code(400); // "Bad request" response code echo 'Invalid parameters'; } else { echo...

Modal won't close on ajax success

jquery,ajax

You're using the wrong method to hide the element. Change this: $('#modal-container').modal('hide'); To this: $('#modal-container').hide(); Or if you want to completely remove it from the page, change it to this: $('#modal-container').remove(); ...

ajax test not working

javascript,php,jquery,ajax

I want the php file to pass the $add1 to the Javascript and then i want the javascript to return the var sum back to the php and the php to echo the $sum from the $POST. $sum from $_POST is actually echoed, but not shown in HTML page,...

cross domain ajax form post — How is this allowed?

jquery,ajax

If the server has a response header of 'Access-Control-Allow-Origin': '*' or something similar, it will return a response. In short, this has nothing to do with jQuery, and has everything to do with the server. In the case above, * is a wildcard representing all origins. But it could also...

How to send current page number in Ajax request

javascript,jquery,ajax,spring-mvc,datatables

DataTables already sends parameters start and length in the request that you can use to calculate page number, see Server-side processing. If you still need to have the URL structure with the page number, you can use the code below: "ajax": { "data": function(){ var info = $('#propertyTable').DataTable().page.info(); $('#propertyTable').DataTable().ajax.url( "${contextPath}/admin/getNextPageData/"+(info.page...

How to write .htaccess file for AJAX page

php,jquery,ajax,.htaccess

I think it's more related to apache than ajax. Anyway - your RewriteRule is ^findcontents/([A-Za-z0-9-]+)/?$ and you post to the url '/findcontents'. Did you try to post to '/findcontents/asdf' ? Another option is to add ^findcontents$ to your rules. If none of these works for you please provide some more...

Why are fields reset after ajax update with Primefaces

ajax,jsf-2,primefaces

Why are fields reset after ajax update with Primefaces This problem has 2 possible causes depending on the concrete functional requirement: It's because you didn't tell JSF to process the desired input values. Or, it's because you told JSF to also update the non-desired input values. The solution depends...

Get all images from local folder

javascript,jquery,ajax

I think your best option is to use the new File API in Javascript. Is has a lot of functions to read files from the file system. <input type="file" id="fileinput" multiple /> <script type="text/javascript"> function readMultipleFiles(evt) { //Retrieve all the files from the FileList object var files = evt.target.files; if...

how to use geocoder class to retrieve latitude and longitude through ajax

javascript,ajax,google-maps

Because of it's scope, your codeAddress javascript function is not visible for outer caller myLoop, as it is enclosed within myFunction, therefore you get the codeAddress is not defined. Try to rewrite your code similar to this (I have not tested, so it might not work right away, but you...

No Ajax success after php-script is run

php,jquery,ajax

Your script db_backup.php should output something in JSON format, echo something like this. echo json_encode(array('success')); OR You can change your code to this: <button id="btn">Backup</button> <script> $("document").ready(function(){ $("#btn").click(function(){ $.ajax({ type: "POST", url: "backup/db_backup.php", success: function(data) { alert("success!!!"); } }); }); }); </script> ...

Identifier starts immediately after numeric literal

jquery,ajax,razor

I think you have to include it with the ' mark Like this : var userID = '@User.Identity.GetUserId()';...

json_encode and parsing information if there are no records returned

php,ajax,json

Here are two (of several) possibilities: PHP Option: Handle the NULL object to make it parseble ahead of time... if ($mydata==NULL) { $mydata = new stdClass(); } echo json_decode($mydata); JS Option: Try catching the error when parsing it on the client side. // Catch the error try { var data...

WooCommerce seems to only orderby date and not price

php,ajax,wordpress,woocommerce

Try this: $args = array( 'post_type' => 'product', 'posts_per_page' => 100, 'product_cat' => 'beast-balls', 'orderby' => 'meta_value_num', 'meta_key' => '_price', 'order' => 'asc' ); ...

Sending LIst via ajax to complex model

javascript,c#,asp.net,ajax

You don't need to JSON.stringify the recipients. "recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]") Remove JSON.stringify form here and it should work. var postData = { "workplaceGiverId": $(".wpgDropdownList").val(), "fromMemberId": $(".wpgFromMemberDropdownList").val(), "toMemberId": $(".wpgToMemberDropdownList").val(), "voucherExpiryDate": $("#expiryDatePicker").val(), "recipients": [{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}] }; ...

Making an alert() with PHP and ajax

javascript,php,jquery,ajax

You're trying to output javascript from the php, without outputting it in your ajax callback, won't work. The easiest way to do what you want, is to return the string with your php, and handle the outputting to your javascript. something like : if($QueueCount == 1){ Echo "You already have...

Check AJAX response data before taking action

javascript,php,jquery,ajax

I would return a json string, with a flag for what type of content it is: if ($numLegs == 1) { echo json_encode(['type' => 'form', 'content' => $formData]); } else { echo json_encode(['type' => 'modal', 'content' => $modalContent]); } And then in your js: $.getJSON("ajax.php", { date: date, num: num...

Custom HTTP Header or cookies? how custom authentication/authorization helps in CSRF?

javascript,http,cors,csrf

When authentication is based on cookie, every fired request from the client will be authenticated. Whether it is a "good" - intended by application, or "bad - as a result of CSRF attack. Browser will always blindly add cookie to every request. When authentication is based, for instance, on bearer...

Run AJAX function on form submit button after javascript confirm() cancel

javascript,jquery,ajax,wordpress,forms

Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit, Try below code, var isBusy = false; //first time, busy state is false $('#publish').on('click', function (e) { if(isBusy == true) return ; //if...

Jquery parsley validate not working

javascript,php,jquery,ajax,parsley.js

Make sure this line: $('#remarks').parsley( 'addConstraint', { minlength: 5 }); is called before you check isValid()....

Jquery html page dynamic control and load

jquery,html,ajax

The options added to the virtual select is not reflected. Either you can write the tr to DOM and then try binding the values OR return the updated data. http://jsfiddle.net/mn5b0hjg/2/ var bindDrpValues = function (control, valueList, setting) { for (var i = 0; i < valueList.length; i++) { var option...

In simple RESTful design, does PATCH imply mapping to CRUD's (ORM's) “update” and PUT to “destroy”+“create” (to replace a resource)?

database,rest,http,orm,crud

Well, Both the actions actually means update, where PUT is full update and PATCH is partial update. In case of PUT you already know the identifier of the resource and the resource already exists, so it is not a create and delete action per se. Infact, you can make do...

How to return value in Meteor.JS from HTTP.call “GET”

javascript,ajax,http,meteor,facebook-javascript-sdk

Don't pass a callback to get the HTTP to return. You're also able to pass off URL parameters quite easily: var result = HTTP.call("GET", "https://graph.facebook.com/me", { params: { access_token : Meteor.user().services.facebook.accessToken, fields : "likes.limit(5){events{picture,cover,place,name,attending_count}}" } }); console.log(result); ...

Multiple AJAX forms with the same ID on the same page

javascript,php,jquery,ajax,forms

Don't use the same ID for the top and bottom forms. An id must be unique in a document -- see MDN Docs. Instead have two separate id's and reference them both in the one jQuery call when you are binding to the submit event: $('#newsletter_top, #newsletter_bottom').on('submit', function(e) { //...

nodejs head request isn't triggering events

node.js,http

The problem is that you don't declare a data or readable event handler. According to the fine manual: A Readable stream will not start emitting data until you indicate that you are ready to receive it. Instead, the stream will be put in a "paused" state indefinitely (until you start...

Storing result from FOR loop as one array (array only saves each results seperately)

javascript,jquery,arrays,ajax

Here is my Solution var id = "1#2#3#4#5#"; var chkdId = id.slice(0, -1); console.log(chkdId); var arr = chkdId.split('#'); var checkedId = ''; var chkdLen = arr.length; // here is the array var arrayWithResults = []; for (var i = 0; i < chkdLen; i++) { checkedId = arr[i]; var checkedId...

Loading external php file in a div with jquery ajax

javascript,php,jquery,ajax,mysqli

You have to add jquery js in your html code. you can use online jquery. <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> ...