I have a javascript function that is executed onClick via jquery. Within this function I am calling a Web Service "getTestConnection" which returns a True or False and I have confirmed it is working but keeps returning variable undefined.
$("#btnNext2").click(function() {
var postData = {}; {
postData['user'] = user;
postData['password'] = password;
postData['serviceurl'] = serviceurl;
postData['datasource'] = datasource;
};
//Converts object to string and formats to JSON
var json = JSON.stringify(postData);
//connTest keeps getting returned as 'Undefined'
var connTest = getTestConnection(json);
});
< script type = "text/javascript" >
function getDocType(json, rowcount) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/GetDocTypes",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//*****************************************************************************
//This is being called immediately after getTestConnection is executed
//******************************************************************************
for (i = 0; i < data.d.length; i++) {
$('#SelectDocType' + rowcount + '')
.append($("<option></option>")
.attr("value", data.d[i].docTypeID)
.text(data.d[i].docTypeName));
}
var firstDocTypeID = data.d[0].docTypeID;
var jsonUnstringify = JSON.parse(json);
var postDataNew = {}; {
postDataNew['user'] = jsonUnstringify.user;
postDataNew['password'] = jsonUnstringify.password;
postDataNew['serviceurl'] = jsonUnstringify.serviceurl;
postDataNew['datasource'] = jsonUnstringify.datasource;
postDataNew['docTypeID'] = firstDocTypeID;
};
var jsonnew = JSON.stringify(postDataNew);
getKeywords(jsonnew, rowcount);
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
//Test Connection Web Service
function getTestConnection(json) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/TestConnection",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
}
< /script>
You have multiples errors:
You have a <script type = "text/javascript"> tag inside another <script> tag
You define a new function inside another function:
function getDocType(json, rowcount) {
$.ajax({
.....
});
function getTestConnection(json) {
....
}
}
which should be
function getDocType(json, rowcount) {
$.ajax({
.....
});
}
function getTestConnection(json) {
....
}
You forgot to get returned data from the AJAX call in your getTestConnection function :
$.ajax({
type: "POST",
url: "http://localhost...",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
....
}
});
Related
The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}
this is my code for a simple chatbox basically what does this does is on clicking send(input) button it will send the message into database and also create notification for the reciever but I want to create notification only when the user is not the this this page i.e on /message.php. Is there any way I can know on which the other user is? or any other approach to what I am trying to do?
$(".chatbox input").on("click", function () {
var rly = $("#reply").val();
var send = "<?php echo $Sender?>";
$.ajax({
type: 'POST',
url: 'Message_chat.php',
data: {
repl: rly
},
dataType: 'json',
success: function (data) {
document.getElementById("reply").value = "";
populatedata(data, send);
},
error: e => console.log(e)
});
});
function fetchdata() {
var send = "<?php echo $Sender?>";
$.ajax({
type: 'GET',
url: 'Message_chat.php',
dataType: 'json',
success: function (data) {
populatedata(data, send);
notification();
}
});
}
function notification() {
var notify = "";
$.ajax({
type: 'GET',
url: 'notify.php',
dataType: 'json',
success: function (data) {
if (data == null)
{
document.getElementsByClassName("ncircle")[0].style.display = "none";
} else {
var len = data.length;
for (var i = 0; i < len; i++) {
if (data[i].nread == 0) {
notify += "<p>" + data[i].nby + " sent you a message</p>";
}
}
$("#myDropdown").html(notify);
if (data.length != 0) {
document.getElementsByClassName("ncircle")[0].style.display = "block";
$(".ncircle").html(len);
}
}
},
error: e => console.log(e)
});
}
I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :
"use strict";
$(document).ready(function(){
function searchWikipedia(searchCriteria){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);
}
$('#btn').click(function searchCriteria() {
var searchCriteria = $("input[name=Wikipedia]").val();
searchWikipedia(searchCriteria);
})
function processResult(apiResult){
if (apiResult.query.pages[-1]){
console.log("No results");
} else {
for (var i = 0; i < apiResult.length; i++){
$('#display-result').append('<p>'+apiResult+'</p>');
}
}
}
});
So far nothing appends to my html and there's no errors in my console.
#Ali Mamedov's answer is the way to go (it's from Wikipedia)
But the wikipedia link is missing the http:. Also, you can handle the response on your function:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: processResult
});
});
});
function processResult(apiResult){
for (var i = 0; i < apiResult.query.search.length; i++){
$('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
}
}
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, item) {
if (i == 1) {
var searchData = item[0];
WikipediaAPIGetContent(searchData);
}
});
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
function WikipediaAPIGetContent(search) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=" + search + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
// remove links as they will not work
blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });
// remove any references
blurb.find('sup').remove();
// remove cite error
blurb.find('.mw-ext-cite-error').remove();
$('#results').html($(blurb).find('p'));
$('#results').html(blurb);
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
</script>
Try this sample:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: function (x) {
console.log('title', x.query.search[0].title);
}
});
});
});
Source
This will show the query result with image:
$(document).ready(function(){
$('#btn').click(function() {
var search_text = $("input[name=Wikipedia]").val();
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
$.getJSON( url + search_text +'&callback=?',function(data){
for(var key in data.query.pages){
var titleArt = data.query.pages[key].title;
var extractArt = data.query.pages[key].extract;
var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
var imgArt;
if(data.query.pages[key].hasOwnProperty('thumbnail')){
imgArt = data.query.pages[key].thumbnail.source;
} else {
imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
}
var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></div></div>';
$('#display-result').append(contentHTML);
}
});
});
});
function Wiki(lang) {
this.lang = lang || "fr";
this.inuse = false;
}
Wiki.prototype.research = function(s, callback) {
if (this.inuse) {
console.error("Wiki est déjà en cours d'utilisation !");
} else {
this.inuse = true;
var r = new XMLHttpRequest();
r.onload = function() {
Wiki.prototype.inuse = false;
var j = JSON.parse(r.responseText);
callback(j);
}
r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
r.send();
}
}
var c = new Wiki();
c.research("Victor Hugo", function(result) {
console.log(result);
});
//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
console.log(result);
}
I would like display my data following a tag select.
I fill the select tag with javascript method, hier it works well.
First : I want to pass in parameter the selectedindex value for my web service methode. But I have the error :
How do I have to write the parameter?
Here is the javascript code :
function getStatistic3() {
var response;
var allstat3 = [];
var e = document.getElementById("Select1");
var kla = e.options[e.selectedIndex].value;
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: { klant: kla },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
function fillSlectTag() {
var response;
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3_All_Klant',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
var sel = document.getElementById('Select1');
for (var i = 0; i < response.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = response[i];
opt.value = response[i];
sel.appendChild(opt);
}
},
error: function (e) {
alert("error loading select stat3");
}
});
}
Second : When I load the html page for the first time, it loads with null because I have not yet chosen the klant in the select tag.
How to fix this?
Edit :
#Talspaugh27
Here my html code :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
$(function () {
$('table').visualize({ type: 'line' });
});
fillSlectTag();
</script>
</head>
<body>
<select id="Select1" name="D1"><option></option></select>
<script >
$(".Select1").change(function () { getStatistic3(); });
</script>
<table id="table_campaigns" class="display">
<caption style="font-size:20px">Statistiek 3 : per klant en productgroep</caption>
<thead>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
And javascript code :
function fillSlectTag() {
var response;
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3_All_Klant',
//data: data2Send,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
var sel = document.getElementById('Select1');
for (var i = 0; i < response.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = response[i];
opt.value = response[i];
sel.appendChild(opt);
}
},
error: function (e) {
alert("error loading select stat3");
}
});
}
function getStatistic3() {
var response;
var allstat3 = [];
var e = document.getElementById("Select1");
var kla = e.options[e.selectedIndex].value;
if (kla) {
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: JSON.stringify({ klant: kla }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: false,
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
}
function showStatistic3() {
$("#contentCamp").empty();
$.ajax({
url: 'Statistic_3.html',
dataType: 'html',
success: function (data) {
$("#contentCamp").html(data);
getStatistic3();
},
error: function (e) {
alert("Error loading statistic 3 html : " + e.statusText);
}
});
}
Without having the full app to test I think this should take care of both of your problems Will Explain each change after the code bit
function getStatistic3() {
var response;
var allstat3 = [];
var e = document.getElementById("Select1");
var kla = e.options[e.selectedIndex].value;
if (kla)
{
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: JSON.stringify({ klant: kla }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
}
}
I wrapped the .ajax call in the if statement to capture whether a value is selected from your drop down and when you pass the data to the service Use the JSON.stringify to make sure that it properly wraps and escapes the data to something the service and javascript can mutually use.
HTH
T
Seems like the webservice expects json, which you aren't sending( you're sending url encoded form data)
Use JSON.encode to convert your data to JSON
$.ajax({
type: 'GET',
url: 'http://localhost:52251/Service1.asmx/Statistic_3',
data: JSON.stringify({ klant: kla }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
response = msg.d;
for (var i = 0; i < response.Items.length; i++) {
var j = 0;
allstat3[i] = [response.Items[i].Interventie, response.Items[i].Sum[j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j], response.Items[i].Sum[++j]];
}
fillDataTable(allstat3);
},
error: function (e) {
alert("error loading statistic 3");
}
});
I am calling live('click') function in which i call ajax method and do some server side functionality.
But before ajax call i need to check for valid data.
Am bit confused how to call it
// Depend on this condition i have to start process my ajax function.
function validData()
{
if ($('.edt').val() == "")
{
return false;
}
var maxtxtvalue = $('edt3').val();
var mintxtvalue = $('edt4').val();
// alert(maxtxtvalue > mintxtvalue);
if(parseInt(maxtxtvalue) > parseInt(mintxtvalue))
{
return true;
}
else
{
$('input:text[id$="txtmaxctc"]').val('');
$('input:text[id$="txtminctc"]').val('');
alert("Max ctc must be greater then Min ctc.");
return false;
}
}
$("img[class^='sav_']").live('click', function (event) {
if( return false )
{
}
else{
//start process
$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/upajx",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
} });
}
});
// Depend on this condition i have to start process my ajax function.
can't you do like this..
function validData()
{
if ($('.edt').val() == "")
{
return false;
}
var maxtxtvalue = $('edt3').val();
var mintxtvalue = $('edt4').val();
// alert(maxtxtvalue > mintxtvalue);
if(parseInt(maxtxtvalue) > parseInt(mintxtvalue))
{
return true;
}
else
{
$('input:text[id$="txtmaxctc"]').val('');
$('input:text[id$="txtminctc"]').val('');
alert("Max ctc must be greater then Min ctc.");
return false;
}
}
$("img[class^='sav_']").live('click', function (event) {
if(validData() )
{
}
else{
//start process
$.ajax({
type: "POST",
url: "ajax_function/updatefn.asmx/upajx",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.d);
} });
}
});