asp.net mvc how to save data from jquery control - javascript

I am using the TinyMCE control in a MVC page, and now I want to save the content of the control (hopefully with ajax so the page is not rendered again)... I have some javascript that looks like this:
mysave = function() {
var ed = tinyMCE.get('content');
// Do you ajax call here, window.setTimeout fakes ajax call
ed.setProgressState(1); // Show progress
window.setTimeout(function() {
ed.setProgressState(0); // Hide progress
alert(ed.getContent());
}, 3000);
};
What is the best way to pass the content back to the controller, save it, and return back to the same page?

well, use jQuery.ajax. http://docs.jquery.com/Ajax. I suggest you to use POST request so you can transfer arbitrary long texts.
How do you plan to save the text? Do you use any database engine? we need more information.
$.ajax({
url: "/controller/savetext",
cache: false,
type: "POST",
data: { text: ed.getContent() },
success: function(msg) {
alert("text saved!");
},
error: function(request, status, error) {
alert("an error occurred: " + error);
}
})
and on server side something like this:
string text = Request.Form["text"]

Related

How to send multiple variables from a HTML web page to a python script without form submissions

This is going to be a strange one if I'm honest so please bare with me.
Im currently working on a project that requires me to call python scripts that are part of a webserver that is running a HTML webpage from the page itself i.e You move a slider on the webpage and it calls the python script and passes the value of the slider and an ID value that the script requires to pass the value to its relevant end point. In this case its a monitor ID and the slider value is the brightness value that the brightness must be set to.
Currently I have achieved this with a form submission action but I don't want the webpage to reset once a new value is sent and so JavaScript is my next best option using Ajax requests and while I have made some progress I am basically a noob with web development and have hit a brick wall.
Here is the script I have attempted and the python script that it calls.
<script>
slider.oninput = function (event, ui)
{
var slider_val=event.target.id;
console.log(slider_val);
$( "#"+slider_val ).val( ui.value );
$( "#amount_"+slider_val ).val( $( "#"+slider_val ).slider( "value" ) );
changeBrilliance();
}
function changeBrilliance(value, monid)
{
$.ajax({
type: "POST",
url: "/brilliancechange",
data: { mydata: value, mon: monid }
});
}
</script>
Python:
#app.route('/brilliancechange', methods=['POST'])
def brillchange():
userinput = request.form['mydata']
selectedMon = request.form['mon']
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
DATA = "A6" + selectedMon + "0000000401C0"
DATA += hex(int(userinput)).lstrip("0x")
check = checksum(bytes.fromhex(DATA))
DATA += hex(int(check)).lstrip("0x")
dataarray = hextobyte(DATA)
s.sendall(dataarray)
s.close()
What should the javascript look like if i want to call this method with a different ID and value each time without it reloading the webpage everytime?
It looks like changeBrilliance() accepts two parameters but when called nothing is getting passed. I'm not too familiar with the Python framework being used, but as long as it accepts content-type: application/json in POST body you could do:
// not totally sure which value/id combo you need but just pass the necessary ones here
changeBrilliance(slider_val, ui);
function changeBrilliance(value, monid)
{
var myObj = { 'myData': value, 'mon': monid };
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
});
}
Then if you want something in the browser to change, you'll have to callback on done if successful or fail if something goes wrong, and always callback for some behavior that should always happen:
$.ajax({
type: "POST",
url: "/brilliancechange",
contentType: "application/json",
data: JSON.stringify(myObj)
}).done(function(data) {
// do something
}).fail(function(jqXHR, textStatus, err) {
// handle error
}).always(function(data) {
// always callback
});

Jsonresult is failing with parameter in my Ajax Call. Why is it happening?

That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.

Mutually exclusive submits

