How to add dynamic javascript alert box in asp.net? - javascript

Please help me .I am new to asp.net .How can I write dynamic javascript in asp.net web forms ? What I want to do is as the following code .
The follow code is in button click event of server side ,written in c# . Please help me .
if(Email.send()){
//show javascript alert box
}else{
//show javascript alert box
}

Create a webmethod that you call via AJAX and pop the javascript alert based on the result of that function.
example (in your .aspx page):
function doSomething() {
$.ajax({
type: "POST",
url: "Do_Something.aspx/DoSomething",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
}
});
In Do_Something.aspx.cs:
[WebMethod]
public static string DoSomething()
{
if (Email.Send)
{
return "success";
}
return "not a success";
}

With asp.net, all server side code is going to run before the Web Page is sent to the end user, and then the result of that code is injected into the HTML/Javascript.
Also, when injecting server side code into javascript, you are required to do it within a string literal (quotes).
So, if you have in a javascript click handler:
if ("#Email.Send()") {
// stuff
} else {
// other stuff
}
The Email.Send() command will run, and the results of that command will be placed in the Html. If your Send function returned a boolean, which I am assuming it does, the Html returned to your end user would look like this:
if ("true") {
// stuff
} else {
...
I'm assuming this is not your desired outcome. The correct way to do this, is to trigger another command on your server via AJAX inside your click command, and use the result of that AJAX command for your logic. It would look like this:
function clickHandler() {
$.ajax({
type: "POST",
url: "UrlToYourServerSideAction",
data: {
WebParam1: "value",
WebParam2: "value"
},
success: function (response) {
if (response == "true") {
// code if Web Method returns true
} else {
// code if Web Method returns false
}
}
});
}

Related

The URL string changes after ajax call return

I have been struggling with a problem for some time. I cannot understand the reason as it happens in a specific case, not with the others.
I have a javascript function that calls a PHP script to upload a file to the server (standard code, have been using it and works perfectly normally).
function upload_picture(fieldID, success, error) {
var folderName;
switch (fieldID) {
case "pop_drawing":
folderName = "pop_dwg";
break;
case "pop_installation":
folderName = "pop_inst";
break;
case "pop_picture":
folderName = "pop_pict";
break;
}
var file_data = $('#' + fieldID).prop('files')[0];
var form_data = new FormData();
form_data.append('folder', folderName);
form_data.append('file', file_data);
$.ajax({
url: 'dbh/upload.php',
dataType: 'text',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
if (response.indexOf("yüklendi") > 0) {
success();
}
},
error: function (response) {
event.preventDefault();
console.log (response); // display success response from the PHP script
error(response);
}
});
}
The function is called from several points in the code and it works OK except one point. At this particular point when it returns it changes the page URL from
http://localhost/pop/#
to
http://localhost/pop/?pop_drawing=&pop_installation=&pop_picture=Compelis-Logo.jpg&pop_need_special_prod=Hay%C4%B1r&pop_need_application=Hay%C4%B1r&pop_order_made=Evet&pop_approval=4&pop_cost_visible=Hay%C4%B1r#
due to a reason I could not understand. This string in the URL line are some parameters on the web page where I press the button to call the function.
The code which call the function is:
function uploadPopPicture () {
if ($('#pop_picture_label').html() !== 'Seçili dosya yok...') {
upload_picture('pop_picture',
function(){
console.log('Görsel yüklendi...');
},
function(error){
console.log('Error:', error);
});
}
}
Same code (obviously with different parameters) is used elsewhere in the program and works OK.
Any ideas what I might be missing.
Many thanks in advance
A button's default behaviour is "submit". If you don't specify any particular behaviour then that's what it will do. So when clicked it will submit your form, regardless of any JavaScript.
Add the attribute type="button" to your button HTML and that will stop it from automatically submitting the form.

Execute Ajax call on user confirmation that should appear depending on a previous Ajax call

