how to pass #model.ApplicationId from html form to js - javascript

I am trying to make an auto save function that will save the form data. I am unable to pass my ApplicationId in from form to JS in order to auto save. Though with the fixed id, auto saving does work. I have the following code:
Js Code:
window.setInterval(AutoSaveDraft(id), 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
Html CODE:
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId" >
...
</form>
Basically, I want the #Model.ApplicationId to be passed to my Js, so that I can use that in my Autosaving function.

Let's say you have your JS on the same page as your html, you could simply write:
window.setInterval(function () {
var id = '#Model.ApplicationId'; // Turned C# to JS here
AutoSaveDraft(id);
}, 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
Now let's say your JS is somewhere else:
HTML:
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId" >
...
</form>
JS:
window.setInterval(function () {
var id = $("#application-form").attr('name'); // Retrieve the ID
AutoSaveDraft(id);
}, 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
That's said, I would suggest you to use data- attribute to pass that kind of data. Let's try with data-application-id.
<form asp-action="Edit" id="application-form" data-application-id="#Model.ApplicationId">
...
</form>
window.setInterval(function () {
var id = $("#application-form").data("application-id"); // Retrieve here
AutoSaveDraft(id);
}, 50000);

First off, your interval is wrong. What you are doing is calling a function and passing the result to the interval. You need to pass it a function that it can then call when needed. You are calling your function right away.
Next, all you need to do, is to use jQueries attr() method like so:
let id = 'application-form'
window.setInterval(() => AutoSaveDraft(id), 5000);
function AutoSaveDraft(id) {
let name = $(`#${id}`).attr('name')
console.log(name)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId">
</form>

Related

How to define a variable after process in ajax?

I use an ajax process to modify user's state on an index.php file.
It works but I would like to color my div function of the user's state
My code:
function recupstatut() {
$.post('recup.php', function(data) {
$('.cont2').html(data);
var content = document.querySelector('#cont2');
var status2 = content.innerHTML;
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cont2" id="cont2">
</div>
The condition always applies the else state:
content.style.backgroundColor = "#f44336";
I think the problem comes from var status2 =
How can I fix this?
HTML
<div class="cont2" id="cont2"></div>
SCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
function recupstatut() {
$.post('recup.php', function(data) {
console.log(data);
var status2 = data.trim();
console.log(status2);
$('.cont2').html(status2);
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
</script>
what went wrong is that you imported jquery file after calling the function
so make the import in top of calling your function
your mistake was that you made the import after calling the function, that is why you got undefined error.
As you say you echo string in your page then you can check this one directly from the data as per below code.
Script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(function(){
function recupstatut() {
$.post('recup.php', function(data) {
$('#cont2').html(data); // If the data return from the php page as a string then you can compare it directly.
if (data == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut, 1000);
});
</script>
HTML:
<div class="cont2" id="cont2"></div>
function recupstatut(){
$.post('recup.php',function(data){
console.log(data);
$('.cont2').html(data);
var status2 = data;
if (status2 == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut,1000);
nothing appear in my div now with the console.log...
THere many ways to accomplish this. You can use the $.post() function by sending the $.post as a variable. Example:
// Fire off the request to /form.php
request = $.post({
url: "recup.php",
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
Or (i recommended) use the $.ajax({}) function as this way:
// Fire off the request to /form.php
$.ajax({
url: "recup.php",
type: "post",
data: { //specify data to be sent },
beforeSend:function(){
/* before sending the data to the other page
may be a loader to show waiting animation
*/
},
success:function(status){
/* this will check the response received from the previous page
and the determine the below conditions
*/
if (status == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
}
});

How to detect new line in result of ajax?

I get result of PartialViewResult in asp.net mvc project via ajax.When Model is null ! I pass nothing in partialViewResult but I get newline in result of ajax.How can i detect it by js?
var GetSuns = function (btn) {
$('body').append('<div class="WrapProgress"><img class="loadingimg vertical-middle-image" src="/Content/Travelo/images/travelenter_process_Art.gif" /></div>');
var urn = $(btn).data('urn');
var method = $(btn).data('method');
$.ajax({
url: '/art/ShowTime',
data: { s: urn, method: method },
type: "POST",
success: function (result) {
if (result.trim) {
console.log("1"+result+"1")
$('.WrapProgress').remove();
$('#ModalSuns .modal-body').html(result);
$('#ModalSuns').modal('show');
} else {
$('#Modal').modal('show');
}
},
error: function (jqXhr, textStates, errorThrown) {
console.log(errorThrown);
$('.WrapProgress').remove();
}
});
};
The issue with your code is anyway the result.trim need to changed to result.trim() inorder to trim the result string for any trailing spaces or linebreaks.
In order to detect line breaks in your code
text = `
`;
numberOfLineBreaks = (text.match(/\n/g)||[]).length;
console.log(numberOfLineBreaks)

div.load() causing full page postback

After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.

Using Jquery/SetTimeout to Update Div - Update Not Working

What I am Trying to Do:
I am trying to use settimeout to loop/run after a function is called to automatically update/refresh a div.
What Isn't Working:
To be clear settimeout is working, but the div is not automatically refreshing/updating when I enter new test data into the db. In other words, If I refresh the page, I see the new test data, but not if I let the update function run.
Code:
function update(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
console.log("Queried Database...");
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#login-box").hide();
//$("#trades").html(' ');
localStorage.setItem("wings_lastsignal", v.candel);
var lastsignal = localStorage.getItem("wings_lastsignal");
console.log(v.candel);
if(lastsignal == v.candel) {
console.log("No New Signals");
localStorage.getItem("wings_currentsignals");
if(v.signal == 'Buy') {
console.log("Current Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Current Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
} else {
playChing();
console.log("New Signal");
if(v.signal == 'Buy') {
console.log("Buy Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowup"></span>'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'" onClick="var a = this.innerHTML; tsclick(a);" value="'+v.symbol+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
} else {
console.log("Sell Sent...");
$("#trades").append('<span id="'+v.candel+'" class="tradesignal"><span class="signalarrowdown"></span>'+v.time+'<span style="color:#fb5350;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
}
}
});
}
//alert(response);
//console.log(response);
}
}).then(function() { // on completion, restart
var a = localStorage.getItem("wingsaccnum");
//setTimeout(update, 10000);
setTimeout(function(){ update(a) }, 20000); // function refers to itself
console.log("Timeout");
});
}
This function is called when I a button is pressed, using this Jquery snippet:
$( "#rbuttonon" ).click(function() {
var acc = localStorage.getItem("wingsaccnum");
//refresh_box();
update(acc);
console.log('Interval set');
});
Other Notes:
To be clear, I don't mind if there is a way to always make sure this div is updated every xx amount of time, without the need to press any buttons. I believe the problem is in my code's logic, but I would greatly appreciate some assistance!

Form reloading page without sending the data on submit

here's my code.
In my .js file:
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = '';
params += 'action=Send';
params += '&title='+title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
}
else
{
return true;
}
}
And in my index.php file:
<form action="" method="post" name="myform" id="myform"" >
Title: <input class="" type="text" name="title" value="" id="title"/> <br>
<input type="submit" value="Submit" onClick="javascript:Sendit();return false; ">
</form>
<?php
if ($_REQUEST["action"]=='Send')
{
$title = $_REQUEST["title"];
$sql = "INSERT INTO ...
$retval = $mysqli->query($sql, $conn);
if(! $retval ) {
echo('Could not enter data insert: ' . mysql_error());
}
else
{
//inform that everything went well
}
?>
This does not send a thing when the sunmit button is clicked. In fact, you can click the button until the end of the day that nothing happens (not even a message in the debugger)
If I delete the return false; from the onClick in the button, I click on the button and the page reloads even without filling in the title input which has to be filled in.
Ajax's success does not alert a thing and in both cases, nothing gets inserted in my database.
The insert query is correct, I've checked it.
Any ideas on how to send the data and validate?
Thanks
Use below Code to send req.
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = {};
params["action"] = 'Send';
params["title"] = title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
your validateField() function never returns true, so your if(bValidate) will never run. Javascript functions return undefined unless you explicitly return something, try this:
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
} esle {
return true;
}
}

Categories

Resources