I have a field on my database that stores a number of clicks, and want to increment that when I click in a link(<a href="#selecoes" data-identity="31" id="clicks" clicks="0">) of my tag cloud. Note that I get the number of clicks throught my webservice. This is I do so far:
index.html
<div id="tags">
<ul id="tagList">
<li>
<img src='.../>Brasil
</li>
</ul>
main.js
$('#tagList a').live('click', function() {
findByIdSelecoes($(this).data('identity'));
});
function findByIdSelecoes(id) {
console.log('findByIdSelecoes: ' + id);
$.ajax({
type: 'GET',
url: rootURLSelecoes + '/id/' + id,
dataType: "json",
success: function(data){
$('#btnDelete').show();
console.log('findByIdSelecoes success: ' + data.nome);
currentWine = data;
renderDetails(currentWine);
findJogadoresBySelecao(id);
addClick(currentWine);
}
});
}
function addClick(selecao) {
console.log('addClick na seleção: ' + selecao.id_selecao);
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: rootURLSelecoes + '/update/' + selecao.id_selecao,
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR){
alert('clicks updated successfully');
},
error: function(jqXHR, textStatus, errorThrown){
alert('updateWine error: ' + textStatus);
}
});
}
function formToJSON() {
return JSON.stringify({
"clicks": ($('#clicks').val())++ // i dont know what i have to do so i try this(don't work)
});
}
I can't update the dataBase when I click the link in the list. The function formToJSON doesn't increment the value in the database.
Try to do this
Make a var number like global, and do this:
function addClick(selecao) {
console.log('addClick na seleção: ' + selecao.id_selecao);
number = parseInt(selecao.clicks,10);
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: rootURLSelecoes + '/update/' + selecao.id_selecao,
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR){
alert("Done: " +number);
},
error: function(jqXHR, textStatus, errorThrown){
alert('updateWine error: ' + textStatus);
}
});
}
function`enter code here` formToJSON() {
var ola = parseInt(number,10);
ola = ola +1;
return JSON.stringify({
"clicks": parseInt(ola,10)
});
}
Related
I have a function to add a record to database that uses Ajax with C# web service. Prior to updating DB I call another function to validate input that also uses Ajax. So, I need the validate function to finish before continuing with the one adding the record.
I know due to asynchronous nature of ajax I have to use promise/deferred but just can't get my head wrapped around it to set it up properly.
Updated
function validate() {
var deferred = $.Deferred();
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
}).done(function (result) {debugger
if (!result || result.d === "") {
isValid = false;
}
else {
var duplicate = JSON.parse(result.d);
switch (duplicate) {
case DuplicateData.Name:
isValid = false;
break;
case DuplicateData.ID:
isValid = false;
break;
}
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
deferred.resolve(isValid);
return deferred.promise();
//return isValid;
}
$(document).on("click", "#btnAdd", function (event) {debugger
$.when(validate())
.then(function(isValid) {
if (isValid) {
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
}).done(function (result) {
addNewRecord();
)}.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
}
})
});
function addNewRecord(){
// add record to DB
}
As you are only dealing with a boolean result, there is no reason to return a value, you can just resolve or reject the deferred.
function validate() {
var $defer = $.Deferred(function() {
$.ajax({
url: "path/to/web/service",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
})
.done(function (result) {
// If there's no result
if (!result || !result.d) {
$defer.reject();
}
else {
// This call shouldn't be necessary, as dataType: "json" will call it for you
// Unless you double-encoded it.
var duplicate = JSON.parse(result.d);
// Not sure about this part, what's DuplicatedData and what does result.d contain?
switch (duplicate) {
case DuplicateData.Name:
case DuplicateData.ID:
$defer.reject();
}
}
// Everything checks out, resolve the promise
$defer.resolve();
})
.fail(function (jqXHR, textStatus, errorThrown) {
// If there was a network or server error
// alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
$defer.reject();
});
});
return $defer;
}
$('form').on("click", "#btnAdd", function (event) {
validate()
.done(function() {
// If the validation passes
$.ajax({
url: "path/to/another/webservice",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: some_param,
})
.done(function (result) {
// Creation successful
addNewRecord();
}).fail(function (jqXHR, textStatus, errorThrown) {
// Creation failed
alert(textStatus + ' - ' + errorThrown + '\n' + jqXHR.responseText);
});
})
.fail(function(reason) {
// Called in case of a validation error
console.log("Validation error");
});
});
Here is a getData method and I am unable to get row using multiple conditions.
because I am trying to set input value where rows condition is matched. but it's not working yet
function getData() {
$.ajax({
type: 'POST',
url: APIUrl + 'api/GetCustomerProductDetailsDetailByEmployeeID?JSONStringData=' + JSON.stringify(objReqCustomerProductDetails),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
success: function (data, textStatus, xhr) {
objResCustomerProductDetails = data;
if ($(objResCustomerProductDetails.CustomerProductDetails).length > 0) {
$.each(objResCustomerProductDetails.CustomerProductDetails, function () {
$('#tbCustomer tbody tr[data-id=' + this.CustomerID + ' data-product-id=' + this.ProductID + '] td').find('input').val(parseFloat(this.Quantity.toString().trim()).toFixed(2));
});
}
},
error: function (xhr, textStatus, errorThrown) {
messageProvider(0, errorThrown);
}
});
}
$('#tbCustomer tbody tr[data-id=' + this.CustomerID + '][data-product-id=' + this.ProductID + '] td').find('input').val(parseFloat(this.Quantity.toString().trim()).toFixed(2));
After an attribute ends you need to close it. Convention is [attr1][attr2]. This was the problem with the above code.
Ref: https://api.jquery.com/multiple-attribute-selector/
Now, i want to use service from http://www.webservicex.net/globalweather.asmx to get weather by javascript. I try this code:
var wsUrl = "http://www.webservicex.net/globalweather.asmx?op=GetWeather";
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) {
if (status == "success")
$("#response").text($(req.responseXML).find("GetWeatherResult").text());
}
function processError(data, status, req) {
alert(req.responseText + " " + status);
// alert("Error");
}
i've got a problem
i want to use a website to do a checkin and checkout on my svn server.
i already got everthing to the point where i can do a checkout using jQuery.
my remaining problem is with the handling of the MERGE process.
within the MERGE svn transmits a chunked response.
but my console just reports Bad Request.
wireshark told m that the Transfer-Encoding is chunked.
but i couldn't set it to chunked. if i set the contentType to chunked the body is chunked not the transfere-encoding.
and jquery.ajax() doesn't provide something as Transfer-Encoding.
trying to put it into the headers didn't work as well...it didn't even show this header
my checkin code:
$.ajax({
type: "OPTIONS",
url: baseURL,
contentType: "text/xml",
data: '<?xml version="1.0" encoding="utf-8" ?><D:options xmlns:D="DAV:"><D:activity-collection-set></D:activity-collection-set></D:options>',
success: function(data1, status, jqxhr){
$.ajax({
type: "POST",
url: baseURL + "/!svn/me",
contentType: "application/vnd.svn-skel",
data: "(create-txn-with-props (svn:txn-user-agent 40 SVN/1.8.9(i686-pc-linux-gnu) serf/1.3.4 svn:log function svn:txn-client-compat-version 5 1.8.9))",
success: function(data2, status, jqxhr){
rev = jqxhr.getResponseHeader('SVN-Txn-Name');
newdata = new XMLSerializer().serializeToString(xmlString["context"]);
hashResult = calcMD5(newdata);
$.ajax({
type: "PUT",
url: baseURL + "/!svn/txr/" + rev + file + ".xml",
headers: {"X-SVN-Version-Name": latestRev, "X-SVN-Base-Fulltext-MD5":hashBase, "X-SVN-Result-Fulltext-MD5": hashResult},
contentType: "text/xml",
data: newdata,
success: function(data3, status, jqxhr){
chunked1 = '<?xml version="1.0" encoding="utf-8"?><D:merge xmlns:D="DAV:"><D:source><D:href>/svn/check/!svn/txn/' + rev + '</D:href></D:source><D:no-auto-merge></D:no-auto-merge><D:no-checkout></D:no-checkout><D:prop><D:checked-in></D:checked-in><D:version-name></D:version-name><D:resourcetype></D:resourcetype><D:creationdate></D:creationdate><D:creator-displayname>';
chunked2 = '</D:creator-displayname></D:prop></D:merge>';
length1 = chunked1.length;
length2 = chunked2.length;
$.ajax({
type: "MERGE",
url: baseURL,
headers: {"X-SVN-Options": "release-locks"},
contentType: "text/xml",
data: length1 + chunked1 + length2 + chunked2,
success: function(data4, status, jqxhr){
alert('file submitted');
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' at MERGE \n' + textStatus);
}
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' at PUT\n' + textStatus);
$.ajax({
type: "DELETE",
url: baseURL + "/!svn/txn/" + rev,
success: function(data3, status, jqxhr){
alert('file deleted');
}
});
}
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' at POST\n' + textStatus);
}
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + ' at OPTIONS\n' + textStatus);
}
});
EDIT: corrected some mistakes in my code
changed the problemfocus from PUT to MERGE, because i found the problem
the problem was that i transmitted within the "X-SVN-Version-Name" not just the number but 'number', therefore the error "File is out of Date"
set the contentType: "text/xml" and data: chunked1 + chunked2
than everything works fine and svn accepts the file
I have a page, and i've got a link looking like:
<span>Nordjylland</span>
And in my Javascript file, i've got a function called GetCitiesByRegion(), however, when clicking the link, i get an error, saying that GetCitiesByRegion is not defined?
The function looks like this:
function GetCitiesByRegion(id) {
var params = '{"id":"' + id + '"}'
var request = {
type: "GET",
async: false,
cache: false,
url: "http://" + location.hostname + "/webservices/services.svc/GetCitiesByRegion",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: params,
success: function (result) {
alert("Data Loaded: " + result);
},
error: function (xhr, status, error) {
alert('Fejl ved webservice: error: ' + error);
}
};
$jq.ajax(request);
}