Data not passing in ajax call in Codeigniter - ajax

I am sending a file through ajax. Instead of passing the csrf token its not available in the controller
Bellow is code
<script type="text/javascript">
var csrfName = '<?php echo $this->security->get_csrf_token_name(); ?>',
csrfHash = '<?php echo $this->security->get_csrf_hash(); ?>';
$(document).on("change","#channel_setup_file",function(e){
var formData = new FormData($("#process-form")[0]);
$.ajax({
url: "<?php echo site_url('parse-setup-file')?>",
type: "POST",
data: {cform : formData,csrfName:csrfHash},
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
error: function(msg){
},
success: function(msg){
}
});
});
</script>
I am getting only the url in the controller.

Expecting that you are getting both token and name so in context to that I am writing the code
var formData = new FormData($("#process-form")[0]);
$.ajax({
url: "<?php echo site_url('parse-setup-file')?>",
type: "POST",
data: {cform : formData,cName:csrfName,cToken:csrfHash},
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
error: function(msg){
},
success: function(msg){
}
});

Related

Second ajax call return 404

My second ajax call starts only when the first succeeded. The problem, the second ajax call return 404 error code. Find below the code.
Can anyone help troubleshooting ? Thanks a lot
$.ajax({
contentType: 'application/json',
type: 'GET',
url: '${pageContext.request.contextPath}/transaction/status/'+$("#telephone").val()+'/'+$("#transref").val(),
dataType : 'json',
cache: false,
error: function(xhr,error,textStatus){
console.log(error);
},
success: function(data) {
console.log(data)
if(data.transfertResponseCode == '01'){
$('#statut').empty();$('#statut').append('<div class="row"><div class="col-md-2 col-sm-2"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span></div><div class="col-md-10 col-sm-10">Transaction en cours de traitement.... Veuillez patienter quelques instants</div></div>');
}else if(data.transfertResponseCode == '00'){
var data = {"msisdn":$("#telephone").val(), "amount":$("#montant").val(), "transref":$("#transref").val(), "clientid":$("#clientID").val()};
$.ajax({
contentType: 'application/json',
url: 'http://74.208.84.251:8221/QosicBridge/user/deposit',
type: 'POST',
data : JSON.stringify(data),
dataType : 'json',
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('USR28' + ":" + 'YG739G5XFVPYYV4ADJVW'));
},
error: function(xhr,error,textStatus){
console.log(error);
},
complete: function(data) {},
success: function (data) {
console.log(data);
}
});
}
}
});

Form validation in codeigniter when ajax used to form submit

Form submit is not happened in this scenario..
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
In your view you can add this:
<script type="text/javascript">
var base_url = "<?php print base_url(); ?>";
</script>
Plus try to alert and see the value of final url in ajax i.e alert(url);
Try adding a id to the firstname input
<script type="text/javascript">
$(document).on('submit','#form-reg',function(){ // #form-reg is id on form open tag
$.ajax({
url: "<?php echo base_url('register/registration_val');?>",
type: 'POST',
data: {
firstname: $('#firstname').val(),
},
dataType: 'html', // I perfer to use json
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
}
});
});
</script>
I would use dataType: json much easier that way to get data from controller
You used data: "register_first_name="+first_name, it's not correct. Correction is data: {register_first_name:first_name},
base_url like this var base_url = <?php echo base_url(); ?>
So, Bellow final code :
<script type="text/javascript">
jQuery(document).ready(function ($) {
var base_url = <?php echo base_url(); ?>
$.ajax({
url: base_url+"register/registration_val", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {register_first_name:first_name}, // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
}).done(function (data) {
$('#inferiz').html(data);
}).fail(function (data) {
console.log('failed');
});
}(jQuery));
</script>
Please verify your view part that whether you provided id same as in ajax function.
view part:
<form id="form-reg">
<input name="firstname" id="firstname" type="text" required placeholder="Enter firstname " >
<span id="name_validation" class="text-danger"></span>
<button name="submit" id="submit_button" onClick="myFunction();" >submit</button>
</form>
Then correct the base url path which has to be given inside php tag.
function myFunction() {
$.ajax({
url: "<?php echo base_url();?>register/registration_val",
type: "POST",
data:'firstname='+$("#firstname").val(),
success: function(msg)
{
alert('done..!');
}
});
}

how to send csrf token through ajax call in laravel?

i have a form with method=post.In that form i have an image upload field which is ajax.when the ajax call process,verify csrf token mismatch error occure.help me.this is my code..,
<script>
$(document).ready(function(){
$(document).on("click", "#upload", function() {
var file_data = $("#groupe_img").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("csrftoken",document.mainform.csrftoken.value;) // Adding extra parameters to form_data
$.ajax({
url: "/upload_avatar",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post'
})
})
});
</script>
this is my html portion
<input type="file" name="groupe_img" id="groupe_img">
<button id="upload" value="Upload">upload image</button>
tysm
First add csrf token to a meta tag like this (in main layout for example: resources/views/default.blade.php in head section):
<meta name="_token" content="{{ csrf_token() }}"/>
Then use $.ajaxSetup before ajax call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: "/upload_avatar",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post'
})

jquery ajax web method call

I am trying to call ajax web method when button is clicked. This is the following code I have written.
$(function() {
$("<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: '{rating: \'' + textrating.val() + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {
},
error: function throwError(data) {
},
});
});
This is asp button I am using
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClick="btnBack_Click" />
The code behind is
[WebMethod]
[ScriptMethod]
public static void SubmitRatings(string rating)
{
if (HttpContext.Current.Request.QueryString["ID"] != null)
{
if (HttpContext.Current.Session["LoginId"] != null)
{
string str = HttpContext.Current.Request.Form["lblRate"];
RatingsBAL bal = new RatingsBAL();
bal.StoreRatings(HttpContext.Current.Session["LoginId"].ToString(), HttpContext.Current.Request.QueryString["ID"], Convert.ToInt32(rating));
}
}
}
But for some reason the web method is not being fired. Can anyone help me please? Thanks in advance.
Change $("<%=btnRatingSubmit.ClientID%>").click to
$('#'+"<%=btnRatingSubmit.ClientID%>").click
You were missing a #, which is used to select elements by their ids in jquery.
Full Code:
$(function () {
$('#' + "<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
});
function Functioncall(){
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
}
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClientClick="Functioncall()" />

how to codeigniter ajax get data?

HTML
<div id="tabs">
<ul id="category">
<li><a href='#' class='cate' id='3'>3</a></li></br>
</ul>
</div>
Jquery
$(function() {
$(".cate").click(function()
{
var user_id = $(this).attr("id");
$.ajax({
type: "GET",
url: "<?php echo base_url('workplace/'.$username.'/menu') ?>",
data: user_id,
success: function(result){
$("#category-details").html(result);
}
});
});});
but in url is : localhost/project/workplace/test/menu?3
how to make : localhost/project/workplace/test/menu/3
Try replace
url: "<?php echo base_url('workplace/'.$username.'/menu') ?>",
this
url: "<?php echo base_url('workplace/'.$username.'/menu/') ?>" + user_id,
but it isn't best solution.
If you want to remove the ?3 from the URL, use a POST instead of a GET:
jQuery.ajax({
type: "POST",
url: "<?php echo base_url('workplace/'.$username.'/menu') ?>",
data: user_id,
error : function(result){
// Do something here to see what the problem is
// maybe console.log(result);
},
success : function(result){
$("#category-details").html(result);
}
});
This will make the URL localhost/project/workplace/test/menu/

Resources