dialog does not come up after uploading asp.net mvc 2 - asp.net-mvc-2

my dialog does not popup after successfull upload? the upload works fine but $("#dialog-confirm").dialog does not work?
<h2>
upload Data</h2>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="../../Scripts/jqueryform.js" type="text/javascript"></script>
<script src="../../Scripts/jblock.js" type="text/javascript"></script>
<script src="../../Content/jquery-ui-1.8.12.custom/js/jquery-ui-1.8.12.custom.min.js"
type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.8.12.custom/css/ui-lightness/jquery-ui-1.8.12.custom.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$("#ajaxUploadForm").block({ message: '<h1><img src="/Content/busy.gif" /> uploading file...</h1>' });
},
success: function (result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
//alert(result.message);
//does not popup??
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Ok":
function () {
alert('ok');
$(this).dialog("close");
}
,
Cancel: function () {
$(this).dialog("close");
}
}
});
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Home")%>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file</legend>
<label>
File to upload:
<input type="file" name="file" />(100MB max size)</label>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
</form>
public FileUploadJsonResult AjaxUpload(HttpPostedFileBase file)
{
// TODO: Add your business logic here and/or save the file
System.Threading.Thread.Sleep(2000); // Simulate a long running upload
// Return JSON
return new FileUploadJsonResult { Data = new { message = string.Format("{0} uploaded successfully.", System.IO.Path.GetFileName(file.FileName)) } };
}

I see that you are using the jquery.form plugin for AJAXifying the form and returning JSON from your controller action. Here's what the documentation says about this scenario:
Since it is not possible to upload
files using the browser's
XMLHttpRequest object, the Form Plugin
uses a hidden iframe element to help
with the task. This is a common
technique, but it has inherent
limitations. The iframe element is
used as the target of the form's
submit operation which means that the
server response is written to the
iframe. This is fine if the response
type is HTML or XML, but doesn't work
as well if the response type is script
or JSON, both of which often contain
characters that need to be repesented
using entity references when found in
HTML markup.
To account for the challenges of
script and JSON responses, the Form
Plugin allows these responses to be
embedded in a textarea element and it
is recommended that you do so for
these response types when used in
conjuction with file uploads.
So for this to work the response from the server needs to look like this:
<textarea>{ message: 'file uploaded successfully' }</textarea>
Is it what this custom FileUploadJsonResult is doing in your controller action?

Related

Passing form data to the JSP without passing to the server

html>
<head>
<title>Landing</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<form name="testForm" action="move.jsp">
<label><h1>Enter the data <h1/></label><br/>
<input type="text" name="DATA"><br/>
<input type="submit">
</form>
<% out.println(DATA) %> <!-- WRONG!! -->
</body>
</html>
Please ignore the action part
I am working on a spring mvc project and I have a problem. What I want is that, when the user clicks submit, we should not leave the page, we should just stay. But the values submitted would be used as a parameter to a function in the same page. Here, let's just say I want to print it, and that is the part that is wrongly entered.
What should I do to accomplish this? Please help
You can use ajax here when your submit button is clicked call this function and then using this call your ajax passed the value from your input to your server and then at your server side perform operation which you needed to do and then the result back to ajax .
Your form :
<form name="testForm" action="move.jsp">
<label><h1>Enter the data <h1/></label><br/>
<input type="text" name="DATA"><br/>
<input type="button" onclick="submit_values()">
<!--^^added this-->
</form>
<div id="result"><!--here data will come back--></div>
Then on click of your button submit_values() function will get called . i.e :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
function submit_values() {
//get input value
var values = $("input[name='DATA']").val();
console.log(values);
$.ajax({
type: 'POST',
data: {
values: values//passing to server
},
url: "Your_server_url",
success: function(data) {
alert(data);//this will display whatever server will return
$("#result").html(data);//add response back to show
}
});
}
</script>
Then at your server-side do like below :
String data =request.getParameter("values");//get value
String send_back = something(data);//call your function
out.println("DATA BACK"+send_back );//this will go back to ajax

Meteor server api using iron router returns HTML not the response

