I have this code:
$.ajax({
type: 'get',
url: 'https://......./confirma.asp',
data: $('.newform').serialize(),
dataType: 'jsonp',
beforeSend: function () {
$('.ajax-loader').slideToggle();
},
success: function (resposta) {
alert(resposta); // not work
$('.ajax-loader').slideToggle();
}
});
I get this response from ajax GET (firebug):
CODRET=1&MSGRET=JA CONFIRMADA
How I get this values? For example:
resposta['CODRET'];
or
resposta.CODRET
Because I need set in another JQuery function( );
Well that looks like a query string. Here is a modified version of this answer:
function parseQueryString(qs) {
var urlParams = {};
var e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = qs.substring(1);
while (e = r.exec(q))
urlParams[d(e[1])] = d(e[2]);
return urlParams;
}
console.log(parseQueryString("CODRET=1&MSGRET=JA CONFIRMADA"));
http://jsfiddle.net/GphYj/
probably you should split them:
$.ajax({
type: 'get',
url: 'https://ecommerce.redecard.com.br/pos_virtual/confirma.asp',
data: $('.newform').serialize(),
beforeSend: function () {
$('.ajax-loader').slideToggle();
},
success: function (data) {
var codret = data.split('&')[0].split('=')[1];
var msgret = data.split('&')[1].split('=')[1];
$('.ajax-loader').slideToggle();
}
});
If you can't change the server code do this
function QueryStringToJsonObject(queryString)
{
var queries = {};
decodeURIComponent(queryString).replace(/([^=]+)=([^&]+)/g,
function(all, key, value) {
queries[key.replace(/^&/,'')] = value;
}
);
return queries;
}
and then:
QueryStringToJsonObject(responseText) ["CODRET"] //1
Otherwise consider returning JSON to http request.
Related
In the following code i am not able to filter entry.AllLinks.
The code is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
}
It does not filter and when i hover cursor over AllLinks in entry.AllLinks it is undefined.
Value of entry is coming as:
[{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
You can use Array.filter to filter the array as per the values you require.
let arr = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}] ;
arr = arr.filter(function(elem) {
return elem.AllLinks !== 'Link9';
});
console.log(arr);
On my code I hava a function with 3 nested AJAX calls, in order for it to work I had to set Async=false.
As I have read that Async=false is deprecated I replaced the Async=false with promises.
This is my function before I edited it:
self.getOrders = function (name) {
var orders= [];
var order= function (item, type1, type2) {
var self = this;
self.order= item;
self.type1= type1;
self.type2= type2;
}
$.ajax({
url: "/API/orders/" + name,
type: "GET",
async: false,
success: function (orderResults) {
var mappedOrders = $.map(orderResults, function (orderItem) {
$.ajax({
url: "/API/orders/property/" + orderItem.id + "/type1",
type: "GET",
async: false,
success: function (property1Results) {
$.ajax({
url: "/API/orders/property/" + orderItem.id + "/type2",
type: "GET",
async: false,
success: function (property2Results) {
orders.push(new order(orderItem, property1Results, property2Results));
}
});
}
});
})
}
});
return orders;
This function worked perfectly, I got the data end everything worked fine.
Then I changed the function to use promises instead of Async=false,
this is the edited function, with promises:
//The begin of the function- same as first one
var orders= [];
var firstPromise = $.ajax({
url: "/API/orders/" + name,
type: "GET"
});
$.when(firstPromise).done(function (orderResults) {
var mappedOrders = $.map(orderResults, function (orderItem) {
var secondPromise = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type1",
type: "GET"
});
$.when(secondPromise).done(function (property1Results) {
var thirdPromise = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type2",
type: "GET"
});
$.when(thirdPromise).done(function (property2Results) {
orders.push(new order(orderItem, property1Results, property2Results));
});
});
});
});
return orders;
And the function call:
self.populateOrders = function (name) {
var mappedOrders = $.map(self.service.getOrders(name), function (item) {
return new Order(item)
});
self.orders(mappedOrders);
}
The new function is not working, I'm getting back from the firstPromise a wrong json with backslashes, and the returned orders object is empty.
Any idea what am I doing wrong? I spent so much time on it but couldn't figure it out.
Thanks in advance.
Nested ajax calls inside a loop is a hell to manage. You can do it like this.
Create a promise to notify the caller when the whole process is finished
Wait for all the inner ajax calls to resolve
Resolve you main promise to notify the caller
self.getOrders = function (name) {
var mainDeferred = $.Deferred();
var orders = [];
var order = function (item, type1, type2) {
var self = this;
self.order = item;
self.type1 = type1;
self.type2 = type2;
}
$.ajax({
url: "/API/orders/" + name,
type: "GET",
success: function (orderResults) {
var innerwait = [];
var mappedOrders = $.map(orderResults, function (orderItem) {
var ajax1 = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type1",
type: "GET"
});
var ajax2 = $.ajax({
url: "/API/orders/property/" + orderItem.id + "/type2",
type: "GET"
});
$.when(ajax1, ajax2).done(function (property1Results, property2Results) {
orders.push(new order(orderItem, property1Results[0], property2Results[0])))
});
innerwait.push(ajax1, ajax2);
});;
$.when.apply(null, innerwait) //make sure to wait for all ajax requests to finish
.done(function () {
mainDeferred.resolve(orders); //now that we are sure the orders array is filled, we can resolve mainDeferred with orders array
});
}
});
return mainDeferred.promise();
}
self.populateOrders = function (name) {
self.service.getOrders(name).done(function (orders) { //use .done() method to wait for the .getOrders() to resolve
var mappedOrders = $.map(orders, function (item) {
return new Order(item)
});
self.orders(mappedOrders);
});
}
In the example, note that I use $.when.apply() to wait for an array of deferreds.
A bug recently introduced in chrome 52 (august 2016) can cause this kind of behavior : answers for nested requested are ignored.
Hoppefully, it will not last long.
https://bugs.chromium.org/p/chromium/issues/detail?id=633696
Try to add cache: false
I am trying to create an auto-suggestion from scratch. I am using canjs controller to control the DOM elements (ul and li).
I want smart and short code to implement this. I have tried with filter but I want Ajax filter method to use for this purpose.
I have tried the following thing:
can.Model:
var SearchDomainModel = can.Model.extend({
findAll: function(){
return this.getDomains;
}
}, { domainList: null,
getDomains: function(params, callback) {
var promise = $.ajax({
url: '/scripts/models/domains.json',
type: 'GET',
dataType: 'json',
dataFilter: function(data, type){
var parsed_data = JSON.parse(data);
var regex = new RegExp(params, 'gi')
var temp = [];
$.each(parsed_data, function(i, item){
for(var j in item)
if ((item[j].url).toLowerCase().indexOf(params) >= 0){
temp.push(item[j].url);
console.log(temp);
}
});
return temp;
}
});
This is my can.controller:
var DomainController = can.Control.extend({
defaults: {
view: 'views/domainSearch.hbs'
}
}, {
searchList: new can.List(),
domainModel: new DomainModel(),
init: function(element, options) {
this.element.html(can.view(this.options.view, this.searchList));
$('html,body').css({
percentWidth: 100,
percentHeight: 100
});
$('.error').hide();
}, // control domain filter on keyup event
'input keyup': function(element, event) {
var self = this;
var searchText = element.val();
if (searchText !== "") {
this.domainModel.getDomains(searchText, function (response, error) {
self.searchList.attr("domains",response);
console.log(error);
})
I am trying and searching from last two days. I could not have done it. Can anybody suggest me where is my mistake in the code and how to solve it?
Thanx in advance!!
I would probably do something like this:
var SearchDomainModel = can.Model.extend({
findAll: function(){
return this.getDomains;
}
}, { domainList: null,
getDomains: (function() {
var domains = null;
function search(searchText, callback){
var regex = new RegExp(searchText, 'gi')
var temp = [];
$.each(domains, function(i, item){
for(var j in item)
if (regex.test(item[j].url))
temp.push(item[j].url);
});
callback(temp);
}
return function(searchText, callback) {
if( domains ) {
search(searchText, callback);
return;
}
$.ajax({
url: '/scripts/models/domains.json',
type: 'GET',
dataType: 'json',
success: function(data) {
domains = data;
search(searchText, callback);
}
});
};
})()
});
I didn't test the code but it doesn't spawn one ajax request everytime you release a key but instead grabs the data once and then refers to the same data.
I can`t return result of this function.
function get_duration() {
var a = '';
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos?q=3KMz3JqRByY&max-results=50& format=5,1,6",
dataType: "jsonp",
success: function (data) {
re2 = /seconds='(\d+)'/ig;
while (re.exec(data) != null) {
a = re2.exec(data);
}
}
});
return a;
}
You have to use return inside the success callback since, A in Ajax is asynchronous.
Like this:
function get_duration() {
var a = '';
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos?q=3KMz3JqRByY&max-results=50& format=5,1,6",
dataType: "jsonp",
success: function (data) {
re2 = /seconds='(\d+)'/ig;
while (re.exec(data) != null) {
a = re2.exec(data);
}
return a;
}
});
}
But, this function isn't guaranteed to return. You'll have to use a callback function kind of thing.
Hey all I am working on a json call that will implement Drupal's services module with json. I am using jquery's ajax function to call the function but I am getting an error stating that no parameters are being passed. When I look at the query string being posted I notice that sessid is not being passed even though its with the parameters. Below is what Im running.
// JavaScript Document
$(document).ready(function() {
function drupalConnect(src) {
$.ajax({
url: src,
type: 'POST',
data: {
method: 'system.connect'
},
success: function(data) {
return data["result"]["sessid"];
}
});
}
function getTimestamp() {
return Math.round((new Date).getTime() / 1000);
}
function randString(length) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var randomstring = '';
for (var i = 0; i < length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
return randomstring;
}
var session_id = drupalConnect('http://localhost/drupal/services/json-rpc');
var nonce = randString(10);
var timestamp = getTimestamp();
var username = "markusgray";
var password = "Markus1990";
var key = '2ae0392e0aebbfeeddefcc962ea1924f';
var domain = 'localhost';
var hashObj = new jsSHA(timestamp + ";" + domain + ";" + nonce + ";user.login", "TEXT");
var hash = hashObj.getHMAC(key, "TEXT", "SHA-256", "HEX");
var parameters = {
hash: hash,
domain_name: domain,
domain_time_stamp: timestamp,
nonce: nonce,
sessid: session_id,
username: username,
password: password
};
var par = JSON.stringify(parameters);
$.ajax({
url: 'http://localhost/drupal/services/json-rpc',
type: 'POST',
dataType: 'json',
data: {
method: 'user.login',
params: par
},
success: function() {
}
});
});
drupalConnect doesn't return anything, also the return from the success callback is just thrown away. The best way to use the data returned from an ajax call is to use it in thee callback itself.
function drupalConnect(src){
$.ajax({
url: src,
type: 'POST',
data:{method:'system.connect'},
success: function(data){
var session_id = data["result"]["sessid"];
//use session_id here
}
});
}
It is because of the Asynchronous ajax, let me elaborate, to get the session_id you are making an ajax call. At the moment it will send the request, but it wont ensure that the session_id will be assigned at that moment. Hence when you making the second ajax call, the session_id may not be assigned for a value.
There are two workarounds for this,
One is, making the first ajax call with an option async:false and assign the value within the success call, something like
var session_id;
function drupalConnect(src) {
$.ajax({
url: src,
type: 'post',
async : false,
data: {
method: 'system.connect'
},
success: function(data) {
session_id = data["result"]["sessid"];
}
});
};
DEMO
The second one and preferred way is, use of deferred objects, something like
$.when(
// make your first ajax request
).then(function(data) {
session_id = data["result"]["sessid"];
// make your second ajax call
});
DEMO