jquery .ajax's .done function get done on alert only - javascript

This seems a bit strange and i cant get a hold of the situation, apparently i used jquery's .ajax() function to process some script to get some data from the database. The script works fine and data gets returned as accordingly:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
$("#error2").html(msg);
});
After the scripts process, it is suppose to populate the data echoed in the script to the div i mentioned, but this does not happen. However, if i write an alert statement before the div population, the div gets populated. meaning:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
alert(msg);
$("#error2").html(msg);
});
I dont seem to get why this is happening and what I can do to resolve this.
P.S. I have done this before, and this was working correctly before

Is it possible #error2 is not on the page yet?, so the alert gives it time? try putting the ajax call in
$(function(){
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
}).done(function( msg ){
$("#error2").html(msg);
});
});
Another thing you can try for reference is using the success callback
$.post("getevaluationdata.php",{evaluation_ID:value},function(msg){
$("#error2").html(msg);
});

Related

If statement in jQuery and HTML?

I m running the following script with success : it updates the text every 3s
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
window.setInterval(function() {
loadNewText()
}, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
$(report).replaceWith(data)
}
});
}
});
</script>
I want to change the function in HTML to run 'loadNewText()' only if there's changes in certain variable in Python code !
I've put the variables in python route :
#app.route('/console-output')
def console_output():
fileHandle = open("console_output.txt", "r")
lineList = fileHandle.readlines()
fileHandle.close()
last= lineList[len(lineList)-1]
with open('console_output.txt', 'r') as r:
co =r.read()
return render_template("console-output.html",console_output_msg=console_output_msg, last=last, co=co)
and write the following code in HTML :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(function() {
if (last != console_output_msg) {
loadNewText();
}
function loadNewText() {
$.ajax({
url: "/update_text",
type: "POST",
dataType: "json",
success: function(data) {
$(new_text).replaceWith(data)
}
});
}
});
</script>
This method is not working ! I don't have a big experience with Javascript! I don't know if I m not calling the variables (last, console_output_msg) the right way or my function is not valide !
If there's any way to correct it or any other suggestion to call 'loadNewText()' when changes happens in python code !
Thanks!
There are 2 popular ways to update the text when there is a change in Python:
Long polling
Using setInterval() function to trigger an ajax call to the server to check if there are any changes.
WebSocket
Implement a WebSocket connection between the server and browser. Receive the message sent from the server.
Link for implement WebSocket in Python.
https://websockets.readthedocs.io/en/8.1/intro.html
You can't access server variables on the client.
You could save the previous output in a JavaScript variable, and only update the DOM if it has changed. You need to put the if statement inside the loadNewText() function, after it has received the response, so it can compare it.
This won't skip the AJAX call, but it will avoid refreshing the page when nothing has changed.
$(function() {
let last_output;
window.setInterval(loadNewText, 3000)
function loadNewText() {
$.ajax({
url: "/update_report",
type: "POST",
dataType: "json",
success: function(data) {
if (data != last_output) {
$(report).replaceWith(data);
last_output = data;
}
}
});
}
});

How to put ajax request inside function and call it when necessary?

I have an ajax request:
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
I want to be able to put this inside a function that waits for me to trigger it with a return call. I am not exactly sure how to word it, I am new to javascript and jquery. But basically, I want to trigger this ajax call with various different button clicks and instead of having to put the ajax call inside every button click event, I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
Heres an example of a click event Id like to call the ajax request function with. Thanks!
$(function() {
$(".task-listing").click(function() {
//Call Ajax function here.
});
});
Callbacks are well-suited for this scenario. You can encapsulate your ajax call in a callback function.
function apiCall() {
$.ajax({
type: 'POST',
url: '/get-result.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
} }); };
}
You can now hook apiCall()method as a callback to button click.
$(function() {
$(".task-listing").click(apiCall);
});
By doing this you will able to achieve this.
I want to put it in a stand alone function so if I ever update it later I dont have to change it 5 times.
EDIT:
Note:
This is lead to start, you can alter this according to your requirement.
Is this not working for you? ↓↓
$(function() {
$(".task-listing").click(function() {
let pid = $(this).attr("id"); //get any other value which you want to pass in function, say url
someFunction(pid); // pass any other parameters, eg- someFunction(pid, url)
});
});
function someFunction(pid){ // someFunction(pid, url)
$.ajax({
type: 'POST',
url: '/get-result.php', // url: url
dataType: 'json',
data: 'pid=' + pid,
success: function(response) {
$(".reviewee-fname").append(response['fname']);
$(".reviewee-lname").append(response['lname']);
}
});
}

Ajax success and laravel

I'm currently working on a project using Laravel platform.
I'm trying to delete data from a model asynchronously using ajax. And when all is done my data should be removed from the table. My code runs perfectly, data are being removed from my database , yet "tr" elements arent really faded or removed. Here is my code :
ajax sucess not really working.
$(document).on('click', '.btn-remove-interview' , function() {
var id = $(this).attr('data-interview-id');
$.ajax({
url: './manage/interviews/destroy/'+id ,
type: 'post',
dataType: 'json',
data: id,
success: function (data) {
$(this).parents("tr").remove();
}
});
});
Use
$(this).closest('tr').remove();
Instead of
$(this).parents("tr").remove();
The problem is that the success function callback within your ajax request no long refers to the button when you use this. You need to get an explicit variable to the button if you want to use it.
$(document).on('click', '.btn-remove-interview' , function() {
// Get this button as a variable so we can use it later
var el = $(this);
var id = $(this).attr('data-interview-id');
$.ajax({
url: './manage/interviews/destroy/'+id ,
type: 'post',
dataType: 'json',
data: id,
success: function (data) {
$(el).parents("tr").remove();
}
});
});
Solution was by removing dataType json . My function doesnt return any data .

Sending the body of a page to another server?

Is it possible to send the body of a page (i.e. all of the HTML code/DOM) from a page on one server to another and then receive a response? The method used doesn't really matter, but I do have access to jQuery functions if that helps.
You could do this by sending...
$("html").html();
...in an ajax call:
var data = $("html").html();
$.ajax({
url: "/echo/json/",
data: data,
type: "POST"
}).done(function(res) {
console.log(res);
});
Working jsFiddle: http://jsfiddle.net/brandonscript/p5zEW/
(See console for body output).
Something like this should work:
$.get( "somePage.html",
function( pageData ) {
$.post("targetPage.php", pageData, function( data ) {
alert("Done!");
},
"html"
);
});

load view using ajax symfony2

I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)

Categories

Resources