ajax form submits fine, but success does not work? - ajax

I have a simple form that submits with jquery and ajax. the form submits fine and the data posts, but the success message will not call... just the error message. can someone tell me what I am doing wrong.
<script type="text/javascript" >
$(function() {
$(".form-submit").click(function() {
var esn = $("#esn").val();
var dataString = 'esn='+esn;
if(esn=='')
{
$('.error').show().fadeOut(3000);
}
else
{
$.ajax({
type: "post",
url: "include/submit_repair_form.php",
data: dataString,
success: function(result) {
alert(result);
$('.testing').hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
}
});
}
return false;
});
});
</script>

You forgot to set the result variable in function()
Like this:
success: function(result) {
alert(result);
$('.testing').hide();
}

Related

Check for cookie and then geo-redirect if

The following geo-redirect code works:
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script>
function geoip() {
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "NZ") {
window.location = "https://www.example.com/";
}
}
});
}
geoip();
</script>
Building on this, I now want to check for a cookie, but can't get it to work. Where am I going wrong?
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script>
var cookieSwitch = 'geo-switch';
if(typeof Cookies.get(cookieSwitch) == 'undefined') { // If cookie is not found, then geo-redirect
function geoip() {
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "NZ") {
window.location = "https://www.example.com/";
}
}
});
}
geoip();
});
</script>
This worked!
<script async src="https://get.geojs.io/v1/ip/geo.js"></script>
<script>
if(typeof Cookies.get('geo-switch') == 'undefined') { // If cookie not found, then redirect if applicable
$.ajax({
type: 'get',
url: 'https://get.geojs.io/v1/ip/country.json',
success: function(data) {
if (data['country'] == "NZ") {
window.location = "https://www.example.com/";
}
}
});
}
</script>
Please note, you will need to include the following for this to work:
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>

How to use submit form with ajax

I already make login form and success, but when I'm trying add ajax, it fails, does anyone know a solution? this is my code:
$(document).ready(function()
{
$("#formLogin").submit(function(e)
{
$.ajax({
url:"<?php echo site_url('login'); ?>",
type:"POST",
data:$("#formLogin").serialize()
})
.done(function(response)
{
if(response =='gagal')
{
$(".alert.alert-danger").show('fast');
}
else
{
window.location.href = "http://localhost/epeds_web/";
}
});
e.preventDefault():
});
});

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

show ajax-loader.png on a MVC3 form submit in a Jquerymobile application

I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}

Converting MVC Ajax to Jquery

I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});

Resources