allow the user to update textbox value using jQuery - javascript

i am developing a project in ASP.NET MVC5 using SQL SERVER 2012
In this in one of the for i have scenario where user clicks on the Edit button and modal popup gets open with populated Email address in it(user can change it); after user changes the value of email that new email should gets stored.
my code is as below:
<tr>
<th>Email</th>
<td>
<input id="txtEmailId" name="txtEmailId"type="text" class="form-control"
placeholder="Email" size="254" style="width: 200px;"
value="#ViewBag.EmailAddress"/>
</td>
</tr>
js code is as below:
//save profile email address
$("#btnSaveProfile").click(function (e) {
debugger;
// var test = document.getElementById("txtEmail");
var userEmail = $("#txtEmailId").val();
alert(userEmail);
$.ajax({
type: "POST",
url: '/UserProfile/SaveUserDetails?EmailAddress=' + userEmail,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
if (data == "OK") {
alert("Email Saved")
}
},
error: function (msg) {
alert("Error :" + msg.responseText);
}
});
})
but it is saving older email address.

Are you referenceing the wrong input? Should you use:
$("#txtEmailId").val();

The button in the modal pop-up may need to trigger a script that assigns the new value to the input field $('#txtEmailId').
Sample html for modal pop-up.
<div class="modal-pop-up">
<input type="text" id="new-email" name="new-email">
<button id="save-btn">Assign New Email</button>
</div>
Sample script for modal pop-up.
$("#save-btn").on('click', function(e){
var $newEmail = $('#new-email').val();
$("#txtEmailId").val($newEmail);
// close modal
});
However you may not really need a modal pop-up just to allow the user to modify a single field in the original form.
It seems you are not assigning the data property:
$.ajax({
type: "POST",
url: '/UserProfile/SaveUserDetails?EmailAddress=' + userEmail,
contentType: "application/json; charset=utf-8",
data: { EmailAddress: userEmail } /* assign data property */
dataType: "json",
async: true,
success: function (data) {
if (data == "OK") {
alert("Email Saved")
}
},
error: function (msg) {
alert("Error :" + msg.responseText);
}
});

Related

Facing issue in retrieving data when user clicks on browser back button in MVC5