I have a simple Meteor app just the basic meteor create test. I want to be able to route traffic to the "/" directory to a template.
I want to be able to route data from a facebook web-hook to a simple js response.
My issue is that when I fire the web-hook URL using postman it returns HTML and not my response.
I've tried many different options for other posts I have read but now have the most basic version to just get it working.
Here is the code I've used
main.html
<head>
<title>test</title>
</head>
<body>
</body>
<template name="home">
<form class="new-message">
<input type="text" name="message" placeholder="Testing">
</form>
</template>
main.js:
import { Meteor } from 'meteor/meteor';
import { Router } from 'meteor/iron:router';
import { Template } from 'meteor/templating';
import './main.html';
Router.route('/', function () {
this.render('home');
});
Router.route('/webhooks/facebook', function() {
var request = this.request;
var response = this.response;
response.end('webhook was called');
}, {
where: 'server'
});
All other files are exactly how they are created with meteor create.
I'm on Meteor version 1.8.1
I'm using postman to test the web-hook this is the created GET URL:
https://------.ngrok.io/webhooks/facebook?hub.verify_token=mytoken&hub.challenge=1234567&hub.mode=subscribe
code omitted to keep ngrok from getting slammed.
This is the response I'm getting:
<html>
<head>
<link rel="stylesheet" type="text/css" class="__meteor-css__"
href="/merged-stylesheets.css?hash=6b1f9f6fb78291ae58da8ec4f36476931155453c">
<title>simplechat</title>
</head>
<body>
<script type="text/javascript">
__meteor_runtime_config__ = JSON.parse(decodeURIComponent("%7B%22meteorRelease%22%3A%22METEOR%401.8.1%22%2C%22meteorEnv%22%3A%7B%22NODE_ENV%22%3A%22development%22%2C%22TEST_METADATA%22%3A%22%7B%7D%22%7D%2C%22PUBLIC_SETTINGS%22%3A%7B%7D%2C%22ROOT_URL%22%3A%22http%3A%2F%2Flocalhost%3A3000%2F%22%2C%22ROOT_URL_PATH_PREFIX%22%3A%22%22%2C%22autoupdate%22%3A%7B%22versions%22%3A%7B%22web.browser%22%3A%7B%22version%22%3A%22b22f1ad86c0a904c992885256b7de72ed2863e1d%22%2C%22versionRefreshable%22%3A%22a580e09175421ec6994fc6da61a0413f3a15d2b1%22%2C%22versionNonRefreshable%22%3A%22fc4ded0006de942fe57524f94d500abeb4569d6f%22%7D%2C%22web.browser.legacy%22%3A%7B%22version%22%3A%222571a76ffc344fbc5b40ade303255cbbc59e2682%22%2C%22versionRefreshable%22%3A%22a580e09175421ec6994fc6da61a0413f3a15d2b1%22%2C%22versionNonRefreshable%22%3A%22dc1e886b7786e303655c010220e9f502e82dcf1c%22%7D%7D%2C%22autoupdateVersion%22%3Anull%2C%22autoupdateVersionRefreshable%22%3Anull%2C%22autoupdateVersionCordova%22%3Anull%2C%22appId%22%3A%22zqskgg1xifoj.hlnqbjmcma6f%22%7D%2C%22appId%22%3A%22zqskgg1xifoj.hlnqbjmcma6f%22%2C%22isModern%22%3Afalse%7D"))
</script>
<script type="text/javascript" src="/packages/meteor.js?hash=857dafb4b9dff17e29ed8498a22ea5b1a3d6b41d"></script>
<script type="text/javascript" src="/packages/meteor-base.js?hash=29010b127daf4ebacaaf9db9b8a61487e57d7d86">
</script>
<script type="text/javascript" src="/packages/mobile-experience.js?hash=2751f9ec11102d1106042c462b340c3fcfcb1990">
</script>
<script type="text/javascript" src="/packages/modules-runtime.js?hash=d3c3e5d67c95f97a60888bda7373292efad3be5e">
</script>
<script type="text/javascript" src="/packages/modules.js?hash=e8b7455d5562fec1444a3c6882cdc6639055cfca"></script>
<script type="text/javascript" src="/packages/modern-browsers.js?
<script type="text/javascript" src="/packages/autoupdate.js?hash=6d56c0f3a885390c688b4f3f893d96d1280fd0ee"></script>
---- Cut out all of the other script calls to keep this short -----
<script type="text/javascript" src="/app/global-imports.js?hash=1f8a1ae2e343994912f72f1dc6eec1ca7df24cae"></script>
<script type="text/javascript" src="/app/app.js?hash=70cfa37cd2f85e533f69d7312d02ef8984eae01a"></script>
</body>
</html>
So basically it returns HTML.
I'm sure I'm missing something simple.
Thanks in advance for you help. Usually I wait till I have exhausted all other options before posting here. And I'm sure I have tried every other example given here on StackOverflow.
My desired result is simple to just return a HTTP response "webhook was called" instead of the HTML garbage.
You could use somethings like this :
Router.map(function(){
this.route("routeName", {path: "/url/:param1/:optionalParam?,
where: "server",
action: function(){
var param = this.params.param1;
this.response.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
//authenticate call and decrypt body
if (this.request.method == 'POST') {
//do something
}
if (this.request.method == 'GET') {
//do something
}
}
});
this.route("abc", {path: "/api/get/user/activity/:temp1",
where: "server",
action: function(){
//proceed as above
}
});
});
For help, read through https://iron-meteor.github.io/iron-router/#server-routing
The router file should be saved inside the server folder (for server-side routes)
Haven't used iron route in a long time but from what I remember you want to change your server side route to the following as it is for restful routes.
Router.route('/webhooks/facebook', { where: 'server' })
.get(function () {
// GET
})
.post(function () {
// POST
})
.put(function () {
// PUT
})
For others who have been struggling getting both server and client routes to work on the same Meteor app here is the solution.
Iron routers newest version requires all server side routes to be on the server side and you must fire them from the startup.
All client routes are added on the client side and included in the main.js on the client side.
My simple test was this:
meteor create test
Then in clients/main.html replace the current code and add a simple template as follows:
<head>
<title>newroutetest</title>
</head>
<body>
</body>
<template name="home">
<h1>Home</h1>
</template>
Then in the client/main.js add your client routes as follows:
import { Template } from 'meteor/templating';
import './main.html';
Router.route('/', {
template: 'home'
});
Now we setup the server side route in the file server/main.js you add the route in the startup section as follows:
import { Meteor } from 'meteor/meteor';
Meteor.startup(() => {
Router.route('/webhook', function () {
var req = this.request;
var res = this.response;
res.end('hello from the server\n');
}, {where: 'server'});
});
That's It
I hope this helps others who have been struggling with this.

