How to execute ajax if page is load - javascript

I am trying to display the database table using php. When the page is loaded I need to show all table data and when I select the dropdown select, I neeed to display only data related to it ie.using where condition. I don't need any sql query or php code for it, I just need jquery.
$(document).ready(function()
{
$('#myHref').change(function()
{
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
});
$('#myHref').on('change',function()
{
$('#projectDetail').fadeIn();
});
});
Here when I select drop down menu id="myHref" execute get_projectName.php, but I need to execute get_projectName.php when page is load before select dropdown so I can display all data
Plz Help!!

bt I need to execute get_projectName.php when page is load before select dropdown so i can display all data
So I see you want to initially load execute get_projectName.php once when page loads and also execute it if there are any changes in the dropdown. So you can do like below
$(document).ready(function() {
//make a call initially on page load
var firstOptionValue = $("#myHref option:eq(1)").val() // take first option value as default
$.get('get_projectName.php',{id:firstOptionValue},function(data)
{
$('#projectDetail').html(data);
});
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
});
Refactoring the code, you can just pull out the common logic into a function and call that function by passing the required value, See below
$(document).ready(function() {
//make a call initially on page load
var firstOptionValue = $("#myHref option:eq(1)").val(); // take first option value as default
GetProjectDetails(firstOptionValue);
$('#myHref').change(function(){
var value = $('#myHref').val();
GetProjectDetails(value);
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
function GetProjectDetails(value){
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
});
}
});

In the above code you are trying to pass the selected id to php file through $.get() when the dropdown is changed. it is fine, if you want to display all the data when page is loaded then you should have another php which returns all the data in db and doesn't take any value. And write the code as below
$(document).ready(function() {
$.get('get_allDataFromDb.php',function(data)
{ $('#projectDetail').html(data);
});
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{ $('#projectDetail').html(data);
});
});
$('#myHref').on('change',function(){
$('#projectDetail').fadeIn();
});
});

function getData(value) {
params = {};
if value
params.id = value;
$.get('get_projectName.php', params, function (data) {
$('#projectDetail').html(data);
});
}
// Get Data onLoad
getData($('#myHref').val());
$('#myHref').on('change',function(){
getData($('#myHref').val());
$('#projectDetail').fadeIn();
});

Looks like your element (e.g. #myHref) don't exist at time when your script . And when you want to show all data on load just call function eg.
function getData(){//ajax here}
getData();
running. Are there any errors? or something that can help?

Try like this
$(document).on("change", "#myHref" , function() {
// Your Code Here
});
let me know in case it still dont work.

Ok , here is my another answer that how you can trigger some event after our document get ready .
hope this will be helpful to you .
<script>
$(document).ready(function(){
//Function for AJAX Call
function GetData(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
$('#projectDetail').html(data);
//
$('#projectDetail').fadeIn();
// Any other code here you want to write.
});
}
$('#myHref').change();
//OR you can use
$("#myHref").trigger("change");
});
$(document).on("change", "#myHref" , function() {
// Call the function as change evvent is triggered
GetData();
});
</script>

Related

URL check with JS

