Javascript functions keeps executing even after updating the DIV - javascript

I have certain content that gets updated using ajax on that Id, for example, let's suppose I have a complete main page and inside the body I have this code:
<div id="content">
<button onclick="update1()"></button>
<button onclick="update2()"></button>
</div>
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
<script src="js/script.js"></script>
And the index.html of Page1 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page1"> .....</div>
And the index.html of Page2 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page2"> .....</div>
And the script.js contains some code like this:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
});
What I want to do is when the button is pressed to call Ajax that gets the index.html from Page1 and puts it inside the id content, run a script.js this script only executes when the id page1 exists, I have found this trick from this answer, by using an if with jQuery for example if($('#page1').length ){my sj code} the javascript code runs only when that id exists, but unfortunately when I click the button to get the Page2 that has another id page2 that code keeps running, is there a way to stop this js code when that div is updated???

The function is not stopping because the interval will not stop firing unless you clear it, using clearInterval() function.
just put all your JS code in one file like this:
$(document).ready(function() {
var the_interval = setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
function stopTheInterval(){
clearInterval(the_interval);
}
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
stopTheInterval(); // we stop the first interval
}
});
}});
what I did here is saved the interval number in a variable, and created a new function to clear it.
next, all I did was put my new function in your update2() function, so once I get the data back I clear the interval and stop the repeating function.

script.js
dont use setInterval.
function some_function(){
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}
And call above function in update1.because you want it only when page1 updated
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
some_function() // call function here
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>

Try using update1().stop()
in starting of update2 function

Related

Html Ajax button not doing anything

im sure this is something obvious but I cant figure it out
onclick of button retrieveScoreButton my button is simply not doing anything
any help is appreciated, im attempting to append the data to a table but cant even get it to register the clicking of the button so I cant test the function showsccore
<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>
<div id="Scores">
<ul id="scoresList">
</ul>
</div>
<script>
$(document).ready(function () {
$("#addScoreButton").click(function () {
$.ajax({
type: 'POST',
data: $('form').serialize(),
url: '/addScore',
success: added,
error: showError
}
);
}
);
});
$(document).ready(function () {
$("#retrieveScoreButton").click(function () {
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
}
);
}
);
});
function showScores(responseData) {
$.each(responseData.matches, function (scores) {
$("#scoresList").append("<li type='square'>" +
"Home Team " + matches.Home_Team +
"Away Team: " + matches.Away_Team +
"Home: " + scores.Home_Score +
"Away: " + scores.Away_Score
);
}
);
}
function showError() {
alert("failure");
}
</script>
</body>
</html>
There are a couple things wrong here:
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
});
First, you never defined id. (After some comments on the question it turns out your browser console is telling you that.) What are you trying to log? You may as well just remove that line entirely.
Second, what are you expecting here?: success: alert("success") What's going to happen here is the alert() is going to execute immediately (before the AJAX call is even sent) and then the result of the alert (which is undefined) is going to be your success handler. You need a handler function to be invoked after the AJAX response, and that function can contain the alert.
Something like this:
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: function() { alert("success"); },
error: showError
});
(To illustrate the difference, compare your current success handler with your current error handler. One of them invokes the function with parentheses, the other does not. You don't want to invoke a handler function right away, you want to set it as the handler to be invoked later if/when that event occurs.)

LARAVEL: Use a javascript variable in php

I would like to get an id from a button. I need this id in my ajax request. This is my button:
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
I'm getting the id of the button this way:
<script type="text/javascript">var JcarID = this.id;</script>
Finally my Ajax Request.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '{{ action('CarController#delete', [$user->id, $car->id])}}',
success: function (data)
{
// alert(data);
}
});
});
Thx for reading!
SOLUTION
Changed some bits in my code. I changed the url of my request.
$('[name="deletecar"]').click(function (e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/deletecar/'+this.id,
success: function (data)
{
// alert(data);
}
});
});
Hard to guess what is your requirement yet either if you want to get the button id value
this.attr('id'); or this.prop('id');
Or if you want to set the id value of button
$('[name="deletecar"]').attr('id', yourvalue)
I think you want to use JcarId rather $car->id in ajax request. Here what you can do rather than directly using PHP code in ajax call.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '/CarController/delete',
data: {'carId':JcarId}
success: function (data)
{
// alert(data);
}
});
});

