how to write specific ajax post in Jquery - javascript

I have a jquery ajax post and when a user wirte and press enter in a messagebox this ajax triggers. but I want to make a specific post, so when a user write specific message then the ajax triggers. I used something like:
if(input == "Hello")
AjaxPost(input);
but it works for the first time and when I write something else than "hello" and then I write "hello" it does not trigger my ajax. but I do not think this way works, how can I write a specific ajax message?
AjaxPost : function(data) {
$.ajax({
type : "POST",
url : "/api/user",
datatype : "application/json",
contentType: " text/plain",
data : dataAttribute,
success : function(data) {
},
error : function(error) {
},

If it's a input or a textarea, then bind the change or the blur event to the element.
$('messagboxIdentifier').change(function() {
if(this.value === 'Hello') {
// call the method here
}
});

$('#messagboxIdentifier').change(function() {
if(this.value === 'Hello') {
// call the method here
}
});
A # symbol is to be used with the id to bind it properly, was it done ?

Related

ASP.net/JS/JQuery/AJAX - ajax works but handler event not firing properly

I have a HTTP handler (ASHX) which I am calling from UI side using an AJAX function. The following is what needs to happen in this call:
When the section loads, it will display the status of the short code on the server in the shortcodestatus span. It will either say on or off:
<a class="btn btn-default" id="toggleshortcode">Short Code <span id="shortcodestatus"></span></a>
This is the function for getting the status of the short code and this works properly. I can manually change the status of the short code and the changes reflect properly on the div when I reload the page:
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
$("#shortcodestatus").empty();
if (output == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
});
};
This is the short code status code from the handler:
case "shortcodestatus":
{
output = ShortCodeStatus() ? "true" : "false";
}
break;
I want to be able to click on the toggleshortcode div to fire off this event through the handler. The functions for disabling and enabling the short code are working properly:
case "toggleshortcode":
{
if (ShortCodeStatus() == true)
{
DisableShortCode();
output = "false";
}
else
{
EnableShortCode();
output = "true";
}
}
break;
Here is the ajax call for the short code toggle:
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
ShortCodeStatus();
}
});
});
I'm hitting the URLs correctly and I'm getting the correct responses from each function. However the change to the short code does not seem to be happening.
For example, if the short code is off, the ShortCodeStatus function will return false and thus render the OFF button. When I click on the toggleshortcode button, the output is true (I want to turn on short code) which is correct but when the ShortCodeStatus function fires again in the success, it will still say false. The ajax functions seem correct but I can't figure out why the toggleshortcode on the handler is not firing properly.
Thank you so much for your time!
I'm seeing 2 cases that you can check.
First, in the ajax call for 'toggleshortcode', you are calling the function 'getShortCodeStatus()', and base on your example the correct name of the function is 'ShortCodeStatus()'.
Second, in the call to 'Handler.ashx?action=toggleshortcode', you are already returning the status (true or false), I suggest you make a javascript function named SetShortCodeStatus(status) , and use this inside of the success of both ajax request 'Handler.ashx?action=shortcodestatus' and 'Handler.ashx?action=toggleshortcode'.
function SetShortCodeStatus(status) {
$("#shortcodestatus").empty();
if (status == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
SetShortCodeStatus(output);
}
});
};
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
SetShortCodeStatus(output);
}
});
});

Ajax form reloading page instead of working in the background

Firstly, based on other suggestions, I've tried moving around the preventDefault() but haven't had success.
My feedback form uses this JavaScript to pass form fields to "process.php" and return with the relevant messages (ie: "sucesss" or "fail")
It's doing its job except that instead of staying on the same page 'feedback.php' it loads 'process.php' page with this ... {"Data":"Data Value"}
Heres the code:
$(document).ready(
function(){
$('form').submit(
function(event){
var formData =
{
'name' : $('input[name=name]').val(),
'page' : $('input[name=page]').val()
};
$('.form-group').removeClass('has-error'); // remove the error class
$('.error').remove(); // remove the error text
event.preventDefault();
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
.done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}
);
.fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
}
console.log(data);
);
event.preventDefault();
}
);
});
looks like syntax error calling $.ajax, it should be corrected like this:
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
}).done(function(data){
if ( ! data.success)
{
if (data.errors.name)
{
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#nameField').append(data.errors.name); // add the actual error name under our input
}
}
else
{
$('form').append('<div class="buttonError">Message Sent!</div>');
form.myButton.disabled = true;
}
}).fail(function(data){
$('form').append('<div class="buttonError">Failed!</div>');
console.log(data);
});
Remove the method and action in the form tag in your HTML file. This looks fine. Let me know if it doesn't work.

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

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

