How to call a DAO method through a javascript function? [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 5 years ago.
I'm writing a jquery code and calling a JavaScript function through it on a jsp page.
This is the jquery function
$(function () {
$('#defaultCountdown').countdown({until: $.countdown('//SomeTime'),onExpiry: liftOff});
});
liftOff is a javascript method which is called after the specified time expires.
This is the JavaScript function
<script>
function liftOff() {
alert("Before Delete");
<% DAO_Object.deleteRecord(ID);%>
alert("After Delete");
}
</script>
Now here the problem is, the line <% DAO_Object.deleteRecord(ID);%> is getting executed before the function call and the record from database is getting deleted. The alert statements are executing correctly AFTER the function call.
Am i calling the deleteRecord method incorrectly?

You are mixing your server-side JSP logic with your client-side JavaScript logic.
Everything between <% %> runs on your servlet when it's processing the request, so the record is already deleted by the time you get the response in the browser. If you look at the HTML/JS you are receiving in the browser using Chrome DevTools or similar tool, you will see that there is nothing between those alert(...) calls.
Your solution here is to setup a route that handles the deleteRecord() on the server-side, and call it via AJAX in your liftOff() method. So liftOff() would look something like this:
// assuming `id` is a string here
function liftOff(id) {
alert("Before Delete");
// You'll have to setup this endpoint to run
// your `DAO_Object.deleteRecord(ID);` code
// in your JSP code.
$.get("/delete/my/record/" + id, {
error: function(e){
// some kind of error occurred in making the request
},
success: function(resp){
// `resp` is the response from the server
alert("After Delete");
}
});
}

Related

Calling C# Function from ASP.NET View [duplicate]

This question already has answers here:
How to call a C# function from JavaScript?
(7 answers)
How to Call Controller Actions using JQuery in ASP.NET MVC
(5 answers)
Closed 4 years ago.
I have an ASP.Net Entity Framework view where I have multiple drop-down lists. Once a user changes an item in this list, I need to call a c# method which is passed the values in all of the dropdown lists to check whether their values overlap.
Currently I have:
#Html.DropDownListFor(model => model.Periods[i].StartTime, new SelectList(Model.DateTimeList, Model.Periods[i].StartTime), new {#class = "form-control", onchange = "dropdownChange()" })
which called a method called dropdownChange():
<script>
function dropdownChange() {
#{
var overlapping = PeriodController.ConfigureViewModel.IsOverLapping(Model);
}
console.log("here");
}
</script>
This method is found by the view but doesn't go into my c# code as I have tested by putting in javascript code and it is run. e.g. the console.log appears but doesnt call the c# code.
Either a solution to this or a more sophisticated way to call a c# method every time a dropdownlist is changed.
Added Ajax Method:
$.ajax({
type: "POST",
data: { 'Model': Model },
success: function(isOverLapping) {
overLappping = isOverLapping;
console.log(1);
},
error: function() {
console.log(2);
}
});
One line answer: MVC doesn't work like that.
Longer answer: You can't access the server-side code directly from the browser like that. The most common solution is to use something called AJAX to call the C# function on the server. You then need to write code in the View to handle the response from the server. Have a look at this question and this answer: https://stackoverflow.com/a/16186212/5173105

What's wrong with my JSON.parse and why's the code not executed in order of appearance? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm importing some data with PHP, which gets data from an SQL database. I'm using AJAX to import the data from the PHP to Javascript. The PHP code works fine and results in "2", but something's wrong with my Javascript code:
<script>
$.getJSON("Kategorie1.php", function (data) {
window.nrFragen = JSON.parse(data);
window.alert(data)
});
window.alert(window.nrFragen);
</script>
If I run it, it first runs window.alert(window.nrFragen) which alerts undefined and then window.alert(data), which alerts "2", as it should.
Why does it first run the window.alert(window.nrFragen), even though it's written after window.alert(data)? And, why isn't window.nrFragen = JSON.parse(data); working?
$.getJSON is async.
$.getJSON("Kategorie1.php", function (data) {
//this will be called only after request completion
window.nrFragen = JSON.parse(data);
window.alert(data)
});
//this will be called immediately after $.getJSON, it won't wait for request completion
window.alert(window.nrFragen);

How can i prematurely close an ajax call from php? [duplicate]

This question already has answers here:
How do I close a connection early?
(20 answers)
Closed 8 years ago.
okay so,
[browser] ==> makes AJAX call to webserver running php
i have the following php code,
<?php
//Process Ajax request
//return success code to browser
//continue with other php code
?>
How exactly can i achieve the second part i.e "return success code to browser"? and continue with processing php code.
put **async:false** in ajax call so your code will execute synchronously means until you don't get success or failure from ajax return rest of code will not execute .. do like following
// add here jquery file
<script>
$.ajax({
url : "abc.com/page",
type: "POST",
data: {},
async:false
success : function(data)
{
//you can use data here
}
});
</script>
//you can write here php code
i think it can be done like follow
//initial php code
call_function();
echo json_encode(array('success'=>true));
//other php code
call_function(); //etc
or you can split the ajax call in 2 parts.. in 1st part it will get the status so echo json_encode() will be executed and call ends and in success call back of ajax make 2nd call which will execute the remaining code!

Variable undefined although correctly assigned I think [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a simple script to get a PHP session user id into a javascript file. Yet when I try to simply alert the user id it says undefined?
As shown in code I have tried with simple alert to check the data coming back from the script and it is correct.
var user_id;
$.get( "/ajax/actions/getUserId.php", function( data ) {
// alert(data); <-- this works correctly
var user_id = data;
});
alert(user_id);
Is there a better way to do this?
The PHP file accessed (getUserId.php) is simply:
session_start();
echo $_SESSION[user_id];
Ajax is asynchronous, so the last alert will be executed before the callback function of ajax is called.
You should use:
$.get( "/ajax/actions/getUserId.php", function( data ) {
var user_id = data;
alert(user_id);
});
Ajax is asynchronous by default.
In your snippet the code goes through the following steps:
Define variable called user_id in the global lexical scope
Make GET ajax request to /ajax/actions/getUserId.php
Alert the value of the variable user_id which is undefined (by default, you haven't set it any value).
At given point the ajax request is successfully completed, your callback gets invoked so:
You define new variable called user_id, in the lexical scope of your callback

How to get data out of $.post [duplicate]

This question already has answers here:
getting a response from $.post
(2 answers)
Closed 9 years ago.
I want geting data out of jQuery podt, How can do it?
nat="";
$.post("random_unique", function(data){
nat = data;
});
alert(nat); //--> Nothing.
jQuery calls are asynchronous, in that you can execute the remainder if your script while the data is still loading. Perform your tasks in the callback of your $.post().
nat="";
$.post("random_unique", function(data){
nat = data;
alert(nat); //--> Something!
});
P.S. don't use alert() to debug code; use console.log(). If you receive a JSON response (or when you get into error handling) often times you'll be working with objects, which don't alert out.

Categories

Resources