I am trying to figure out why my function to run the submit(searchBtn) is not working correctly. If you have any idea on what is going wrong, I would appreciate the help!
$(document).ready(function() {
//Click searchbtn and run our search
$('#searchBtn').click(function() {
// Get value of our searchbar that user inputs
var searchInput = $('#searchInput').val();
//reset our textbox when search is called
$('#searchInput').val('');
//set our search url with the API and searchInput
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchInput + "&format=json&callback=?";
$.ajax({
data: "GET",
url: url,
async: false,
dataType: "JSON",
success: function(data) {
$('#output').html('');
for (let i = 0; i < data[1].length; i += 1) {
$('#output').append("<li>" + data[1][i] + "<p>" + data[2][0] + "</p></li>");
}
},
error: function(errorMessage) {
alert("There was a problem retrieving your results.");
}
})
This is the function to run the click function when the enter key is released. It appears directly after the code example above.
$('#searchInput').keyup(function(event) {
if (event.which === 13) {
$('#searchBtn').click();
}
});
});
});
This is how I'd do it, it removes the programmatic click and just runs the function.
$(document).ready(function() {
//Click searchbtn and run our search
function search() {
// Get value of our searchbar that user inputs
var searchInput = $('#searchInput').val();
//reset our textbox when search is called
$('#searchInput').val('');
//set our search url with the API and searchInput
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchInput + "&format=json&callback=?";
$.ajax({
data: "GET",
url: url,
async: false,
dataType: "JSON",
success: function(data) {
$('#output').html('');
for (let i = 0; i < data[1].length; i += 1) {
$('#output').append("<li>" + data[1][i] + "<p>" + data[2][0] + "</p></li>");
}
},
error: function(errorMessage) {
alert("There was a problem retrieving your results.");
}
}
$('#searchBtn').click(search);
$('#searchInput').keyup(function(event) {
if (event.which === 13) {
search();
}
});
});
Solved with the help of #SethWhite and some people from /r/learnprogramming with the following code:
$(document).ready(function() {
//Click searchbtn and run our search
function search() {
// Get value of our searchbar that user inputs
var searchInput = $('#searchInput').val();
//reset our textbox when search is called
$('#searchInput').val('');
//set our search url with the API and searchInput
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchInput + "&format=json&callback=?";
$.ajax({
data: "GET",
url: url,
async: false,
dataType: "JSON",
success: function(data) {
$('#output').html('').addClass('animated slideInUp');
for (let i = 0; i < 5; i += 1) {
$('#output').append("<li>" + data[1][i] + "<p>" + data[2][i] + "</p></li>");
}
},
error: function(errorMessage) {
alert("There was a problem retrieving your results.");
}
})
$('#output').removeClass();
}
$('#searchBtn').click(function(event) {
event.preventDefault();
search();
});
$('#searchInput').keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
search();
}
});
});
Using event.preventDefault(); takes care of this, since each time the ajax is called, we are resetting the #seachInput with '' causing the input form to alert you of an empty form.
Related
I have a project dropdown.A user can multiselect projects.
I want to pass the values selected from multiselection in dropdown as filter parameters in ajax url.
The code is as follows:
function CheckIfPresent(callback)
{
var proj = [];
var urlprograms;
if ($("#projNameDropdown :selected").text() != 'Select all projects') {
$('#projNameDropdown :selected').each(function (i, sel) {
proj[i++] = $(sel).val();
if (proj.length == 1)
urlprograms = "(Project_Name/Project_Name eq '" + proj[0] + "')";
});
if (proj.length > 1) {
for (i = 1; i < proj.length; i++) {
urlprograms += " or (Project_Name/Project_Name eq '" + proj[i] + "')";
}
}
}
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists('')/items?$select=*,Project_Name/Project_Name&$expand=Project_Name&$filter=" + urlprograms + "'",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: function (dataActive) {
}
error: function (dataActive) {
console.log(dataActive);
}
});
}
I am not able to reach the success method and get error.What is that I am doing wrong?
How do I combine script 1 and script 2 to achieve my objective of sending data as well as one script.
The idea is to have the fresh content anytime a post is sent. I am using this with Framework7. Both scripts already work well in their roles to post or retrieve data.
This is the script that is getting/fetching data from the back-end.
SCRIPT 1
<script type="text/javascript">
$(document).ready(function() {
var url = "http://localhost/integration/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var comment = field.comment;
var user = field.user;
var post_time = field.post_time;
$("#listview").append("<tr class='even gradeA' width = '30px'><td>"+comment+"</td><td>"+user+"-"+post_time+"</td></tr>");
});
});
});
</script>
SCRIPT 2
The role of script 2 is to post data to the server.
<script type="text/javascript">
$(document).ready(function() {
$("#insert").click(function() {
var comment = $("#comment").val();
var user = $("#user").val();
var ip = $("#ip").val();
var dataString = "comment=" + comment + "&user=" + user + "&ip=" + ip + "&insert=";
if ($.trim(comment).length > 0 & $.trim(user).length > 0 & $.trim(ip).length > 0) {
$.ajax({
type: "POST",
url: "http://localhost/integration/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('Connecting...');
},
success: function(data) {
if (data == "success") {
alert("Successfully submitted");
$("#insert").val('submit');
} else if (data == "error") {
alert("error");
}
}
});
}
return false;
});
});
</script>
Both scripts are working independently.
Try this below code:
Here is what I have done. I have converted it into a function which you can call once your insertion code has been completed and also can be called when the page is refreshed.
function getUpdatedData() {
var url = "http://localhost/integration/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var comment = field.comment;
var user = field.user;
var post_time = field.post_time;
$("#listview").append("<tr class='even gradeA' width = '30px'><td>" + comment + "</td><td>" + user + "-" + post_time + "</td></tr>");
});
});
}
$(document).ready(function() {
getUpdatedData();
$("#insert").on('click', function() {
var comment = $("#comment").val();
var user = $("#user").val();
var ip = $("#ip").val();
var dataString = "comment=" + comment + "&user=" + user + "&ip=" + ip + "&insert=";
if ($.trim(comment).length > 0 & $.trim(user).length > 0 & $.trim(ip).length > 0) {
$.ajax({
type: "POST",
url: "http://localhost/integration/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('Connecting...');
},
success: function(data) {
if (data == "success") {
alert("Successfully submitted");
$("#insert").val('submit');
getUpdatedData();
} else if (data == "error") {
alert("error");
}
}
});
}
return false;
});
});
I was trying to redirect a page using jquery but it is not working.
I tried to use all the falvors:
window.location.href = url;
location.href = url;
window.location = url;
location = url;
window.location.assign(url);
my code is:
$(document).ready(function () {
btnsubmit = $("#btnLogin");
btnsubmit.click(function () {
var uName = $("#userName").val();
var uPass = $("#pasWord").val();
var str = -1;
$.ajax({
type: "Post",
async: false,
url: "Default.aspx/userLogin",
data: '{"userName":"' + uName + '","userPassword":"' + uPass + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
str1 = response.d;
str = str1;
},
failure: function (msg) {
alert("Please contact your administrator");
}
});
redirectUser(str);
});
redirectUser = function (str) {
if (str == 0) {
alert("Hello you have not yet been verified.\nPlease contact your supervisor for the same.");
}
else if (str == 1) {
alert("You have been approved by your supervisor.\nBut the admin has not approved you yet.");
}
else if (str == 2) {
document.write("You will be redirected to main page in 5 sec.");
setTimeout(redirect_changePassword(), 5 * 1000);
}
else if (str == 3) {
document.write("You will be redirected to main page in 5 sec.");
setTimeout(redirect_approved(), 5 * 1000);
}
else if (str == 4) {
alert("You have been rejected by your Supervisor.\nPlease contact your supervisor for the same.");
}
else if (str == 5) {
alert("You were approved by your supervisor.\nBut the admin has rejected you.\nPlease contact your supervisor for the same.")
}
else if (str == 6) {
document.write("You will be redirected to main page in 5 sec.");
setTimeout(redirect_admin(), 5 * 1000);
}
else if (str == 7) {
alert("Some unkonwn error has occured.\nPlease contact your administrator.");
}
else if (str == 8) {
alert("Wrong credentials");
}
else if (str == 9) {
alert("Some unkonwn error has occured.\nPlease contact your administrator.");
}
}
redirect_changePassword = function () {
var nextUrl = location.protocol + '//' + location.host + '/ChangePassword.aspx';
window.location.href = nextUrl;
}
redirect_approved = function () {
var nextUrl = window.location.protocol + "//" + window.location.host + "/UserHome.aspx";
//window.location.href = nextUrl;
window.location.assign(nextUrl);
return false;
}
redirect_admin = function () {
var nextUrl = location.protocol + "//" + location.host + "/AdminHome.aspx";
window.location.href = nextUrl;
}
});
please help me to solve the problem
if I write the url and then try then also it is not working.
even it is not redirecting to google.
You can make use of javascript Promise or jQuery Deferred object
var promise = new Promise (function (resolve, reject) {
$.ajax({
type: "Post",
async: false,
url: "Default.aspx/userLogin",
data: '{"userName":"' + uName + '","userPassword":"' + uPass + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
str1 = response.d;
str = str1;
},
failure: function (msg) {
alert("Please contact your administrator");
}
});
promise.then(function success() {
redirectUser(str);
});
according to your code redirectUser(str) function is called before ajax is executed. You can keep redirectUser(str) in done of ajax. So, str will have -1.
$.ajax({
type: "Post",
url: "Default.aspx/userLogin",
data: '{"userName":"' + uName + '","userPassword":"' + uPass + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
str1 = response.d;
str = str1;
},
failure: function (msg) {
alert("Please contact your administrator");
}
}).done(function(){
redirectUser(str);
});
I found the error and solved it by using the following code:
document.write("You will be redirected to main page in 5 sec.\n" + "<script>window.location.href ='http://google.com'; </script>");
//but this was not working because you have already passed data to headers, but not the redirect code.
setTimeout(redirect_approved(), 5 * 1000);
actually the new page was created and hence the page redirect was not working
Please look at this code on https://jsfiddle.net/safron6/9g98j68g/embedded/result/
I am trying to get the calculated result from the list of APIS and JSON code that is generated to show the precipIntensity. At the end of the code there is an alert and the code works in firebug but nothing is showing up. What may be the reason why the alert does not pop up?
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
});
totalPrecipSinceDate did not declared.
I can't access your hosted data source.
Replacing your current $.getJSON call with an $.ajax call should work:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.ajax({
type: 'GET',
url: darkForecastAPI,
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain") {
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
},
error: function(){
alert('failure');
}
});
});
I am using jQuery.validationEngine plugin .I have a below ajax function to check duplicate unique value for a field.
function _is_unique(caller) {
var value = jQuery(caller).val();
var field_id = jQuery(caller).attr('id');
var field_name = jQuery(caller).attr('placeholder');
if (value != '') {
var uniqueObject = new Object();
uniqueObject.field_id = field_id;
uniqueObject.value = value;
var uniqueString = JSON.stringify(uniqueObject);
var getUrl = window.location;
//console.log(getUrl);
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
jQuery.ajax({
type: "POST",
url: baseUrl + "/dashboard/check_unique",
data: uniqueObject,
async: false,
cache: false,
dataType: "text",
success: function(msg) {
if (msg == "exist") {
isError = true;
promptText += " This " + field_name + settings.allrules["is_unique"].alertText + "<br />";
}
}
});
}
}
if the field value is present in server then from server I am returnning "exist" else I am returning "notexist".
Now while running my ajax script is calling infinitely . Can any please tell me what should I do to stop infinite loop of my ajax call.
Edited
This is the form Submit function . its also showing
too much recursion
error in console. By any chance am I having problem here ?
$('#searchform').on('submit', function(e){
var validateError ='';
var id='';
var fieldError = [];
$('#searchform :input:text').each(function(){
id = $(this).attr('id');
validateError = jQuery.fn.validationEngine.loadValidation(document.getElementById(id));
if(validateError)
{ fieldError.push(id);
}
});
if(fieldError.length!=0)
{
return false;
}
else{
$("form#searchform" ).submit();
return true;
}
});
});