I have the jQuery code below, but the when().done() does not work as expected for me. The updateResultFooter() is called bedore the doReverseSearch() method finish her its work. and as a result of that, a button in my view is enabled, and then re-take his default value (desabled) after the replace in the doReverseSearch() method.
$("#idBnSearch").click(function ()
{
$.when(doReverseSearch(telValue, pageIndex, methodUrl))
.done(function ()
{
updateResultFooter("#ViewBag.CountResult", pageIndex, "#ViewBag.PageCount");
});
});
function updateResultFooter(resultCount, pageIndex, pageCount)
{
if (pageIndex == 0)
$("#bnPreviousPage").attr('disabled', 'disabled');
else
$("#bnPreviousPage").removeAttr('disabled');
if ((pageIndex + 1) == pageCount)
$("#bnNextPage").attr('disabled', 'disabled');
else
$("#bnNextPage").removeAttr('disabled');
}
function doReverseSearch(telValue, pageIdx, methodUrl)
{
$.ajax(
{
url: methodUrl,
type: 'post',
data: JSON.stringify({ Telephone: telValue, pageIndex: pageIdx }),
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#result').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
}
Thank you in advance
Related
I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work
I know this may be a trivial question but I am just not able to get this ajax call to work..
View (html)
<div class="col-sm-6 col-xs-3 pl0" style="margin-left: -5px;">
<button class="btn btn-primary visible-xs" name="btn-callback"><i class="fa fa-arrow-right" aria-hidden="true"></i></button>
<button class="btn btn-primary hidden-xs" name="btnCallback" id="btnCallback"><i class="fa fa-arrow-right" aria-hidden="true"></i> Instant Callback
</button>
</div>
now I am placing a click event on btnCallback button
JQuery code
$('#btnCallback').click(function () {
var phone = document.forms["frm-callback"]["callphone"].value;
if (phone.length != 10) {
document.getElementById('errcallbackModal').innerHTML = "Enter 10 digit Phone number";
return false;
} else if (isNaN(phone)) {
document.getElementById('errcallbackModal').innerHTML = "Please Enter only number";
return false;
} else {
document.getElementById('errcallbackModal').innerHTML = "";
var randomnum = Math.floor(100000 + Math.random() * 900000)
randomnum = randomnum.toString().substring(0, 5);
var fullNumber = '0091' + phone;
url = '/ambulance/type2/sendOtp';
data = {
Code: randomnum,
MobNumber: fullNumber,
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(fullNumber);
$.ajax({
url: url,
data: data,
type: 'POST',
datatype: 'JSON',
success: function (response) {
if (response.status === true) {
console.log(response.message);
$('#myModalCallback').modal('toggle');
} else {
alert('Issue');
}
},
error: function (response) {
$('#errormessage').html(response.message);
}
});
}
});
</script>
web.php (routes)
Route::post('/ambulance/type2/sendOtp', 'AmbulanceController#sendOtp');
Controller
public function sendOtp()
{
$code = Input::get('Code');
$mobnum = Input::get('MobNumber');
//set otp code in session to verify
// session(['verifyOtp' => $code]);
// ParseCloud::run('sendcode', ["Code" => $code, 'MobNumber' => $mobnum]);
return Response::json(['status' => true, 'message' => 'OTP has been sent to your mobile number']);
}
It's not entering the success callback. There is some trivial mistake with the code but I am not able to figure it out.
Any assistance will be highly appreciated.
I tried the below code and it worked .. hope it helps somebody
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '<?= csrf_token() ?>'
}
});
$.ajax({
url: '/ambulance/type2/sendOtp',
data: {'Code': randomnum, 'MobNumber': fullNumber},
type: 'POST',
datatype: 'JSON',
success: function (response) {
if (response.status === true) {
console.log('success');
} else {
document.getElementById('errcallbackModalOtp').innerHTML = "Some error occured .. Please try again later";
// $('#errcallbackModalOtp').html('Some error occured .. Please try again later');
}
},
error: function (response) {
document.getElementById('errcallbackModalOtp').innerHTML = response.message;
// $('#errcallbackModalOtp').html(response.message);
}
});
try passing the csrf token in the header (this will only work inside a blade.php file)
also might be worth reading this http://engageinteractive.co.uk/blog/csrf-protection-with-ajax-and-laravel
or researching laravel csrf with ajax
$.ajax({
url: url,
headers: { 'csrftoken' : '{{ csrf_token() }}' },
data: JSON.stringify(data),
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (response) {
if (response.status === true) {
console.log(response.message);
$('#myModalCallback').modal('toggle');
} else {
alert('Issue');
}
},
error: function (response) {
$('#errormessage').html(response.message);
}
});
I wanted to just comment, but I can't, so please don't mark my answer as not useful.
You're being redirected and your controller does not give a redirect response. So maybe your route is wrapped into a middleware group redirecting in some cases?
Add contentType & JSON.stringify(). Try code written below.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(fullNumber);
$.ajax({
url: url,
data: JSON.stringify(data),
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (response) {
if (response.status === true) {
console.log(response.message);
$('#myModalCallback').modal('toggle');
} else {
alert('Issue');
}
},
error: function (response) {
$('#errormessage').html(response.message);
}
});
I want to run a function inside beforesend() in jquery ajax. Depending on the return value of that function I want to change the URL of ajax request. For an example refer below.
If myFunction() returns a value grater than 1, I want to run url1 otherwise I want to run url2. How to achieve that?
myFunction() gives a value grater than 1. But always ajax runs the url2.
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
myFunction($('#com').val())
},
url: (myFunction($('#com').val()) > 1) ? url1 : url2,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
try this
$.ajaxSetup({
beforeSend: function(jqXHR, settings) {
settings.url ="new Url";
}
});
Create a global variable something like:
var urlToSend;
and then assign it in beforeSend
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
urlToSend=myFunction($('#com').val()) > 1 ? url1 : url2;
},
url: urlToSend,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
$.ajax({
type: "POST",
data: {
fname: $('#com').val()
},
dataType: "json",
beforeSend: function () {
url = myFunction(parseInt($('#com').val())) > 1 ? url1 : url2;
},
url: url,
success: function (data) {
if (data == 'success') {
window.location.href = 'index.php?r=site/index';
} else {
alert("Already registered email");
}
},
failure: function (errMsg) {
alert(errMsg);
}
});
I'm working with jQuery UI Auto Complete extenders for populating list.
Here i include this article for more reference of my code detail.
Here I modify method for auto complete. In article this calls from css class and I want from the ID of the control.
This is my jQuery script :
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#<%=txt_reason.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#<%=txt_reason.ClientID %>").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
And this is my method:
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
[System.Web.Services.WebMethod]
public static List<string> SearchReasons(string prefixText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
var query = db.Reasons.Where(r => r.ReasonText.Contains(prefixText)).Select(r => r).ToList();
List<string> reasons = new List<string>();
foreach (var item in query)
{
reasons.Add(item.ReasonText.ToString());
}
return reasons;
}
}
The problem is not detecting this textbox not displaying result.
Use this
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("#txt_reason").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Raise_Ticket.aspx/SearchReasons",
data: "{'prefixText':'" + $("#txt_reason").val() + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
Using this you can also try
$(document).ready(function () {
$("#textbox").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (retrieveddata) {
if (retrieveddata.length > 0) {
}
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
Take Tern Variable in Code
I using the mvc controller with ajax. I perfom the task using the jquery confirm box. when i click the "ok" button its needs to the call another ajax and its link to the another controller but its not working
Sample code:
function button_click() {
$.ajax({
type: 'POST',
url: 'url',
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { call(data); }
else { alert(data.data); }
}
});
}
function call(data)
{
var ans = confirm(data)
if(ans)
{
$.ajax({
type: 'POST',
url: '#(Url.Action("StudentList", new { Area = "Mec", Controller = "HOD" }))',, // this url not goes to the controller
data: {data},
dataType: 'json',
success: function (data) {
if (data.success == true) { alert(data.data); }
else { }
}
});
} else { }
}
i have tried your code but it worked for me.the difference is that
you need to pass data in correct format. data:data or data:{ data:data } but not data:{data}
function button_click() {
$.ajax({
type: 'POST',
url: 'Demo/Demo_action',
data: { data: "what you want to pass" },
//dataType: 'json',
//contentType: 'application/json',
success: function (data) {
if (data == "hello") {
call(data);
}
}
});
}
function call(data) {
var ans = confirm(data)
if (ans) {
$.ajax({
type: 'POST',
url: '#(Url.Action("Demo_action2", new { Area = "Mec", Controller = "Home" }))',
//url: 'Home/Demo_action2', // this url not goes to the controller
data: { data: data },
dataType: 'json',
success: function (data) {
alert(data);
}
});
}
else
{ }
}