Asked By: Anonymous
I have a custom element using iron-ajax. I don’t know why the request occurs twice. This is my code:
<template>
<div style="text-align: center" hidden="{{!cargando}}">cargando ... <br />
<paper-spinner alt="cargando ..." active="[[cargando]]"></paper-spinner>
</div>
<ficha-folleto datos="[[ajaxResponse]]"></ficha-folleto>
<iron-ajax
auto
url="backend/api.php?operacion=folleto&idf=[[idf]]&len=[[len]]"
handle-as="json"
verbose=true
last-response={{ajaxResponse}}
loading="{{cargando}}"> </iron-ajax>
</template>
<script>
Polymer({
is: "folleto-digital",
properties: {
}
});
</script>
The call is from this page:
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="elements/folleto-digital/folleto-digital.html">
<!DOCTYPE html>
<html>
<head>
<a href="http://bower_components/webcomponentsjs/webcomponents-lite.min.js">http://bower_components/webcomponentsjs/webcomponents-lite.min.js</a>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<folleto-digital idf="" id="folleto"></folleto-digital>
<a href="http://js/funciones.js">http://js/funciones.js</a>
<script>
var idf = getParameterByName("idf");
var folleto = document.querySelector("#folleto");
folleto.idf = idf;
var len = getParameterByName("len");
folleto.len = len;
</script>
</body>
</html>
And I’m requesting this url: folleto.html?idf=1&len=es
All is working fine, but there are two request:
- api.php?operacion=folleto&idf=&len=
- api.php?operacion=folleto&idf=1&len=es
The Polymer documentation says about auto param:
“If true, automatically performs an Ajax request when either url or params changes”
So I think the param at the begining have value=”” and then take the values from the querystring and because of that request twice.
How can I fix this to do one and only one request?
Thanks!
Solution
Answered By: Anonymous
When <iron-ajax>.auto
is true, the element automatically generates the request if the url
is a non-empty string. Since the url
has a non-empty value even when idf
and len
are blank/empty, the <iron-ajax>
generates a request even before you’ve set idf
and len
.
If you want <iron-ajax>
to send the request only when idf
and len
are set, you’d need to remove auto
, and add a complex observer on idf
and len
that generates the request only when both values are not empty.
// template
<iron-ajax id="ajax" ...>
Polymer({
is: "folleto-digital",
properties: {
idf: String,
len: String
},
observers: ['_sendRequest(idf, len)'],
_sendRequest: function(idf, len) {
if (idf && len) {
this.$.ajax.generateRequest();
}
}
});