I'm dealing with a difficult problem concerning asynchronous calls:
A JQuery function executes on user click, it then calls for a php file to check is the user input will overlap with information already in the database.
If it does, the user then should be prompted for confirmation if he wants to proceed anyway or cancel, if he clicks ok, then it executes another call to write data in the database.
The structure I was thinking is something like
User clicks button:
Ajax -> Success: true or false.
If True -> User is prompted -> It overlaps, want to proceed?
If Yes -> Ajax -> Write stuff on database.
The problem is, I couldn't find a single solution that would let me do this.
Any help is appreciated!
Javascript
$.ajax({
type: "POST",
url: 'your_url.php',
data: your_data
})
.success(handleResponse);
function handleResponse(data) {
if (data.request_overide) {
if (confirm('There is an overlap... Proceed?')) {
data.force = true;
$.ajax({
type: "POST",
url: 'your_url.php',
data: your_data
})
.success(handleResponse);
}
} else {
alert('Successfully added!')
}
}
PHP - your_url.php
$duplicate = false;
//Check if duplicate
if(!$_POST['force']){
$duplicate = somecheck();
}
if(!$duplicate){
addData();
}
echo json_encode(['request_overide' => $duplicate]);
Method using jQuery.post():
/* check if the user input will overlap with information already in the database */
$.post('/path/to/check-database.php', dataObject, function(response) {
/* If it does - because JavaScript treats 0 as loosely equal to false (i.e. 0 == false) */
if(response != false) {
/* the user then should be prompted for confirmation if he wants to proceed anyway or cancel */
if(!confirm('It overlaps, want to proceed?')) { return false; } // cancels
}
/* Write stuff on database */
$.post('/path/to/update-database.php', dataObject);
});
Basically, you POST into your check PHP script and it returns either 1 (true) or 0 (false). If it's true, you confirm your user wants to continue. If they click cancel, it will exit the function. If they confirm or the script returns false, it will execute the second POST into your update PHP script.
$.ajax({
type: 'POST',
data: { input: 'someInput' },
success: function(response) {
if (response.confirmation == 1)
//Do prompt
if (promptisSuccessful) {
//Do a second Ajax call
}
}
});
Your php code should return a json response, something like
{confirmation:1} if validation or logic passes and {confirmation:0} if it fails.
Hope it helps

Binding table in MVC 4 after Ajax call

I have an HTML able, which I bind by using the following Action in MVC controller:
public ActionResult BindTable(int ? page)
{
int pageSize = 4;
int pageNumber = 0;
List<Users> _users = query.ToList();
return View(_users.ToPagedList(pageNumber, pageSize));
}
Below the table I have the following HTML:
<textarea class="form-control" style="resize:none;" rows="9" placeholder="Enter value here..." id="txtValue"></textarea>
<br />
<button style="float:right; width:100px;" type="button" onclick="CallFunction()" class="btn btn-primary">Update specific record</button>
The Javascript function responsible for calling the action is as following:
function CallFunction() {
if ($('#txtValue').val() !== '') {
$.ajax({
url: '/User/UpdateUser',
type: 'POST',
data: { txt: $('#txtValue').val() },
success: function (data) {
$('#txtValue').val('');
alert('User updated!');
},
error: function (error) {
alert('Error: ' + error);
}
});
}
And here is the Action responsible for updating the user:
public ActionResult UpdateUser(string txtValue)
{
var obj = db.Odsutnost.Find(Convert.ToInt32(1));
if(obj!=null)
{
obj.Text= txtValue;
obj.Changed = true;
db.SaveChanges();
return RedirectToAction("BindTable");
}
return RedirectToAction("BindTable");
}
Everything works fine. But the table doesn't updates once the changes have been made ( it doesn't binds ?? )...
Can someone help me with this ???
P.S. It binds if I refresh the website.. But I want it to bind without refreshing the website...
I created a BIND function with Javascript, but it still doesn't binds:
function Bind() {
$(document).ready(function () {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
});
}
You're not actually updating the page after receiving the AJAX response. This is your success function:
function (data) {
$('#txtValue').val('');
alert('User updated!');
}
So you empty an input and show an alert, but nowhere do you modify the table in any way.
Given that the ActionResult being returned is a redirect, JavaScript is likely to quietly ignore that. If you return data, you can write JavaScript to update the HTML with the new data. Or if you return a partial view (or even a page from which you can select specific content) then you can replace the table with the updated content from the server.
But basically you have to do something to update the content on the page.
In response to your edit:
You create a function:
function Bind() {
//...
}
But you don't call it anywhere. Maybe you mean to call it in the success callback?:
function (data) {
$('#txtValue').val('');
Bind();
alert('User updated!');
}
Additionally, however, that function doesn't actually do anything. For starters, all it does is set a document ready handler:
$(document).ready(function () {
//...
});
But the document is already loaded. That ready event isn't going to fire again. So perhaps you meant to just run the code immediately instead of at that event?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
});
}
But even then, you're still back to the original problem... You don't do anything with the response. This AJAX call doesn't even have a success callback, so nothing happens when it finishes. I guess you meant to add one?:
function Bind() {
var serviceURL = '/User/BindTable';
$.ajax({
type: "GET",
url: serviceURL,
contentType: "application/json; charset=utf-8",
success: function (data) {
// do something with the response here
}
});
}
What you do with the response is up to you. For example, if the response is a completely new HTML table then you can replace the existing one with the new one:
$('#someParentElement').html(data);
Though since you're not passing any data or doing anything more than a simple GET request, you might as well simplify the whole thing to just a call to .load(). Something like this:
$('#someParentElement').load('/User/BindTable');
(Basically just use this inside of your first success callback, so you don't need that whole Bind() function at all.)
That encapsulates the entire GET request of the second AJAX call you're making, as well as replaces the target element with the response from that request. (With the added benefit that if the request contains more markup than you want to use in that element, you can add jQuery selectors directly to the call to .load() to filter down to just what you want.)

Jquery ajax call in Cake PHP 3.0

Hi,
I'm trying to make a ajax request to the view A from the controller B like this :
In the view A :
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'B','action'=>'viewresult'));?>",
dataType: 'text',
async:false,
success: function(tab){
alert('success');
},
error: function (tab) {
alert('error');
}
});
}
In the controller B:
public function viewresult()
{
echo 'SUCCESS';
}
The problem is that in the 'response' of ajax, I've 'SUCCESS' but also the entire view A, I don't understand why...
I want only 'SUCCESS'...
Thanks in advance !
Detect if its ajax as per following code in cakephp way :
if($this->request->is('Ajax')) //Ajax Detection
{
$this->autoRender = false; // Set Render False
$this->response->body('Success');
return $this->response;
}
Check here for more detectors - http://book.cakephp.org/3.0/en/controllers/request-response.html#Cake\Network\Request::addDetector
You can also use $this->Url->build instead of including Router for creating links in view.
echo $this->Url->build(['action'=>'index']);
The easiest way to achieve it is adding die() at the end of your function so it prevents to load whole layout:
public function viewresult()
{
echo 'SUCCESS';
die;
}
OR
public function viewresult()
{
die('SUCCESS');
}
But more conventional way is using JSONView. Your action should look as follows:
public function viewresult()
{
$this->set('text', 'SUCCESS');
$this->set('_serialize', ['text']);
}
You also have to load RequestHandler component in initialize() method in your controller:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
You need to set allowed extensions for all routes connected later in routes.php:
Router::extensions('json', 'xml');
Now you can access your action adding extension .json at the end of it's URL, so you need to modify ajax call url:
url:"<?php echo Router::url(array('controller'=>'Main','action'=>'viewresult', '_ext' => 'json'));?>"
That's all, but keep in mind that this solution force you to handle JSON array in response. In this example output will be looks as follows:
{"text": "SUCCESS"}

