Toggle div depending on controller variable value - javascript

EDITED
I have a "Save Changes" button that I want to click and toggle a div with the message "Changes saved". I do it like this:
HTML:
<input type="submit" id="savebtn" name="save" value="Save Changes"/>
<input type="hidden" id="res" name="res" value="#ViewBag.result"/>
<div class="success">Changes saved</div>
JQuery
$('#saveButton').click(function () {
var aux = res.value.toString();
if ($('#res').val() == "OK")
$(".success").show();
alert(aux);
});
However, I need the button to actually save the changes and, if the operation was successful, then show the message div. So, in my cshtml file I have a result variable that contains the success or failure of the operation.
CSHTML:
ViewBag.result = result;
Now, I need to show that message div depending on the result variable: I need to somehow make it a parameter for the JQuery function. I'm passing it in a ViewBag.
NOTE: when the page loads, the viewbag is empty. It only gets its value after the button click. And after that, the viewbag is filled and I wanted it to be used in the jQuery function but I'm not getting any luck.

Pass that result in a viewbag,
Acces that viewbag value in jquery and show/hide your div accordingly

Assuming you can store the result in input hidden field, use below query to access result and initially success div is hidden :
<input type="hidden" id="result" value"success"/>
jQuery :
$(function(){
if($('#result').val()=="success")
$(".success").show();
});

you can check it in a simple if condition
if($('#result').val()=="success")
$(".success").toggle();
or You can use Ajax method
function Save() {
$.ajax({
url: "Your Url", // Current Page, Method
data: Your data // better if you parameter map as JSON
type: "POST",
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 100000, // AJAX timeout
success: function (result) {
$(".success").toggle();
},
error: function (xhr, status) {
alert("An error occurred while processing");
}
});
}
Now call this save() in your button click

Related

How to pass value using javascript success function in old CI

i'm working with an old codeigniter. i'm calling a onchange function. i want to get data from controller and show it to a input filed which is an array.
view page code:
<select name='feed_id[]' style='width:95px;'onchange="getfeedstock(0,this.value)"><?=$this->mod_feed->get_feeds()?></select>
<span><input type='text' name='stock[]' readonly value='' class='num_txt stock<?=$inc?>' /></span>
javascript:
<script >
function getfeedstock(i,obj){
//alert(obj);
$.ajax({
url:base_url+'feed_sale/get_feed_stock',
type:'post',
data:{
feed_id:feed_id
},
success:function(data){
//alert(data);
//var stock=5;
//$('.stock').val(stock);
},
error:function(error,msg){
alert(error+msg);
}
});
}
</script>
Use Output class of Codeigniter
https://www.codeigniter.com/userguide2/libraries/output.html
it will set page header to JSON type. And pass array using json_encode();
all array of PHP will get in JSON object format in success callback of Ajax
success: function(data) {
alert(data.msg); // showing [Object][object]
//all array visible in console log Ctrl+Shift+I (in chrome)
console.log(data);
}

The name parametor does not exist in the current context in JQUERY method