Ajax execute only once inside an event

I have created a widget that displays a html template fetched with an ajax request to the server. I want to refresh the template clicking on a <p> element of the template. However when I click on it, it refreshes the template only once, then, if I try to click again, the event does not respond, it does not execute the request again. This is my code, if someone has any idea what I am doing wrong.
/******** Our main function ********/
function main() {
jQuery(document).ready(function ($) {
var widget_url = "/home/widget?callback=MyCallbackFunction"
$.ajax({
url: "/home/widget",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
success: function (data) {
$('#example-widget-container').html(data.html);
$("#panel-sidebar-icon").on("click", function () {
$.ajax({
url: "/home/widget",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
cache: false,
success: function (data) {
$('#example-widget-container').html(data.html);
}
});
});
}
});
});
}
The template example:
<aside>
<p id="panel-sidebar-icon">Click </p>
<ul>
<li>.... </li>
</ul>
</aside>
events attached to DOM elements are lost when you replace the container html, so.
change this
$("#panel-sidebar-icon").on("click", function () {
to this
$("body").on("click", "#panel-sidebar-icon", function () {
maybe because you create a new DOM object so the event goes with the erasure. You should update simple datas on the element or recreate the same component+event associated to it

Updating div content after form submit without page reload

alright, I have a popup which displays some notes added about a customer. The content (notes) are shown via ajax (getting data via ajax). I also have a add new button to add a new note. The note is added with ajax as well. Now, the question arises, after the note is added into the database.
How do I refresh the div which is displaying the notes?
I have read multiple questions but couldn't get an answer.
My Code to get data.
<script type="text/javascript">
var cid = $('#cid').val();
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid="+cid,
dataType: "html", //expect html to be returned
success: function(response){
$("#notes").html(response);
//alert(response);
}
});
});
</script>
DIV
<div id="notes">
</div>
My code to submit the form (adding new note).
<script type="text/javascript">
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: { note: note, cid: cid }
}).done(function( msg ) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();
//$("#notes").load();
});
});
</script>
I tried load, but it doesn't work.
Please guide me in the correct direction.
Create a function to call the ajax and get the data from ajax.php then just call the function whenever you need to update the div:
<script type="text/javascript">
$(document).ready(function() {
// create a function to call the ajax and get the response
function getResponse() {
var cid = $('#cid').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid=" + cid,
dataType: "html", //expect html to be returned
success: function(response) {
$("#notes").html(response);
//alert(response);
}
});
}
getResponse(); // call the function on load
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: {
note: note,
cid: cid
}
}).done(function(msg) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();}
getResponse(); // call the function to reload the div
});
});
});
</script>
You need to provide a URL to jQuery load() function to tell where you get the content.
So to load the note you could try this:
$("#notes").load("ajax.php?requestid=1&cid="+cid);

Can AJAX update a button argument?

Using AJAX, I'm able to extract a data value from a button click, but is it possible to ensure this value is passed on to an argument within another button on the same page?
test.html:
Activate
Fader
test.js:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
}
});
}
The php file connects to the database and extracts the most recent image number - it works fine and the alert box displays the correct value. So what would be the next step to ensure the "image_number" argument is updated with this 'data' value?
Cheers.
make a global variable like
windows.image_number = 0;
for AJAX function.
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
//update the global variable
windows.image_number = data;
}
});
}
Assuming that the image_number variable that you are passing to the function is a globally defined variable, you simply need to set the variable in your success callback:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
// Assuming data holds the image number you want to use for next click
image_number = data;
}
});
}

Categories