How do I return a boolean value for a form's "onsubmit" attribute depending on the success or error of an ajax call?

If my form is defined as follows:
<form action="myAction" method="post" id="input" target="_parent" onsubmit="doThis();">
and doThis() is part of the following script:
var result = false;
function doThis() {
var myUrl = 'http://somewebsite.com/SomeWebservice/Webservice?args1=AAA&callback=?';
var status = false;
$.ajax({
url : myUrl,
type : 'get',
dataType : 'jsonp',
success : function(res) {
onSuccess(res);
},
error : function(e, msg, error) {
onError(e, msg, error);
}
});
return result;
}
function onError(e, msg, error) {
// do stuff if error
result = false;
}
function onSuccess(res) {
// do stuff if successful
result = true;
}
What I'm expecting is that if the ajax call is successful, onSuccess will set result to true, then doThis will return true and the form will submit. However, this does not happen. In fact, nothing happens.
My suspicion is that since the ajax call is asynchronous, doThis already returns a value (false) before the ajax transaction completes, so the return is always false. If that's the case, how do I modify my code so that it returns true or false depending on whether the ajax call is successful or not?
I think I can set async to false, but I keep on reading that callbacks are a better way to code than doing "async : false" --- so I was wondering what the best solution for this is.
EDIT:
I've put the following alerts in the onError and onSuccess functions:
function onError(e, msg, error) {
alert(e+" - "+msg+" - "+error);
result = false;
}
function onSuccess(res) {
alert("success");
result = true;
}
And running my code confirms that the logic passes through onSuccess.
Success is an AJAX event which is trigged after the AJAX completes http://api.jquery.com/Ajax_Events/ . So, what you are expecting is correct. Try adding some alerts to your code to see what each function is returning. like :
function onSuccess(res) {
// do stuff if successful
alert('Ajax success');
result = true;
}
r you sure that ajax request return success and go to function onSuccess(res) ?
you should add alert to know where the code goes. may be its goes to error : function(e, msg, error). alert what error msg saying?
I would suggest if possible you can go for Jquery Form Plugin. Instead of invoking an jquery ajax call
you can invoke ajaxForm or ajaxSubmitfunctions provided by that plugin. You can use these two functions just like an ajax call and it also supports success or error callback functions
Sample usage
$('#input').ajaxForm({
url: myUrl ,
success : function(response) {
// handle success
},
error : function() {
// handle error
}
});
Remove 'onsubmit' property.
<form action="myAction" method="post" id="input" target="_parent">
Instead use 'onclick' property. let's say your form is submitted by button or html element.
call $('.YourFormSubmitElement').onclick('doThis'). Note that if your has multiple form submission elements use class selector else if it is one use id selector.
Use the below function to submit the form.
function doThis() {
var myUrl = 'http://somewebsite.com/SomeWebservice/Webservice?args1=AAA&callback=?';
$.ajax({
url : myUrl,
type : 'get',
dataType : 'jsonp',
success : function(res) {
$('#input').submit();
}
});
}
I think this should fix your problem.

append url with # using ajax

i want to add hash url for example: #completed in the url using Ajax after form return success:
submitHandler:function(form) {
$(form).ajaxSubmit({
target:'.result',
beforeSubmit:function(){
$('.form-footer').addClass('progress');
},
error:function(){
$('.form-footer').removeClass('progress');
},
success:function(){
$('.form-footer').removeClass('progress');
$('.alert-success').show().delay(10000).fadeOut();
$('.field').removeClass("state-error, state-success");
if( $('.alert-error').length == 0){
$('#smart-form').resetForm();
//reloadCaptcha();
}
}
});
}
Thank you
You can add inside your success callback:
window.location.hash = '#completed';
and in error you could add similar
if however you wanted 1 saying that the url was called and dont care about success failure you could put into finally method instead

Categories

Resources