I have button and when It clicked process event have been called and parameter passed to the event.
Here the code:
<input type="button" value="Accessing Layers" onclick="process('AccessingLayers');" />
function process(actionName) {
$.ajax({
url: '#Url.Action(actionName)',
type: 'POST',
data: {
sessionID: parent.parent.mapFrame.sessionId,
mapName: parent.parent.mapFrame.mapName
},
success: function (result) {
alert('Successfully passed data to controller');
}
});
}
But in this row:
url: '#Url.Action(actionName)'
I get this error:
The name 'actionName' does not exist in the current context
Any idea why I get error above?
And how to fix it?
Remember razor code executes on the server before the your client side code gets executed. So you cannot pass a javascript variable to a razor method like that.
If you still want to build the url using the Url.Action helper method and pass it to your process method, you should call the Url.Action method with correct arguments(the action method,controller name etc..) and generate the url and pass the url( generated by razor) to your javascript method as a string parameter value
<input type="button" value="Accessing Layers"
onclick="process('#Url.Action("AccessingLayers")')" />
and your js code
function process(actionUrl) {
$.ajax({
url: actionUrl,
// existing code
});
}
<input type="button" value="Accessing Layers" id="btnAccessingLayers" />
and in scripts section
$(document).ready(function () {
$('#btnAccessingLayers').on('click', function(){
process('#Url.Action("AccessingLayers")');
}
});
function process(actionUrl) {
$.ajax({
url: actionUrl,
// existing code
});
}
Everything typed between quotes is parsed as plain text, therefore no computation is performed on retrieving value of actionName.
You have to break your url like this:
url: '#Url.Action('+actionName+')'
so that actionName gets resolved as variable.

HTML button not displaying on success of ajax

I need to display an input button on the success message in my view. I am working in MVC 3 application using razor views. This button will allow the user to navigate to another view.
Controller.
var successfull = new string[]
{
"All " + builder.Data.Count.ToString() + " work items were added successfully."
};
return new JsonResult
{
Data = new { success = true, msg = successfull}
};
JavaScript.
var jsonText = JSON.stringify(json);
$.ajax({
url: '/Builder/CreateWork',
type: 'POST',
dataType: 'json',
data: jsonText,
contentType: 'application/json; charset=utf-8',
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
},
complete: function () {
// hides the loading gif
$('.loading').hide();
}
});
View
<div id="resultMessage"></div>
Is there a way to add to the ajax code to include the following input button.
<input type="button" class="styledbutton" value="Some text" onclick="window.location.href='Url.Action("action", "controller")';" />
EDIT ---
The problem lies with this piece of code - but can't see the problem.
onclick="window.location.href = '#Url.Action("actionName", "controllerName")'"/>');
Please advise.
The button is static so you can hide it
<input style="display:none" type="button" class="styledbutton" value="Some text" onclick="window.location.href='Url.Action("actionName", "controllerName")';" />
And then in success callback show it
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
//show button
$(".styledbutton").show();
},
Yes you can generate html in ajax call as given below :
<div id="div1"><div>
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
$('#div1').html('<input type="button" class="styledbutton" value="Some text" onclick="window.location.href='#Url.Action("actionName", "controllerName")'/>')
}
Above Code will work fine,just generate html in ajax call as above.
You can do this in a simple way. As you have been advised, you can hide the button initially using css.
<input type="button" class="styledbutton" style="display:none;" value="demo" onclick="window.location.href='Url.Action("actionName", "controllerName")';"/>
you just need little bit tweak in your js code if everything behind the scenes is working fine (i mean model and controllers).
use done() instead of success and likewise always() instead of complete if you are using jQuery v 1.8 or higher. Check the deprecation notice in docs. success and complete are no longer in use as of jQuery 1.8+
$.ajax({
url: '/Builder/CreateWork',
type: 'POST',
dataType: 'json',
data: jsonText,
contentType: 'application/json; charset=utf-8'
}).done(function(result){
// clear table
$('#instruments-data').empty();
resultMessage(result);
//just show the button
$(".styledbutton").show();
}).always(function(){
// hides the loading gif
$('.loading').hide();
});
Note: Place your button exactly where you want to see it on view and make it display:none. Ajax will handle the rest. Let me know if it doesn't work.
None of the previous answers were allowing for re-direct, so I found a work around.
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
$('#resultMessage').append('<input type="button" id="MultiStatus"class="styledbutton" value="Button text" />');
$('#MultiStatus').click(function (e) {
location.href = "/Controller/Action";
});
If you want advice, i would suggest you to try anchor button with bootstrap styling to reflect the feel of a button.
can you please try this if that doesn't hurt your intention.
example:
#Html.ActionLink("ButtonText", "ActionName", "ControllerName", null, new { #id = "Query", #class = "btn btn-inverse styledButton" })
i have included a jsbin demo about how to use the button for your specific need, please follow this link: Demo
Feel free to comment if you need any explanation

