I´m quite new to Javascript and jQuery. For a project I want to check if a Sharepoint list contains any duplicates, without using build in function, to expand it later on to compare more than one column. In my current code I'm retrieving the value of a lookup field and try to match it to all my results in my table. While I properly got my lookup value, my matching variable (x) shows multiple "undefined" entries. When manually typing in the URL, the XML-document shows all the necessary values in my list.
How can I properly retrieve each of my current list values and pass it to a variable?
<script src="https://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js" type="text/javascript"></script>
<!-- reference jQuery from Miscrosoft CDN -->
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script><script type="text/javascript">
function PreSaveItem() {
if (CheckExists()) {
alert('KU in USE');
return false;
} else {
return true;
}
}
function CheckExists() {
var gnr= $("select[title='Test']").find("option:selected").text();
alert(gnr)
var listUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('My List')/items?$select=*,Test/Test&$expand=Test";
var c = false;
$.ajax({
url: listUrl,
type: "GET",
async: false,
headers: { "Accept": "application/json;odata=verbose" },
success: function(data){
$.each(data.d.results, function(i, item) {
var x = item["Test"].text ;
alert(x);
if (x!= undefined) {
if (gnr === x) {
c = true;
}
}
}); // each
},
error: function(error) {
alert(JSON.stringify(error));
}
});
return c;
}
</script>
I expect the output of an alert, if a duplicate is found, but nothing happens.
The following example for your reference.
1.Create custom list "My List".
2.Add lookup field "Test", column look up values from another custom list with the column "ID".
3.Add the code below into script editor web part in new form page in "My List".
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function PreSaveItem() {
if (CheckExists()) {
alert('KU in USE');
return false;
} else {
return true;
}
}
function CheckExists() {
var gnr= $("select[title='Test']").find("option:selected").text();
//alert(gnr)
var listUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('My List')/Items?$select=Test/Id&$filter=Test/Id eq "+gnr+"&$expand=Test/Id";
var c = false;
$.ajax({
url: listUrl,
type: "GET",
async: false,
headers: { "Accept": "application/json;odata=verbose" },
success: function(data){
if(data.d.results.length>0){
c=true;
}
},
error: function(error) {
alert(JSON.stringify(error));
}
});
return c;
}
</script>
If you want to retrieve a property/column called "Test" from List "Test".
Instead of using:
var x = item["Test"].text
Try to use:
var x = item.Test.Test
Related
I need to make an AJAX request to API to get the word for a hangman game. Also struggling, on reading the word length and displaying it with placeholders. I referenced this link enter link description here , but am still stuck.
//function to get the word from the API using AJAX
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
//accessing global variable (word)
var results = $.getValues("https://hangman-api.lively.software");
for (var i < 0; i < word.length; i++) {
results[i] = "_";
}
Hopefully my snippet can help you in some ways. have a nice day!
$(function(){
$.ajax({
url: "https://hangman-api.lively.software/",
type: 'get',
success: function(data) {
//how to access word
console.log(data.word)
//how to create placeholders
placeHolder = " _ ";
placeHolders = placeHolder.repeat(data.word.length)
//how to print place holder
$(".placeHolder").text(placeHolders)
}
});
})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Placeholders : <span class="placeHolder"></span>
</body>
</html>
Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.
<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/
I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
I want to get the <title> of a page using its URL.
For example,
if the URL is (https://www.google.co.kr/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=ajax%20fail),
what I want to get is (ajax fail - google search)
Here is my code and unfortunately it does not work.
This code return error code: 0, undefined, no transport.
$(document).ready(function () {
titleInfo = {
url: "http://google.co.kr",
title: "abcd"
}
$('#target').text("SS");
requestAjax('http://gorapaduk.dothome.co.kr', titleInfo);
});
var requestAjax = function (url, data) {
$.ajax({
url: url,
cache: false,
success: function (html) {
alert(html);
request(html, data);
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
});
}
var request = function (html, data) {
var matches = data.match(/<title>(.*?)<\/title>/);
var spUrlTitle = matches[1];
data.title = spUrlTitle;
$('#target').text("spUrlTitle");
console.log(data.title);
}
Change,
var matches = data.match(/(.*?)</title>/);
to
var matches = html.match(/(.*?)</title>/);
in your request function .
and put,
dataType: "html",
in your ajax request .