I have a javascript which on a "submit" event does the following ajax call(which in turn triggers a python script),my problem now is that "when one submit event is going on if anyone else clicks on
the submit button this ajax call should notify that a submission is in progress" ,has anyone ran into this problem?(is there a name?) ,how do fix this problem?
Please suggest..
$("#main_form").submit(function(event) {
.....................
$.ajax({
dataType: "json",
type: "POST",
contentType: "application/json",//note the contentType definition
url: "scripts/cherrypick.py",
data: JSON.stringify(data_cp),
//data: data_cp,
error : function (xhr, ajaxOptions, thrownError){
console.log("cherypick fail");
console.log(response);
console.log(response['returnArray']);
alert(xhr.status);
alert(thrownError);
},
success: function(response){
console.log("cherypick sucess");
console.log(response);
console.log(response['returnArray']);
var return_array = response['returnArray'];
console.log(return_array['faillist'].length);
console.log(return_array['picklist'].length);
for (var i = 0; i < ip_gerrits.length; ) {
for (var j = 0; j < return_array['faillist'].length; ) {
if (ip_gerrits[i] != return_array['faillist'][j] )
ipgerrits_pickuplist.push(ip_gerrits[i]);
j++;
}
i++;
}
Ok, as far as you want to synchronize requests processing for all users, it should be done on the server side. I assume that your server side is Python, even though you did not add relevant tag to your question. My preferences are C# and PHP, but in your case I would do the following ...
Options # 1 - Session
1) add or install preferable session module for Python, crowd recommends to use Beaker
Python Module for Session Management
2) send AJAX request to the server side script
$(form).submit(function(e) {
var options = {
url: "scripts/cherrypick.py"
};
$.ajax(options);
});
3) this server side script will have something like this code
session_opts = {
'session.type': 'file',
'session.data_dir': './session/',
'session.auto': True,
}
app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
#hook('before_request')
def setup_request():
request.session = request.environ['beaker.session']
#route('/cherrypick')
def index():
if 'processing' in request.session:
data = { 'procesing': request.session['processing'] }
return data
processor()
def processor():
request.session['processing'] = 1
# Do some processing here for the first request
# When processing is done you can clear "state" variable in session
del request.session['processing']
request.session.modified = True
Bottle.py session with Beaker
http://beaker.readthedocs.org/en/latest/sessions.html#using
http://flask.pocoo.org/snippets/61/
4) Now in your JS script if you get JSON that contains key "processing" you may show alert to the user that he needs to wait until first request is processed
Option # 2 - Long Polling and Comet
Description of this option may take much more space to describe, thus it is better to look at this article, it has quite nice and clean example and implementation of long polling in Python
http://blog.oddbit.com/2013/11/23/long-polling-with-ja/
The main idea here is not to keep static session but use infinite loop instead that can send back different HTTP responses depending on some state variable :
#route('/cherrypick')
def index():
while True :
response = { 'processing': processing }
print response
if processing != 1 :
processing = 1
# Do some processing
processing = 0
sleep(5)
The simplest way is to close around a flag that indicates some processing is underway:
var processing = false;
$("#main_form").submit(function(event) {
if (processing) {
$("#some_notification_pane").text("hold on there, turbo!");
return;
}
processing = true;
...
$.ajax({
...
error: function(xhr, ajaxOptions, thrownError) {
...
processing = false;
},
success: function(response) {
...
processing = false;
}
});
...
});
You might also want to disable the submit button at the beginning of the submit handler (where I have processing = true) and re-enable it after receiving a response.

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

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
}
}
});
}

JQuery Ajax Request returns no data

I am trying out JQuery Ajax methods. I wrote a simple Ajax request to fetch certain 'tagged' photos from Flickr. Following is the snippet I am using:
function startSearch() {
$(function() {
var tagValue = $("#tagInput").attr("value");
alert(tagValue);
$.ajax({
url: "http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tagValue + "&tagmode=any&format=json&jsoncallback",
dataType: 'json',
async: false,
success: function(data) {
alert("Success");
$.each(data.items, function(i, item) {
var pic = item.media.m;
$("<img/>").attr("src", pic).appendTo("#images");
});
},
error: function(data, error) {
alert("Error " + error);
}
}); });
'startSearch' is associated with a Search button. User is supposed to input a 'tag' to search and on click this function gets called.
Problem is that I am not receiving any 'data' in response. Hence no images gets displayed.
What am I doing wrong here?
Thanks & Regards,
Keya
I think the problem is that you're trying to make a cross-site request, which doesn't work because of security concern. You could use JSONP instead, e.g. as described in http://www.viget.com/inspire/pulling-your-flickr-feed-with-jquery/
You can also try searching for "cross site ajax" on this site, there's plenty of discussion about it.

Categories