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);
}
});
Related
I get an 405 (Method Not Allowed) error when sending an AJAX request. I've been working hard looking for a solution but still receive the same error.
I have added this inside the header section:
<meta name="csrf-token" content="{{ csrf_token() }}">
And this is the AJAX code:
function AjaxCall() {
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'insertNum',
type: 'POST',
dataType: 'json',
header: {
'X-CSRF-TOKEN': token
},
data: {
_token: token,
_method: "PUT",
},
success: function() {
console.log('success');
}
});
}
Laravel code:
try {
$lastNum = DB::table('no_antrian')->select('antrian')->first();
if (!is_null($lastNum))
{
$data = DB::table('no_antrian')->update(['antrian' => $lastNum + 1]);
}
return response()->json(['success' => 'Sukses']);
}
catch(\Exception $e) {
return response()->json(['error' => 'failed']);
}
Route:
Route::post('antrian/insertNum', [AntrianController::class, 'getQueueNum']);
please Remove put method inside data
var token = $('meta[name="csrf-token"]').attr('content');
let myData = $('form').find('input[name="my_data"]').val();
$.ajax({
url: 'insertNum',
type: 'POST',
dataType: 'json',
data: {
_token: token,
my_data: myData
},
success: function() {
console.log('success');
}
});
Trying to hit DeleteJobQuote controller through Ajax but no luck. Please guide me if anyone has any idea about it. The code seems OK but not able to do so. I am writing this code to delete a particular record from database.
Controller
[HttpPost]
public ActionResult DeleteJobQuote(int jobQuoteid)
{
using (var db = new KeysEntities())
{
var delJob = db.JobQuote.FirstOrDefault(x => x.Id == jobQuoteid);
if (delJob != null)
{
delJob.Status = "Delete";
db.SaveChanges();
return Json(new { success = true, Message = "JobQuote SuccessFully Deleted!" });
}
else
{
return Json(new { success = false, Message = "Delete UnSuccessFul " });
}
}
}
And JavaScript and Knockout code for this
self.deleteJobQuote = function (jobQuote) {
debugger;
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});
};
Change "data : ko.toJSON(this)" to "data: JSON.stringify({ jobQuoteid: 1 })". I have hardcoded jobQuoteid value to 1. Get it from jobQoute object.
complete code:
$.ajax({
url: '/Companies/Manage/DeleteJobQuote',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ jobQuoteid: 1 }),
contentType: 'application/json',
success: function (result) {
if (result.success) {
$('#jobQuoteDeleteModal').modal('show');
}
else {
alert("You can not delete this record !!");
}
}
});
This is the UI of the demo Application.
I am sending an ajax request to the controller which is verifying the user id and password from the getloginuser method ,the response is coming. I just want to redirect it after successful login to some other page. Can i do anything in callback (jquery).i searched lot of things on net but could not get suitable answer.
Login Image
This is the jquery code
//method
function Login()
{
var res = LoginValidation()
if (res == false)
{ return false; }
var logininfo = {
Username: $('#Username1').val(),
PasswordHash: $('#PasswordHash1').val(),
};
$.ajax({
url: "/Home/Login",
data: JSON.stringify(logininfo),
type: "Post",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//loadData();
$('#myModal1').modal('hide');
alert('Login Successful');
},
error: function (result)
{
$('#myModal1').modal('hide');
alert("Invalid Credentials");
}
});
This is the Login Controller Method:
public JsonResult Login(User info)
{
return Json(obj.GetLoginUser(info), JsonRequestBehavior.AllowGet);
}
You can do in your ajax function like this:
var res = LoginValidation()
if (res == false)
{ return false; }
var logininfo = {
Username: $('#Username1').val(),
PasswordHash: $('#PasswordHash1').val(),
};
$.ajax({
url: "/Home/Login",
data: JSON.stringify(logininfo),
type: "Post",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//loadData();
if(result != null || result != "")
{
window.location.href= "Your redirect url";
}
else
{
alert("login error");
return false;
}
},
error: function (result)
{
$('#myModal1').modal('hide');
alert("Invalid Credentials");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use window.location to redirect to any location your application. Just Implement it in the success part of your Ajax call.
function Login()
{
var res = LoginValidation()
if (res == false)
{ return false; }
var logininfo = {
Username: $('#Username1').val(),
PasswordHash: $('#PasswordHash1').val(),
};
$.ajax({
url: "/Home/Login",
data: JSON.stringify(logininfo),
type: "Post",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
//loadData();
$('#myModal1').modal('hide');
RedirectToPage();
},
error: function (result)
{
$('#myModal1').modal('hide');
alert("Invalid Credentials");
}
});
function RedirectToPage()
{
window.location='Your Link Goes here';
}
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 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