Asp.net MVC 2 - Returned Json object not being picked up in javascript?

Update: I've removed the datatype="html" completely and hoping the return value will always get evaluated - but right now nothing happens.
I've also added the code that calls the "openModal" function. It is in the LogOn UserControl contained in the Site.Master. Hope this clears up a few things
It seems like from the Controller is not returning the json object back to the ajax caller, something is lost somewhere - i am never hitting that break point..it skips it entirely
I have a simple modal for logins, so i call the LogOn Action like this:
<div id="logonForm">
<% using (Ajax.BeginForm("LogOn", "Account", new AjaxOptions{UpdateTargetId = "logonForm"})) { %>
//my login form
<% } %>
</div>
And the Action looks like this:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
//success login
if (Request.IsAjaxRequest())
return Json(new { Url = Url.Action("Index", "Home") }, JsonRequestBehavior.AllowGet);
else
return RedirectToAction("Index", "Home");
}
At this point it retursthe new Json object with the Url to the User Control (in Site.Master), to the javascript here:
<script type="text/javascript">
function openModel() {
$.ajax({
type: "get",
url: '/Account/LogOn',
contentType: "application/x-www-form-urlencoded;charset=utf-8",
// async: true,
success: function (result) {
debugger;
if (typeof result == 'string') {
$.modal(result, {
closeHTML: "",
containerId: "login-container",
overlayClose: true
});
}
else if (result.Url) {
debugger;
window.location.href = result.Url;
}
}
});
}
</script>
<% if (Request.IsAuthenticated) { %>
Welcome <b><%: Page.User.Identity.Name %></b>!
<%: Html.ActionLink("Log Out", "LogOff", "Account") %>
<% } else { %>
Log In
<% } %>
...but the javacript never catches it..i cannot see whats in the "result", the screen renders an "{Url: /}" - just weird behavior
What am i missing? the debugger; break is triggered when i first click the link, but when i try to submit form, it goes thru the LogOn Controller - tries to return the json object, but never goes back to the javascript
Thanks much
JQuery will not treat the call as returning json, because you have told it the call is returning html. You need to change your dataType to json.
However it isn't clear where you expect openModel to be called from. The code as it is will use the Microsoft AJAX code and insert the returned data into the page, which is why you are seeing your json appear on the page.
You need to overwrite the submit click to call your custom jQuery ajax function. Right now it will use the Microsoft ajax. This is why your ajax function never gets called.
Do something like:
$('form').unbind('submit').submit(function(){
$.ajax({ type:'post', url: '/Account/LogOn', data: $(this).serialize(),
success: function(){
if (result.Url)
window.location.href = result.Url;
}
});
});
dataType: "html", should be be dataType: "json",, and this should solve the problem.
Well jQuery will never trigger the success callback, since you specified dataType: "html",, so it will wait for an text/html response, but you're sending JSON.
You need to use "json" as the dataType.
See: http://api.jquery.com/jQuery.ajax/

Categories