I am working on page when user submits data and retrieves html data which contains hyperlinks.
Now when the user clicks on the link, he will be navigated to another page and when the user clicks on browser back button, I want to show earlier displayed html data.
In order to achieve this, I tried to store the value in session and retrieve it when user clicks back browser button.
But I am facing issues
I tried to capture browser back button and display the session stored variable and I am not sure why this is not getting triggered.
$(window).on('hashchange', function () {
$("#spanId").html("test");
});
Html data stored in session variable is not displaying properly like "<" is showing as "&lt" and all the data is showing as string instead of html content.
$(document).ready(function () {
$("#spanId").html("#Session["Data"]");
$("#btnSubmit").click(function () {
var data = {
"Date": $.datepicker.formatDate("mm-dd-yy", DateVal),
"Type": $('#type').val(),
}
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
url: '#Url.Action("GetReportdata", "Reports")',
success: function (result) {
$("#spanId").html(content);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
Please let me know if there is any other way to handle this and help me resolves this issue.
There might be another way of solving this on the server side, but this should work.
$(document).ready(function () {
$("#spanId").html(decodeHtml("#Session["Data"]"));
$("#btnSubmit").click(function () {
var data = {
"Date": $.datepicker.formatDate("mm-dd-yy", DateVal),
"Type": $('#type').val(),
}
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
url: '#Url.Action("GetReportdata", "Reports")',
success: function (result) {
$("#spanId").html(decodeHtml(content));
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
function decodeHtml(encodedHtml) {
return encodedHtml.replace(/&/g,'&')
.replace(/</g,'<').replace(/>/g,'>');
}
I found an event to handle browser back button:
if (window.performance && window.performance.navigation.type ==
window.performance.navigation.TYPE_BACK_FORWARD) {
$("#spanId").html("#Session["Data"]");
}
This can be used to repopulate data.

Fill Data to control from success response which is on another page

I bring my ajax response on success call and after that I want to redirect to new aspx page where all my 30 input type text controls are their. So What I want is I want to fill all the values their. So how could I achieve it. Please suggest.
Here is what I tried till now
function getDataForDashboard(rjSapId) {
$.ajax({
type: "POST",
url: "Dashboard.aspx/GetDashboardDataOnFacId",
data: JSON.stringify({ rjSapId: rjSapId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
window.location.href = "http://localhost:39800/DashboardData.aspx?Id=" + rjSapId + "";
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
The another page some controls are below:-
<span>Site Type:</span>
<input type="text" id="txtSiteType" />
<br />
<span>Facility Type:</span>
<input type="text" id="txtFacilityType" />
<br />
May be you can save all your data in a hidden field by doing a stringify or, save it in local storage and then in the next page ajax ready you can retrieve it

Submit form having file using java script submit button

java-script :
i have a form that feed value to a controller via ajax call .
The form get serialized in ajax call and the controller return 'true' on success but the problem is that my form have a file and the file can't be serialized . I am working out how i can receive the file in my controller using this ajax call .
function save()
{
if(save_method == 'On_submitted')
{
url = "<?php echo site_url('MyController/insertForm')?>";
$.ajax({
url : url,
type: "POST",
data:$('#form_name').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_name').modal('hide');
alert('added successfully');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
}
When i omit the input file fields than its working fine , the main problem is to send the file to controller via java-script .
i have tries but i am don't know what is wrong and how can i do it .
you should not use dataType: "JSON" if you sending files.
you can form data for request using (filesForm = name of form):
var formData = new FormData(document.forms.filesForm);
then add other keys:
formData.append("key", keyValue);
and to send this data, add this options to ajax call:
contentType: false,
cache: false,
processData: false,
you need contentType = false (it will be multipart/form-data in fact) if you wish to upload files.
and final ajax call should be like this:
$.ajax({
url: url,
data: formData,
contentType: false,
cache: false,
processData: false,
type: 'POST',
success: function (result) {
$("#result").html(result)
},
error: function (result) {
$("#result").html(result)
}
});

How can I pass JavaScript variable value in php with same page using modal window

Here is my Javascript for fetching value to input box,
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id = document.getElementById('hdn_user_id').value = userid;
alert(userid);
});
I want this value to use for SQL query in modal window which is on same page.
I fetched value in modal window but unable to use it. What the format to use it.
You can pass js variable into php page using ajax.
$('#edituserModal').on('show.bs.modal', function(e) {
var userid = $(e.relatedTarget).data('userid');
var u_id=document.getElementById('hdn_user_id').value=userid;
$.ajax({ //create an ajax request to load page.php
type: "GET",
url: "page.php",
data:"varabletophp="+u_id, //Here is the value you wish to pass in to php page
dataType: "html", //expect html to be returned
success: function(response){
alert(response);
}
});
});
No you can get this variable into your page.php (php page) using
$fromjs=$_GET['varabletophp'];
echo $fromjs;
you can use input hidden and set userid value in on this input so , post form
Varying modal content based on trigger button :
http://getbootstrap.com/javascript/#modals-related-target
var data = new FormData($('form#' + formId)[0]);
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
beforeSend: function () {
},
success: function (response) {
},
error: function (response) {
}
});

JQuery ajaxfileupload with codeigniter

Good morning.
I wanna ask about JQuery ajax fileUpload. I have some issues regarding this.
I want to pass some variable from javascript function
Insert the variables and value from uploading file through jquery ajax
Here are the javascript function :
var baseurl = 'http://fadli.com/';
function upload_item(kode,field,table)
{
$("#upload_item_"+table+"_"+kode).hide(); //hide submit button
$("#loading_image_upload_"+table+"_"+kode).show(); //show loading image
console.log('masuk ke fungsi upload');
$.ajaxFileUpload({
url : baseurl+"admin/level/upload_item/"+kode+"/"+field+"/"+table,
//url :'./admin/level/upload_file/',
secureuri : false,
fileElementId :'userfile_'+table+'_'+field+'_'+kode,
dataType : 'json',
data : {
'title' : $('#sub_modul_title_'+kode).val()
},
success : function (data, status)
{
if(data.status != 'error')
{
// $('#files').html('<p>Reloading files...</p>');
// refresh_files();
// $('#title').val('');
alert('sukses brow');
$("#upload_item_"+table+"_"+kode).show(); //show submit button
$("#loading_image_upload_"+table+"_"+kode).hide(); //hide loading image
}
console.log(data.msg);
},
error:function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
$("#upload_item_"+table+"_"+kode).show(); //show submit button
$("#loading_image_upload_"+table+"_"+kode).hide(); //hide loading image
}
});
return false;
}
And here is the HTML code :
<input type="file" name="userfile" id="userfile_sub_modul_sub_modul_id_<?php echo $sub->sub_modul_id?>" class="styled-finputs">
<button class="btn btn-labeled btn-success btn-xs" type="button" id="upload_item_sub_modul_<?php echo $sub->sub_modul_id; ?>" onclick="upload_item('<?php echo $sub->sub_modul_id?>','sub_modul_id','sub_modul')"><span class="btn-label icon fa fa-picture-o"></span> Upload gambar</button>
<img src="http://fadli.com/assets/img/input-spinner.gif" id="loading_image_upload_sub_modul_<?php echo $sub->sub_modul_id?>" style="display:none" />
The problem is after the first console log, it's not working all way down.
Any help would be appreciate.
Thanks
For ajaxFileUpload, it is starting with capital A, try to change ajaxFileUpload to AjaxFileUpload
You can simply submit the form with ajax(without page reload).
Just use this code.It will submit your files data too.
$(document).on("submit", "form", function(event)//I wrote it for any form.You can change it for specific form
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//make sure your form has action url
type: $(this).attr("method"),//Your form method type GET OR POST
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
Also you can add addition data with FormData. https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects
You can modify the above function like this
$(document).on("submit", "form", function(event)
{
var formData = new FormData(this);
formData.append("MORE_INPUT_KEY", "MORE_DATA");
event.preventDefault();
$.ajax({
url: $(this).attr("action"),//set any link
type: $(this).attr("method"),//set any metho
dataType: "JSON",
data: formData ,
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});

Categories

Resources