I have a JSON file, js/links.json:
{ "allLinks": [
{
"Link": "http://bbc.com",
"Poster": "John"
},
{
"Link": "http://espn.com",
"Poster": "Jane"
}
...etc.
and the following HTML:
<input placeholder="http://" id="urlField" type="text">
<button type="button" id="search" name="button">Search</button>
<div id="result"></div>
The behaviour I would like is:
You enter a link into the input
When the button is clicked, get the links.json array and loop through it.
If the link exists, output into #result: "This exists, and was posted by [poster]"
If it does not exist, output into `#result"This link does not exist."
This is how I'm trying to do it now:
$(function(){
$.ajax({
type : 'GET',
url : 'js/links.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(jsonResult){
$("#search").click(function() {
var searchValue = document.getElementById('urlField').value;
// Go through the whole list and find the Link name
var linkExists = false;
$.each(jsonResult.allLinks, function(i, obj) {
if (obj.Link === searchValue ) {
linkExists = true;
alert("It exists");
return false;
}
else {
linkExists = false;
alert("It doesn't exist");
return false;
}
});
});
}
});
});
There's definitely something wrong here because, if I don't use the else, it appears to work. When I add it, it doesn't— it always defaults to "It doesn't exist."
Thanks in advance for the help.
Pull the contents of your else statement outside of the for loop, otherwise you alert failure every time you hit the first element and it doesn't produce a match.
$(function() {
$.ajax({
type: 'GET',
url: 'js/links.json',
async: false,
beforeSend: function() { /*loading*/ },
dataType: 'json',
success: function(jsonResult) {
$("#search").click(function() {
var searchValue = document.getElementById('urlField').value;
// Go through the whole list and find the Link name
var linkExists = false;
$.each(jsonResult.allLinks, function(i, obj) {
if (obj.Link === searchValue) {
linkExists = true;
alert("It exists");
return false;
}
});
if (!linkExists) {
alert("It doesn't exist");
return false;
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
Sorry if there are some mistakes, but I am a total noob and I am also posting for the first time on StackOverflow.
I am trying to configure a submit form, that controls if the inserted PIN is right, and if so goes on with the submission. I did some online research and found out that with jQuery we can use to function event.preventDefault(), I tried to insert it inside my AJAX request but it looks like it doesn't stop the form from being saved.
The code looks like these:
function verifyOTP() {
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp" : otp,
"PIN" : PIN,
"action" : "verify_otp"
};
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
},
error : function() {
alert("ss");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
error : function(event) { event.preventDefault(); };
}
//if I insert "return false;" here the submit is always blocked
}
I checked on atom if the parenthesis are right and it looks like it is.
Any ideas how I should use the preventDefault()?
I also checked if the output of m_ajaxpinr.php is correct, and it is. I also tried like these but it still didn't work...
if (otp != null) {
$.ajax({
url : 'm_ajaxpinr.php',
type : 'GET',
dataType : "json",
data : input,
success : function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
$("form").submit(function(event) {
if (response.type == 'success')
{
alert(response.type);
}
else if (response.type == 'error')
{
alert(response.type);
event.preventDefault();
}
});
as said in comment above ajax call is asynchronous, you need to complete cancel default action for the form or put event.preventDefault(); on the top function, then submit it in success function if it valid otp.
.val() will not return null, it return empty if no input.
$('#myForm').on('submit', verifyOTP);
function verifyOTP(e) {
e.preventDefault(); // note this
$(".error").html("").hide();
$(".success").html("").hide();
var otp = $("#contomovimentato").val();
var PIN = $("#PINvalue").val();
var input = {
"otp": otp,
"PIN": PIN,
"action": "verify_otp"
};
if (otp) { // mean not null, undefined, empty, false, 0
$.ajax({
//url: 'm_ajaxpinr.php',
url: 'https://httpbin.org/anything/test',
type: 'GET',
dataType: "json",
data: input,
success: function(response) {
$("." + response.type).html(response.message)
$("." + response.type).show();
if(response.args.otp == 1234){
console.log('valid otp, continue submission')
$('#myForm').off('submit'); // remove submit event
$('#myForm').submit(); // then submit the form
}
else{
console.log('invalid pin,\nvalid pin: 1234');
}
},
error: function() {
console.log("server error, submission cancelled");
}
});
} else {
$(".error").html('XPIN non valido.')
$(".error").show();
console.log("otp maybe empty, submission cancelled");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input id="contomovimentato">
<button>submit</button>
</form>
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
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();
}
}
So I want to detect if the value a user is typing in an input exists in the database, if so, display an error message. I've gotten pretty close except when the input is empty, the empty value is being submitted instead of what is GOING to be typed.
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
})
});
I've also tried one with a keyup function and it's still doing the same, evaluating the empty field. How can I have it so it's constantly evaluating what is being typed?
Along the same lines as Jeff Puckett's answer, I would perform the empty test and return an instructional message if empty:
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
if (val.length < 1 || val==""){
alert('Please complete all fields');
$('#email').css('background','yellow').focus();
return false;
}
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
});
});
This snippet creates an input with the id of "in" and checks if there is something in in's value. I guess that is answering your question a bit more specifically. And thanks "Jeff Puckett II" for pointing this out.
$('#in').on('input focusout', function(){
var val = $('#in').val();
if (val != ""){
console.log('someones typing');
} else {
console.log('empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="in" type="text">
</body>
try .on('input') instead of .on('blur')
$("#email").on("input", function(){//do something});
//in your function just add
if(!val) {
$(".error-msg").text("Empty!");
}
//or
if(val) {
//your ajax code
}
simply check if input is empty first
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
// check if val is empty
if (val != "")
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
})
});
use this:
$('input').keyup(function(){
console.log($(this).val());
});
keyup or keydown to get data every time when a user type in the focused input.
I got an if-else script:
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
if (isFav(fid)) {
alert("Do you want to remove from favorite?");
}
else {
alert("Add to favorite?");
}
});
calling the isFav script function:
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}
which in turn calling my controller action:
public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}
Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered.
I cant get what is wrong here. Any idea?? Please help..
The ajax request in isFav is async and the isFav method will return before it is completed.
This is probably how I would solve it:
function isFav(fid, callback) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { callback(result); }
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid,function(result){
if(result && result.toLowerCase() == "true"){
alert("Do you want to remove from favorite?");
} else {
alert("Add to favorite?");
}
});
});
You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed.
You're gonna need some remodeling.
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) {
if(result == 'favorite') alert("Do you want to remove from favorite?");
else alert("Add to favorite?");
}
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid);
});