AJAX - Button Submit to update a form

I'm attempting to learn to make use of AJAX. I removed most of the complexity of the program to just isolate the problem I'm having. So I have a text area and beneath that a div that has "STATUS" printing out. On button submit using AJAX I want to change the word "STATUS" to the value of my variable, status, which in this case should be "SUCCESS".
What happens instead when I click is it prints out the word STATUS. It appears like nothing is happening when I click my submit button. Any ideas what I am doing wrong?
$(document).ready(
function () {
$('#sub').live('click',
function () {
url = 'http://whatever.php'
success = "Success!"
$.ajax({
url: url,
type: 'POST',
data: null
dataType: 'xml',
async: false,
success: function (data, statusText, reqObj) {
status = $(data).find('status').text()
if (status == 'SUCCESS') {
$('#succ').html(status)
} //if( status == 'SUCCESS' ) {
else {
msg = $(data).find('msg').text()
alert('NOT ADDED: ' + msg)
return
} // else
} //function()
}) //$.ajax( {
} /* function */ ) //live(
} //function()
) //$(document).ready
HTML:
<div id="buttonArea">
<textarea name="txtarea" cols=80 rows=30>>THIS TEXT BOX
IS USED FOR THINGS I WILL WORK ON LATER
</textarea><br/>
<input type=submit value='Submit Textbox Info!' id='sub'>
</div>
<div class="float-left" id='succ'>STATUS</div>
I think your find is empty. Try to replace with
status = $(data).text()
I'm not sure you use .find() the right way. it's used on html elements and expects to be passed a jquery selector or element or jquery object.
here's more details http://api.jquery.com/find/
what you want is to get your response text, so assign your ajax call to a variable:
xmlhttp = $.ajax({
then on success use your response text:
status = xmlhttp.responseText;
Your code works fine for me, on the proviso that:
(i) you add the missing comma from the line:
data: null,
(ii) the content-type returned by your php handler is text/xml

jQuery submit doesn't handle "success"

I've gone through all of the solutions I could find on Stack Overflow and Google but none of them seem to help.
I have a function in Clojure (Noir framework) that takes two keys, "text" and "day-of-note" and inserts the values into a database. Regardless of whether or not that works, the function returns a JSON response with {"result":true} (for testing purposes).
(defpage [:post "/newpost"] {:keys [text day-of-note]}
[]
(println "newpost called")
(post text)
(response/json {:result true}))
My form is a simple form with one textarea, a checkbox and a button.
<form action="/newpost" id="new-post" method="post">
<textarea id="entry" name="text">Insert todays happenings</textarea>
<br />
<input checked="checked" name="day-of-note" type="checkbox" value="true">
<input type="submit" value="Add entry">
</form>
When submitting the form I have added a call to alert to show me the contents of dataString and they are formatted correctly ("text=lalala&day-of-note=true").
$(function () {
$("#new-post").submit(function (e) {
e.preventDefault();
var dataString = $("#new-post").serialize();
alert(dataString);
$.ajax({
url: "/newpost",
type: "POST",
dataType: "json",
data: dataString,
success: function () {
alert("Success!");
};
});
return false;
});
});
What happens here when the code is as it is above, there is a HTML call to /newpost when the user click on the button and the page shows {"result":true}. If I comment out the "$.ajax"-part the message box pops up with the correct content, but if I remove the comments -- no message box, just goes straight to /newpost.
What I thought was supposed to happen was that the /newpost page would never be rendered but a call with the dataString would be put to it by Ajax and a message box with "Success!" would be shown.
Where am I taking the wrong turn?
Remove the semi-colon after the success function declaration:
success: function () {
alert("Success!");
}
The success function declaration is part of an object, which separates declarations by comma.

Categories