I have two scripts, first of them clicks on the button and after that browser opens a new window, where i should click on the other button by the second script, is it possible to run them both at the same time, I mean like unite those scripts together?
function run() {
var confirmBtn = document.querySelector(".selector,anotherSelector ");
}
after this new window appears and here`s the second part of my script
var rooms = document.querySelectorAll(" .btn-a-offers");
console.log(rooms);
for (var room = 0; room < rooms.length; room++) {
rooms[room].click();
}
var prices = document.querySelectorAll(" .li-right-side>strong");
console.log(prices);
for (var price = 0; price < price.length; price++) {
}
var prices = [];
document.querySelectorAll(".new-pa-hotelsoffers .li-right-side > strong").forEach(function(price) {
prices.push(parseFloat(price.innerHTML.replace(/[^0-9.]/g, "")))
})
console.log(
Math.min(...prices).toFixed(2)
)
My English is not that good so I want to be sure that I explained everything right, second script must be executed in the new window, that opens after first script
Depending on the logical dependancy of your application and the use of the functions, you could execute the second function in a document.ready function on the second page.
Example:
<script>
//jQuery
$( document ).ready(function() {
secondFunction();
});
//Pure JS
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
r(function() {
secondFunction();
});
</script>
However, if the page is to act independantly, and the second function is only to respond upon the execution of the first function, then that solution would not be the one you are looking for.
In the case where the function has to act entirely dependant on the use of the first function you could parse a value in the URL (better known as a GET variable) and check if that value is set.
Example:
<script>
functionOne() {
window.location.href = '/your_page.php?click=1';
}
</script>
Then on your second page you need to retrieve the GET variable.
<?php
$clicked = $_GET['click'];
?>
You can then perform a check to see if the variable has been set and fire your function upon that logic.
<?php
if($clicked != "") {
echo '
<script>
functionTwo();
</script>';
}
?>
Another way of doing it could be by the use of AJAX and have the other function execute in the AJAX' success function. That way you can eliminate the use of the GET variable, which is visible in the URL.
Example:
<script>
functionOne() {
$.ajax({
type : "POST", //or GET
url : "/your_page.php",
data : {
//parse your POST variable data if any
// variable : value,
// anotherVairable : anotherValue
// [....]
},
success: function (html) {
//Success handling
secondFunction();
}
})
}
</script>
Note that the AJAX used in the example is jQuery AJAX, so if you want to use some AJAX logic involving this structure, you'll need to include a jQuery library.
You should pass some parameter in the URL query like this:
// first-script.js
openNewWindow('http://example.com?run-second-script=1') // openNewWindow is fake function, just for demo
// second-script.js
if (window.location.search.includes('run-second-script=1')) { ... your code here ...}

How do I use the .done() callback to run a function for new data being loaded on request?

I have a page displaying data from a json feed and I also have a button which loads more of the feed on click of a button. My aim is to append some content inside the page for each feed item. I have been able to create a function which does this on load of the page, but I am unsure how to make this work with the aysynchronous loading of more data.
I understand I need to use the .done() callback to make this work but need some guidance how to implement it correctly.
This function appends the new content initially:
function appendFeed() {
$('.feed__item').each(function (index) {
$feedItem = $('.feed__item', $(this));
$feedItem.append('<div class="feed-gallery"></div>');
for (var i = 1; i <= 5; i++) {
var $count = i;
if ($count > 1) {
$('.feed.gallery', $(this)).append('<div><img data-lazy="//placehold.it/50x50"></div>');
};
});
}
This is where the .done() callback is referred, on click of a button:
$('button').click(function(){
$.getJSON(uri, function (json, textStatus) {
// do stuff
}).done(function (json) {
// do stuff - in my case this would be appendFeed()
});
});
I have already called the appendFeed() function, but if I put it inside the .done() callback on click the button, then it appends the feed again. How do i prevent the duplication for the feed that is already on the page?
This is how you will write.
<script type="text/javascript">
$.getJSON("/waqar/file.php").done(function (data) {
$(".output").append(data);
});
</script>

I get 'Bad assignment' when trying to use $(this) inside function after .load() method

I couldn't find any solutions for my problem yet. Maybe I used wrong keywords.
I'm trying to update the value of an input field onchange after a .load() action has been performed.
Here is my script:
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(this).val('OK');
});
});
So, after someAction.php has been loaded into #actionDiv successfully, I'd like to change the value of that input field, that has been changed.
I have several input fileds, which take this kind of action...
It seems "$(this)" is unknown in the function after load() has been completed.
Can anyone please help?
Thanks
You need to store a reference to the element, or use an arrow method which doesn't change the value of this
$(document).on("change",".myInput",function() {
var that = this;
var value = $(that).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(that).val('OK');
});
});
OR
$(document).on("change",".myInput",function(e) {
var value = $(e.target).val();
$('#actionDiv').load("someAction.php?value="+value, function() {
$(e.target).val('OK');
});
});
OR
$(document).on("change",".myInput",function() {
var value = $(this).val();
$('#actionDiv').load("someAction.php?value="+value, () =>{
$(this).val('OK');
});
});

Page refresh after the request is Done

I have a page with many checkboxes on it, I wrote a JS code that makes call to PHP page for each page, I want to refresh the page after the call has completed..
Here is my code
$(".matchFrnds").each(function(){ //For each CheckBox
if($(this).is(':checked')){
var sendData= $(this).val();
$.post('Call to PHP Page',{sendData:sendData},function(data){
window.location.reload();
});
}
});
The problem is that the page reloads after completing few checboxes, so if there are 60 checkboxes, the page reloads after making call for 10 checkboxes. I also changed the place for window.location.reload(); but the results are same, I want that once the call for all the checkboxes is completed then it reloads.
You can check how many calls you have finished then reload
var boxes = $(".matchFrnds:checked").length;
var calls = 0;
$(".matchFrnds").each(function(){ //For each CheckBox
if($(this).is(':checked')){
var sendData= $(this).val();
$.post('Call to PHP Page',{sendData:sendData},function(data){
calls++;
if(calls >= boxes) {
window.location.reload();
}
});
}
});
It is really easy.
You just need to set a counter, and call reload() on the last one.
The idea would be to have another variable...
// Save the element to iterate in a variable
var matchFrnds = $(".matchFrnds"),
//and save its length too
length = matchFrnds.length;
//Iterate over it
matchFrnds.each(function() {
// modify the counter
--length;
if ($(this).is(":checked")) {
// do your things
$.post( ... , function(data) {
//do what you need to do with the data...
// ....
// ....
});
}
//and, if it's the last element
if (!length) {
// LAST ITERATION!
window.location.reload();
}
});
And that's it.
You could use the .ajaxStop-Event
http://api.jquery.com/ajaxStop/
you can try with this after complete your request:
location.reload();

Resend AJAX request with link?

Is there anyway to reload just the AJAX request, so that it updates the content pulled from the external site in the code below?
$(document).ready(function () {
var mySearch = $('input#id_search').quicksearch('#content table', { clearSearch: '#clearsearch', });
var container = $('#content');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(url)+
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("table");
container.append(justTable);
mySearch.cache();
$('.loading').fadeOut();
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#content').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('link');
});
Right now I have a button which reloads the entire page, but I just want to reload the AJAX request. Is this even possible?
Edit: I need to specify more. While it can easily call the AJAX again, can it also replace the info that is already there?
You just need to call the doAjax function again on button click...
$("#buttonID").on("click", function() {
doAjax("link");
});
Add that into the above document.ready code and set the button ID correspondingly.
Then change
container.append(justTable);
to
container.html(justTable);
In your doAjax function you append HTML onto an element. If you overwrite the element's HTML instead of appending to it then the HTML will be "refreshed" each time the doAjax function runs:
Simply change:
container.append(justTable);
To:
container.html(justTable);
And of-course you can bind a click event handler to a link (or any element) like the rest of the answers show. Make sure you bind the click event in the proper scope (inside the document.ready event handler) so the doAjax function will be accessible from the click event handler.

Categories

Resources