Ajax form submit, validate and return success or fail

Searched and browsed the forum and tried many examples of ajax and form submission but can't get anything close to work for what I am trying to achieve. I must admit I've been going in circles for days with this and need someone with a fresh pair of eyes.
I have 2 pages:
page1.php
page2.php
Using Google jquery/1.9.0/jquery.js and developing this locally.
page1.php is as follows (I've omitted the head script and body/html tags for clarity)
$(document).ready(function() {
$('#theForm').submit(function(){
$.ajax({
type: "POST",
url: "page2.php",
data: 'html',
success: function(html){
if(html == 'success'){
$('#address').fadeOut('slow');
$('#done').fadeIn('slow');
}else if(html == 'fail'){
alert('fail');
}
}
});
return false;
});
});
<div id="address">
<form action="page2.php" method="post" name="theForm">
<input name="checkname" type="text" id="checkname">
<input name="Proceed" type="submit" id="submit" value="Next Page" />
</form>
</div>
<div id="done">
That Worked!
</div>
Page2.php
Has a mysql query that checks the database for the checkname and echoes 'success' or ' fail' depending upon the result. The query runs fine and is not showing any error.
When the form is submitted page2.php loads and just shows 'success' in the browser.
Firebug also shows success under both response and html. There are no errors within firebug.
I basically want page1.php to stay and for the #address div to hide and the #done div to show when success is passed from page2.php
Hope someone can help.
Update
I tried this test page:
ajaxone.php
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#theForm').submit(function(){
$.ajax({
type: "POST",
url: "ajaxtwo.php",
data: 'html',
success: function(html){
if(html == 'success'){
$('#address').fadeOut('slow');
$('#payment').fadeIn('slow');
alert('ok');
}else if(html == 'fail'){
alert('fail');
}
}
});
return false;
});
});
</script>
<style type="text/css">
#payment{
visibility:hidden;
}
</style>
<div id="address">
<form action="ajaxtwo.php" method="post" name="theForm" id="theForm">
<p>
<input name="name" type="text" id="name">
</p>
<p>
<input type="submit" name="submit" value="submit">
</p>
</form></div>
<div id="payment">Name is correct</div>
ajaxtwo.php
print_r($_POST);
if($_POST['name'] == 'rob'){
echo 'success';
}else{
echo 'fail';
}
Using the above firebug shows the following error:
Array ( )
Undefined index: name
fail
However, when I remove the ajax call the submit works and the data is passed.
So, am I right to assume that if you do not specify the form variables within the ajax call nothing is posted to the next page?
Update 2
Sorry I'm answering myself here.
It does appear that you need to specify the form data to send within the ajax call.
I've just added:
$('#theForm').serialize();
within the ajax call and now the form submits without an error.
However, this still goes to ajaxtwo.php and does not show the success or fail on the ajaxone.php page.
So my next stage is to get the success or fail to show on ajaxone.php
You need to add id="theForm" in the form tag itself.
Example:
<form action="page2.php" method="post" id="theForm" name="theForm">
I would say, add a and then make jq read the output and then redirect accordingly, or use php to redict based on $success_fail result.

