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;
});
});
Related
var feedback = function (res) {
if (res.success === true) {
var get_link = res.data.link.replace(/^http:\/\//i, 'https://');
document.querySelector('.status').classList.add('bg-success');
document.querySelector('.status').innerHTML =
'Image : ' + '<br><input class="image-url" value=\"' + get_link + '\"/>' + '<img class="img" alt="Imgur-Upload" src=\"' + get_link + '\"/>';
}
};
The second portion is:
new Imgur({
clientid: '3527680b6690575', //You can change this ClientID
callback: feedback
});
How to get_link to php variable in a index.php page?
The solution is like this:
function notifvanish() {
var data = 0;
var dataset = 'set=' + data;
$.ajax({
type: "POST",
url: "notifvanish.php",
data: dataset,
cache: false,
success: function (html) {
//alert("Success");
}
});
}
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.
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
After submit a reply without 1st post Its display a blank data space and after refresh page its show reply.
What is problem here please.
..............................................................................
This is my script
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var replyList = $("#replynext");
function updateReplybox() {
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid=" + tutid,
complete: function (data) {
replyList.append(data.responseText);
replyList.fadeIn(2000);
}
});
}
$(".repfrm").click(function () {
error.fadeOut();
if (checkForm()) {
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$('.reply_here').hide();
$("#loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author=" + author + "&replycom=" + replycom + "&url=" + url + "&img=" + img + "&parent_id=" + parent_id + "&tutid=" + tutid,
complete: function (data) {
error.fadeOut();
$("#loader").hide();
replyList.append(data.responseText);
updateReplybox();
$("#repfrm").each(function () {
this.reset();
});
}
});
} else //alert("Please fill all fields!");
error_message();
});
Probably all this code should be inside a $(document).ready({ ... });
To debug: Open chrome inspector and put a brakepoint at this line: var tutid = inputTutid.attr("value"); and check for what is inside inputTutid variable.
Also you can try
inputTutid.val();
instead of
inputTutid.attr("value");
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;
}
});
});