i have a Click function , inside it ajax post method,
this method is getting info from database
after i click the button the info show up for 1 second and then they vanish .
this is the code
$('.ViewVisitorMsg').click(function() {
var requestsID = $(this).attr('data-id');
$.ajax({
type: 'post',
url: baseURL + "admin/Messenger/get_messages_to_admin",
data: {
request_id:requestsID
},
dataType: 'json',
success: function(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].sender == 1) {
chatBox.append("<li class= 'clearfix'><div class='message-data align-right'></div><div class='message other-message float-right'>" + data[i].message + "</div></li>");
} else {
chatBox.append("<li><div class='message-data'><span class='message-data-name'> Vincent</span></div><div class='message my-message'>" + data[i].message + "</div></li>");
}
}
}
});
});
i tried to put manually one ID and it works.
it's like when the click function finish , it resets all variables
EDIT:
it's link not a form
You are probably clicking on a button inside a form which is interpreted as a submit button (<button type="submit">), which will submit the form and refresh the page. Change the button to <button type="button"> to prevent it from submitting the form.
Related
I've created an application using codeigniter 3 that gets quizzes stored in the SQL database using a model and populate in the view using ajax and jquery.
Below is the code for populating data inside a div.
$(document).ready(function() {
$.ajax({
url: "/CW2/ASSWDCW2/cw2app/index.php/Leaderboard/quiz",
method: "GET",
dataType: "json"
}).done(function(data) {
$('#modtable tr').remove(); // clear table for new result
var quizzes = data.allQuizzes;
alert(quizzes.length);
var i;
for (i = 0; i < quizzes.length; i++) {
quiz = quizzes[i];
var block = ' <div id="quizMainBox"><h1>' + quiz.quizName + '</h1><br/><h3>' + quiz.creatorName + '<button onclick="myFunction(\''+quiz.quizId+'\')">Try it</button>'+'</h3></div>'
$('#allQuizBox').append(block);
}
});
return false;
// });
});
Below are 3 quizzes populated in the view.
What I want to do is when the user clicks on the "try it " button, I want the user to be directed to the "single_quiz_view" using the quiz id. So I wrote this ajax function (myFunction) below the above code.
function myFunction(quizId) {
// console.log("heyyyy");
// document.getElementById("demo").innerHTML = "Welcome"+quizId ;
$.ajax({
url: "/CW2/ASSWDCW2/cw2app/index.php/Quiz/loadQuiz/",
method: "POST",
}).done(function(data) {
alert("heyyy")
});
return false;
}
where Quiz is the controller name and loadQuiz is the function calling the "single_quiz_view"
//Quiz Controller
public function loadQuiz()
{
// $quizId = $this->uri->segment(3);
$this->load->view('quiz/single_quiz_view');
}
My problem is,
When I click on the "try it button", I get the alertBox inside the done function. I get the status code as 200 but still wont navigate to "single_quiz_view".Console wont give any errors.Please help
My page has a button that calls a Razor Page page handler to delete the associated item.
<a class="delete-item" data-id="#item.Id" asp-page-handler="delete" asp-route-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
I've defined a Javascript click handler. I need that handler to return false if the item should not be deleted.
$('.delete-item').on('click', function (e) {
var id = $(this).data('id');
var tr = $(this).closest('tr');
var td = tr.find('.item-description');
// Get number of lease details for this lease
$.ajax({
type: 'GET',
url: '?handler=LeaseDetailCount',
contentType: 'application/json',
dataType: 'json',
data: { 'leaseId': id },
})
.done(function (response) {
var description = 'Delete "' + description + '"? Are you sure? This cannot be undone.\r\n\r\n';
if (response.count == 0)
description += 'This lease has no lease details.'
else
description += 'WARNING: This lease has ' + response.count + ' lease detail(s).';
if (!confirm(description))
return false;
})
.fail(function (response) {
alert(response.responseText);
})
//.always(function (response) {
//});
}
The problem, of course, is that the AJAX call is asynchronous. And so it returns before my confirmation is displayed.
How can I get the code above to work as I want?
If you not wish to set asp-page-handler for the anchor tag, it is possible. As you mentioned
AJAX call is asynchronous
we can't predict which result come first, href navigation or onclick AJAX response
<a class="delete-item" data-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
In AJAX .done event, If the confirmation is OK page redirect to delete handler
window.location.href = "/?id=" + id + "&handler=delete";
.done(function (response) {
......
.......
if (!confirm(description))
return false;
else
window.location.href = "/?id=" + id + "&handler=delete";
})
Is there a way I could change the default ajax alert box? I currently have the code below, that deletes a user and reloads the current page. It works, but I would like to add some styling to the alert box that it triggers before the user is actually deleted.
function deleteUser(id) {
var action = confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
I tried changing the confirm to
function deleteUser(id) {
var action = bootstrap.confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
This displayed nothing.
You cannot style the custom confirmation box. It varies from browser to browser. If you want something custom you can build out one yourself using HTML and CSS. For example attach click events for yes button and for a no button and based on that you can make the delete
I'm working on a project with API calls. Basically, I need to be able to pass a parameter to a function with jQuery when a certain button is clicked.
I am working on a project that calls an API to display class buttons to a user.
Each button will be generated based on the presence of a classId, which is called in a jQuery file:
jQuery:
function getCourses() {
$.ajax({
url: apisource + "/courses",
dataType: "json"
}).done(function(data) {
let dataLength = Object.keys(data).length;
for (let i = 0; i < dataLength; i++) {
courseId = data["courses"][i].id; //this is the important part
nameOfClass = data["courses"][i].name;
let classButton = ('<button type=\'button\' class=\'classButton\' onclick=\'javascript:getStudentsInCourses(' + courseId + ');\'>' + nameOfClass + '</button>');
$('#classButtonContainer').append(classButton);
}
})
}
getCourses();
function getStudentsInCourses(currentCourseId) {
console.log("current course id: " + currentCourseId);
$.ajax({
url: apisource + "/course=" + currentCourseId + "/students",
dataType: "json"
}).done(function(data) {
console.log("here are the students");
console.log(data);
}}
What I want to do here is that when a user clicks on a class button, the courseId for that button becomes the "currentCourseId", and is able to be passed to getStudentsInCourses so that it can call the students for that course. I've been scouring the web for the proper way to pass that variable but no method has worked so far. Does anyone have any pointers for how to pass this variable?
So it should be something like this:
when a user clicks one of the classButtons, that button's courseId will pass to the "getStudentsInCourses" function as the "currentCourseId"
In Jquery you can use the click event to execute a logic.
Do not forget to call the function before the click event below.
//your functions
$('.classButtons').on('click', function(){
const id = $(this).attr('id');
//now call your function with the id
getStudentsInCourses(id);
});
If you have questions or misunderstood your request let me know =)
It seems to be working for me. Perhaps, it's your courseId variable that's causing an issue ? Are you sure it's not the same id ?
courseId = data["courses"][i].id;
function getCourses() {
for (let i = 0; i < 5; i++) {
let classButton = ('<button type=\'button\' class=\'classButton\' onclick=\'javascript:getStudentsInCourses(' + i + ');\'>Test ' + i + '</button>');
$('#classButtonContainer').append(classButton);
}
}
getCourses();
function getStudentsInCourses(currentCourseId) {
console.log("current course id: " + currentCourseId);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="classButtonContainer"></div>
I want to insert in my page an event that trigger when the window close or change except that in the case that has been triggered by a submit button of a particular submit which bring in an analogus page. I tried the follow but it doesn't work. (prova is the name of submit).
$(window).bind("unload", function (event) {
alert('1');
if (event.target.tagName != "prova") {
alert('2');
var postData = {
'chat_message': "I left"
};
$.ajax({
type: "POST",
dataType: "json",
url: base_url + "chat/ajax_add_message/" + chat_id + "/" + user_id,
data: postData,
success: function (data) {
get_messages();
}
});
}
});
Do you really have HTML element with tag "prova" ?
event.target.tagName != "prova"
Maybe you need to check className or id?