When i select CheckBox().I need to update its value into DB - MVC2,AJAx,JQuery

Please find the code which i tried to update the DB using MVC2.But unable to update
View Page with Ajax Code
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$('#cbID').click(function(){
$.ajax({ url: 'Home/About',
type: 'POST',
data: { checkbox: $('#cbID').attr('checked') },
success: function(o) { alert('saved'); }
});
</script>
<div class="bgDiv">
<input id="cbID" type="checkbox" name="SelectedObject" value="cbValue" />
Controller page code
public ActionResult About(string str)
{
AboutModels ObjAM = new AboutModels();//model class name
polloptions = ObjAM.dbValue(str);//call the model function to udate the table
return View();
}
Please advice
you should either declare your event handler in ready function or declare it with live or delegate methods like
<script language="javascript" type="text/javascript">
$(function(){
$('#cbID').click(function(){
$.ajax({ url: 'Home/About',
type: 'POST',
data: { checkbox: $('#cbID').attr('checked') },
success: function(o) { alert('saved'); }
});
});
});
</script>
the problem is that your script is running before the required checkbox is rendered so putting it in ready will wait until document is ready or live will bind it on document level where the event will reach through propogation

MVC2 Client side validation within Jquery modal dialog

Using MVC2 I currently have a view creating a jquery dialog box containing an Edit partial view. On submit I am looking for it to perform client side validation on the Email class which has a required data annotation attribute for email address. Server side validation works fine but I want the user to have to fix the error in the modal dialog.
Below is the code
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm())
<div>
<label for="EmailAddress">
Email Address :
</label>
<%= Html.TextBoxFor(model => model.Email.EmailAddress)%>
<%= Html.ValidationMessageFor(model => model.Email.EmailAddress)%>
</div>
Scripts I am loading up are
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.3.2.min.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jqueryUI/js/jquery-ui-1.7.2.custom.min.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Splitter/splitter-1.5.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Scripts/Start.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/Scripts/extended/ExtendedControls.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery.validate.js")%>"></script>
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/MicrosoftMvcJQueryValidation.js")%>"></script>
Looking at the html generated I am not getting any of the JSON data generated for the client side validation to work.
Any solutions gladly appreciated. S
I strongly recommend you to use jquery validation script.
jquery.validate.js has all the features for client-side validation within a jquery dialog.
First of all, add the jquery.validate.js to your Site.Master :
<script src="/Scripts/Using/jquery.validate.js" type="text/javascript"></script>
and then write your script something like that :
<script type="text/javascript">
var createLinkObj;
$(function () {
$('#mydialog').dialog({
autoOpen: false,
width: 500,
modal: true,
buttons: {
"OK": function () {
$("#myForm").validate({
rules: {
Name: {
required: true
},
Email: {
required: true,
email: true
}
},
messages: {
Name: " * ",
Email: {
required: " * ",
email: " Invalid e-mail."
}
});
$("#myForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".mylink").click(function () {
//change the title of the dialog
createLinkObj = $(this);
var dialogDiv = $('#mydialog');
var viewUrl = createLinkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
dialogDiv.dialog('open');
});
return false;
});
});
</script>
As you can see when I click the mylink, mydialog appears and before submitting the myForm, I validated the myForm elements namely Name and Email.
Think that your form only contains Name and Email and then you can validate these elments by using jquery validate script.