I am a beginner in web dev and building a simple query-answer web app in which User enters the query in the text field and clicks on the button, JavaScript sends the POST request to server and server sends back the response. Now this response should be displayed on the screen till the user enters a new query and clicks on the button again.
This is the client side code
$(document).ready(function() {
$("button").click(function() {
$.post("ServletServer", {
Query: document.getElementById("query").value
},
function(data, status) {
var json_x = $.parseJSON(data);
$.each(json_x, function(index, element) {
$('#Results').append($('<div>', {
text: index+" "+element.URI
}));
});
});
});
});
When I tried to use window.location.reload() mentioned in some previous questions, like this:
$("button").click(function() {
window.location.reload()
});
It refreshes the page just after displaying the response. I want the response to stay on the page till user again clicks on the button. Can anybody please tell me where I am going wrong
You need to clear the results div before doing the POST request with $('#Results').html("");
$(document).ready(function(){
$("button").click(function(){
$('#Results').html(""); // clears the results, then does the ajax request.
$.post("ServletServer",
{
Query: document.getElementById("query").value
},
function(data, status){
doRequest = false; // update flag
var json_x = $.parseJSON(data);
$.each(json_x, function(index, element) {
$('#Results').append($('<div>', {
text: index+" "+element.URI
}));
});
});
});
});
Related
Hello i am working on a PHP Project where i need to load some request using ajax request. Below are my request function.
Function One: When showNotify event is click i call the ajax request to get content and use ajaxStart to show spinner untill the content is fully ready!
//* First click load nofication
$(document).on('click', '#showNotify', function() {
let check = $(this).data('check');
if(check === 0) {
//* Process notification
$(this).attr('data-check', 1);
//* Load ajax request
$(document).ajaxStart(function() {
$('#notify-wait').show();
});
$(document).ajaxComplete(function() {
$('#notify-wait').hide();
$('#list-noti').show();
});
$.ajax({
url: '/list-dd-notifications',
method: 'GET',
success: function() {
$('#notif-unread').hide();
}
});
}
});
Function Two: i need to check from the server side to see if user has a new unready notify and show up the new notification sign.
function checkNewFotify() {
$.ajax({
url: '/check-notifications',
method: 'GET',
success: function(data) {
if(data) {
if($('#notif-unread').is(":hidden"))
{
$('#notif-unread').show();
}
}
else
{
if($('#notif-unread').is(":visible"))
{
$('#notif-unread').hide();
}
}
}
});
}
//* check for new notification
setInterval(() => {
checkNewFotify();
}, 5000);
Problem: Any time the showNotify is dropdown at first it show the spinner the loader until the request is fully loaded also if the function checkNewFotify is doing is job by refreshing every 5 secs to check the server for new notification the ajaxStart in showNotify will be affected by showing the spinner loader every time the checkNewFotify is refreshing in background.
Please how can i stop it from showing the spinner loader whil it refreshing every 5 seconds.
Set the global option to false on the ajax on checkNewFotify() this will prevent handlers like ajaxStart from firing.
$.ajax({
url: '/check-notifications',
method: 'GET',
global: false,
});
im new here so forgive me if my question seems to be stupid
i have the following code to search youtube video with submit button (normal form)
i want to turned to real time input once the user write any word will fetch result depend on what wrot by hime
so i add
$(".search_input").keyup(function(e) {
instead of
$("form").on("submit", function(e) {
full code is here https://jsfiddle.net/5ymndbax/
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
$(function() {
$(".search_input").keyup(function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: $("#search").val(),
order: "viewCount",
publishedAfter: "2000-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("tpl/item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function init() {
gapi.client.setApiKey("key");
gapi.client.load("youtube", "v3", function() {
// yt api is ready
});
}
i hope can i got some help from you ❤
full of love to each of you.
Currently you are using keyup, and that will check entry by letter.
So you need to check did key up ended with " ",",","." etc. for that will mostly mean the end of the word.
Now when we have the word, we want to add that to
previously entered words so you need to
concatenate or append new_word to previous_words.
And only then you should call AJAX call to URL or script that is using YouTube API for search...
It should go something like this:
**
event.preventDefault();
$.ajax({
type:"GET",
url: "youtube url or some script preforming to yt api call",
data:{"search": previous_words,},
success:function(data){
//display data somewhere
console.log(data);
}
});
I have two pages, on the first page you can select an item with a <select> </select>. When you select an item, a form is automatically displayed through an AJAX Call. In this form, data is automatically loaded from a mysql db in a <textarea> </textarea>. The moment you submit your form, I want the new data to be added to the <textarea> </textarea> I just can't manage this, who can help me?
$(document).ready(function () {
$("#btnAdd").click(function (e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
$.post("save.php", {
besproken: besproken,
}, function (data) {
$("#autoSave").html("Coaching ");
$("#btnAdd").attr("disabled", true);
});
return false;
});
});
If all you want to do is insert the data into the textarea just use jQuery to selected the element $("textarea") then call the text method and pass in your data .text(data). The result call will look like $("textarea").text(data)
$(document).ready(function() {
$("#btnAdd").click(function(e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
$.post("save.php", {
besproken: besproken,
}, function(data) {
$("#autoSave").html("Coaching ");
$("#btnAdd").attr("disabled", true);
$("textarea").text(data);
});
return false;
});
});
You can take a div. When you click submit you will get a ajax response, load this inside the div.
success: function(data){
$("#status").load("url of the php-file");
or
$("#status").html(data);
}
I'am making use of laravel pagination($data->links()) for ajax pagination using below code.
$(document).on("click", '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
loadArts(url);
});
function loadArts(url) {
$.ajax({
url : url
}).done(function (data) {
$(".image-masonry").html(data);
jsIntializations()
}).fail(function () {
alert('Articles could not be loaded.');
});
}
it's working fine, but upon clicking back button from an inner page, browser returning back to page1.
Here is the controller function
public function index(Request $request)
{
$arts = Art::with('artist')->orderBy('id','ASC')->paginate(10);
if($request->ajax()){
return view('art::art.list', compact('arts');
}
return view('art::art.index', compact('arts');
}
.image-masonary is the class in index.blade.php to which contents of list.blade.php is being loaded upon pagination.
This is the url : http://localhost:8000/admin/arts
I tried this method , history.pushState({ path: url }, '', url);
then back button is taking ajax route, but getting only broken view.
You may refer to the answer below
https://blog.pisyek.com/browsers-back-button-issue-after-logout-laravel-5
https://laracasts.com/discuss/channels/requests/back-button-browser?page=1
I don't want to submit my form with AJAX, but I want to make a progress bar by making a couple of GET requests to the server during form submission, since the submission might take a while with multiple file uploads. I've found that in webkit browsers, I can't make GET requests while the form is submitting and I was seeing that submitting the form to an iframe would allow me to do it.
The markup looks like this:
<form action="/my-action" target="target-iframe">
...
</form>
<iframe name="target-iframe"></iframe>
And the JavaScript:
$(document).ready(function() {
$("form").on("submit", function() {
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
I'm still not getting data back on the GET request--how can I get this to work?
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault(); //stop the form from submitting
$.get("/other-action", function(data) {
// Use data returned here
});
});
});
EDIT
Set a flag that won't allow the form to submit until you've received your response form your get request. Once you've received your response, set your flag to allow your form to submit and then resubmit it programmatically.
$(document).ready(function() {
var canISubmit = false;
$("form").on("submit", function(e) { //add a parameter e - the event object
var el = $(this);
if(!canISubmit) {
e.preventDefault();
$.get("/other-action", function(data) {
canISubmit = true;
el.submit();
});
}
});
});
The only way to be certain that your $.get request was completed is to make sure that the form doesn't submit and redirect the page until your $.get request completes.
EDIT #2
$(document).ready(function() {
$("form").on("submit", function(e) { //add a parameter e - the event object
e.preventDefault();
$.post("url",$(this).serialize())
.done(function(response,status,jqXHR) {
$.get("/other-action")
.done(function(response,status,jqXHR) {
//other stuff done
//refresh the page or do whatever....
})
.fail(function() {
//$.get failed
});
})
.fail(function() {
//$.post failed
});
});
});