javascript or ajax to update database with asp.net mvc? - javascript

I have a function here from a change event on a dropdownlist. When the selection gets changed I want to update a row in my database. Should I use javascript or ajax. I don't want the page to be refreshed. I think it should be ajax, but not sure? If ajax, can anyone point me to a tutorial/video/etc?
Here is where I want to update my db row.
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function(event) {
// call db and update row
}, false);

Looks like you using asp.net mvc.
You can write your ajax calls with pure javascript Ajax docs or the easiest way, using JQuery.
You need to add one action on your controller to receive the ajax data, and then insert/update your db.
See this, this and this.

Most common scenario would be making an ajax call using HTTP POST/PUT to a controller method, which would then handle the data and update the database directly or pass through to your service/data layer code.
Probably the easiest way to make the call would be using the jQuery.ajax method. Documentation can be found here: http://api.jquery.com/jquery.ajax/

You can try something like this
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
var name = $('#TextBox1').val();
var email = $('#TextBox2').val();
if (name != '' && email != '') {
$.ajax
({
type: 'POST',
url: 'Home/UpdateDB', //if it is plain asp.net then UpdateDB is declared as WebMethod
async: false,
data: "{'name':'" + name + "','email':'" + email + "'}",
contentType: 'application/json; charset =utf-8',
success: function (data) {
var obj = data.d;
if (obj == 'true') {
$('#TextBox1').val('');
$('#TextBox2').val('');
alert("Data Saved Successfully");
}
},
error: function (result) {
alert("Error Occured, Try Again");
}
});
}
})
});
</script>

fg
iuou
uouienter link description here
uiouidfgsdfgddfgdfgdfgdgdgd##
Heading
##*
uio
uiopomkl
hjlkdsg
dsf
dfgdg
Blockquote

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

PHP not reciving data with AJAX's POST

I have to say I saw a dozens of topics similar to my problem, but most of them were typos or spelling.
My PHP file does not seem to receive any data from AJAX POST function (I'm getting Undefined Index). Here is my code:
var login = $("#log_l").val();
var pwd = $("#pwd_l").val();
alert(login);
alert(pwd);
$.ajax({
type: "POST",
url: 'app/menu/login.php',
data: {
login1: login,
pwd1: pwd,
},
cache: false,
success: function (data) {
if (data == 'fail') {
alert('test2');
$('#failure_log').show();
}
else {
document.location = " {$conf->action_root}postlogin";
}
}
});
return false;
And the login.php:
$login = $_POST['login1'];
$haslo = $_POST['pwd1'];
...
I tried with both:
login1:login,
pwd1:pwd,
And:
'login1':login,
'pwd1':pwd,
But in both ways I receive "Undefined index" error in .php file on 'login1' and 'pwd1' variables.
I checked that ajax 'reaches' file and it even receives the echos from .php file, but the variables are not sent/received.
Do you have any ideas what might be wrong?
You need to use file_get_contents to capture ajax calls or you need to define. Check this
How to get JSON data in php ?
Or
you need to set the ajax call as form_encoded_url
contentType: "application/x-www-form-urlencoded",
refer this link
Submitting HTML form using Jquery AJAX

Wordpress get current page name or id within ajax request callback

I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/

Pass a value to multiple PHP pages at once with JQuery

My inexperience has me here asking this question.
Can I pass a value to multiple PHP pages in JQuery?
Here is an example of what I am trying to do.
$(function() {
$("#account").change(function() {
$("#facilities").load("displayfacilities.php?q=" + $("#account").val());
$("#facilities").load("updatefacilities.php?f=" + $("#account").val());
});
});
When the user changes a selection within a drop down list, a unique ID will be sent over to displayfacilities.php. I also need that ID in updatefacilities.php which is called from displayfacilities.php.
Is this a bad idea, or is there a better way?
Try to make use of $_SESSION and example of the usage.
This object allows you to store and retrieve data and a usual use case is to share this data across multiple pages within a session.
ex.
$(function() {
$("#account").change(function() {
// store value in superglobal variable and retrieved
// by session_start() in php script, see usage examples above
<?php $_SESSION['some_key'] = *some_value* ?>
// the following value however needs to be sent to server
// either via AJAX or some request.
$("#account").val();
});
});
Hope this helps.
Check this out,
First call ajax, when the response is received, make the second ajax call.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#account").change(function() {
var dataString1 = "q="+$("#account").val();
$.ajax
({
url: "displayfacilities.php",
type : "POST",
cache : false,
data : dataString1,
success: function(result1)
{
alert("Response from PHP file 1");
var dataString2 = "f=" + $("#account").val();
$.ajax
({
url: "updatefacilities.php",
type : "POST",
cache : false,
data : dataString2,
success: function(result2)
{
alert("Response from PHP file 2");
}
}
});
});
});
});
</script>

I need to get a variable between jQuery function and AJAX

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.
var button;
var form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
and this other send the form data through AJAX using the info already obtained from the button using the script above.
form.bind('submit',function () {
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
beforeSend: function() {
//$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.message == 0){
$("#fave").attr('src','interactions/favorite.png');
$("#favorite").attr('value',1);
console.log(data.errors);
}
if(data.message == 1)
{
$("#fave").attr('src','interactions/favorite_active.png');
$("#favorite").attr('value',0);
}
if(data.message == "plus")
{
$("#vote_up").attr('class','options options-hover');
$("#vote_down").attr('class','options');
console.log(data.message);
}
if(data.message == "sub")
{
$("#vote_down").attr('class','options options-hover');
$("#vote_up").attr('class','options');
console.log("sub");
}
},
error: function(xhr, textStatus, thrownError) {
console.log(data.message);
}
});
return false;
});
The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.
1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.
2nd edit: I found the solution, I posted below.
var button is in the scope of the .on('event', function(){})
You need to declare the variable in the shared scope, then you can modify the value inside the event callback, i.e.
var button,
form = $('.register_ajax');
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
});
You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at http://www.crockford.com/.
I Found the solution, I just changed a little bit the click function like this:
var button;
var form = $('.register_ajax');
var data = form.serializeArray();
$('#vote_up, #vote_down').on("click",function(e) {
e.preventDefault();
button = $(this).attr("id");
data.push({name: encodeURI($(this).attr('name')), value: encodeURI($(this).attr('value'))});
form.submit();
});
using e.preventDefault(); and form.submit(); to send the form. also I changed the data.serialize to serializeArray(); because it's more effective to push data into the serializeArray(). in the second script I just changed the data.serialize() and used the data variable that I already filled with the serializeArray() and the data.push():
form.bind('submit',function () {
alert(button);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
cache: false,
dataType: 'json',
data: data,
//here goes the rest of the code
//...
});
return false;
});
it worked for me, it solved the problem between the click and submit event that wasn't allowing me to send the function through ajax.

Categories

Resources