csrf token for ajax serialize data in codeigniter - javascript

I am putting csrf token for my all ajax call but I'm getting error 500 where I am passing serialize data and JSON data in my ajax call.
I included in my view page but it's not working and throwing an error.
$("#submit").on('click', function(e) {
e.preventDefault(); // prevent default form submit
if(validateCode()){
$.ajax({
url: 'verifyCode', // form action url
type: 'POST', // form submit method get/post
data: $('#frm').serialize(),
success: function (result) {
result = JSON.parse(result);
if(result.st == 1){
window.location.href="backupCode";
}
else{
$('#validCodeFormat').html("<span style='color:red'>Invalid authentication code.</span>");
}
},
error: function(e) {
}
});
}
});
var json='json={"age":"'+age+'","age1":"'+age1+'","afterTaxincome":"'+aftertaxincome+'","afterTaxincome2":"'+aftertaxincome2+'","annualSave":"'+annualSave+'","annualSave2":"'+annualSave2+'","liqInvest":"'+liqInvest+'","liqInvest2":"'+liqInvest2+'","nonliqassets":"'+nonliqassets+'","nonliqassets2":"'+nonliqassets2+'","totalLia":"'+totalLia+'","totalLia2":"'+totalLia2+'","savingsChange":"'+savingsChange+'","savingsChange2":"'+savingsChange2+'","preference":"'+preference+'","market":"'+market+'","mail":"'+mail+'","investorTypePage":"'+investortype+'"}';
//alert(json);
$.ajax({url: "questions/sendQuestions",
type: "POST",
data: json,
success: function(result){
},
error: function(xhr, status, errMsg) {
alert("error while fetching data from server.\nPlease try again.");
}
});

You might need to use $.ajaxSetup() before your AJAX calls:
<script type="text/javascript">
var csrf_token = {TOKEN};
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
}
});
</script>
I have needed this before when using Flask CSRF Protection.

Related

ajax not called..even alerts are not working

i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

MVC jQuery Ajax Post - can only get it to work with hard-coded values

So I have a basic controller accepting a post..
[HttpPost]
public ActionResult Submit(string postCost)
{
//Do stuff here before sending back redirect details...
return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") });
}
And I'm posting via jquery ajax method:
$.ajax({
url: partyURL,
dataType: 'json',
contentType: 'application/json', //charset=utf-8',
type: 'POST',
data: { postCost: postageCost}, //**This fails!**
//data: "{'postCost':'3.50'}", //**This works**
success: function (response) {
if (response.result == 'SoldOut') {
$("#soldOut").show();
}
else if (response.result == 'Redirect') {
//All good, onward to confirmation page
window.location = response.url;
}
},
error: function (xhr, status, error) {
// Error handling here
}
});
where the postageCost variable sent in when it fails returning status 500:
postageCost = '3.50';
postageCost = JSON.stringify(postageCost); //also fails with this
but if I hard-code the data definition as
data: "{'postCost':'3.50'}",
It works fine.
The key must therefore lie in what I'm doing with the data element?
you need to do
var datum = {'postCost': '3.50'};
data: JSON.stringify(datum), //Ajax call data

ajax Json return type not comming in success

I have following ajax call:
$.ajax({
type: "GET",
url: "/Company/validateForm",
dataType: "json",
data: {
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
},
success: function (responceMessage) {
alert(responceMessage);
if (responceMessage != "1") {
alert(responceMessage);
} else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});
I have made sure that call is going to server side and returning proper message in string format.
But when call from validateForm method on server side is returned, it directly goes to failure instead of success method.
I can't figure out what I'm doing wrong here.
Console is showing:
GET http://localhost:49273/Company/validateForm?txtCompanyName=+x&txtCompanyCon…ebsite=&txtZipcode=&txtCountry=&txtAddress1=&txtAddress2=&txtCompanyRegNo= 500 (Internal Server Error)
I just made cache:false in ajax and code worked.
It was as follows:
$.ajax({
type: "POST",
url: "/Company/validateForm",
cache:false,
dataType: "json",
data:
{
'txtCompanyName': txtCompanyName,
'txtCompanyContactPerson': txtCompanyContactPerson,
'txtCompanyPhone': txtCompanyPhone,
'txtCompanyFax': txtCompanyFax,
'txtCompanyEmail': txtCompanyEmail,
'txtCompanyWebsite': txtCompanyWebsite,
'txtZipcode': txtZipcode,
'txtCountry': txtCountry,
'txtAddress1': txtAddress1,
'txtAddress2': txtAddress2,
'txtCompanyRegNo': txtCompanyRegNo
}
,
success: function (responceMessage) {
if (responceMessage != "0") {
alert(responceMessage);
}
else {
saveCompanyInformation();
}
},
error: function () {
alert('failure');
}
});

Ajax Form Returns Error

I am trying to post a form through AJAX in Netsuite so that I could trigger an event after the form submit without actually reloading it.
Please help me out, I am a newbie with AJAX.
Here is the code
$('#du_joinnow').submit(function(e){
e.preventDefault(); //STOP default action
var formdata = $(this).serializeArray();
$.ajaxSubmit({
type: "POST",
url: "https://forms.na1.netsuite.com/app/site/crm/externalleadpage.nl?compid=XXXXXX&formid=1&h=XXXXXXXXXXXXXX"+ formdata,
data: formdata,
success:function(data, textStatus, jqXHR) {
$('#overlay').fadeIn(); //data: return data from server
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Ajax Call Failed.");//if fails
}
});
return false;
});
Instead of $.ajaxSubmit do $.ajax
Full Code:
$('#du_joinnow').submit(function (e) {
e.preventDefault(); //STOP default action
var formdata = $(this).serializeArray();
$.ajax({
type: "POST",
url: "https://forms.na1.netsuite.com/app/site/crm/externalleadpage.nl?compid=XXXXXX&formid=1&h=XXXXXXXXXXXXXX" + formdata,
data: formdata,
success: function (data, textStatus, jqXHR) {
$('#overlay').fadeIn(); //data: return data from server
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Ajax Call Failed."); //if fails
}
});
return false;
});
Try this,
$('#du_joinnow').submit(function(e){
e.preventDefault(); //STOP default action
var formdata = $(this).serializeArray();
$.ajax({
url:"https://forms.na1.netsuite.com/app/site/crm/externalleadpage.nl?compid=XXXXXX&formid=1&h=XXXXXXXXXXXXXX" + formdata,
type:"POST",
data: formdata,
complete:function(data) {
if (data.readyState == 4)
{
if (data.status == 200)
{
$('#overlay').fadeIn();
alert(data.responseText);
}
else
{
alert("Ajax Call Failed.");
alert(data.statusText);
}
}
}
});
return false;
});

Categories

Resources