Form validation in codeigniter when ajax used to form submit - ajax

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..!');
}
});
}

Related

How to send data from ajax to controller

I want to transfer data to the controller using ajax. Here is the ajax code
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
name2:"admin",
_token: $("input[name='_token']").val()
}
})
});
Here is the code in the controller
public function insert_db(Request $request)
{
dd($request->all());
}
Here is the layout code
<form action="/insert_" method="post">
#csrf
<input type="submit" id="bt1" value="do it">
</form>
Here is code в web.php
Route::post('/insert_',"StudentController#insert_db");
Displays this
Why does display this? Please help
Your jquery ajax request should look like below:
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
"name":"test",
_token: $("input[name='_token']").val()
}
})
});
or
$(document).on("click", '#bt1', function(e)
{
var payload = JSON.stringify({
'name': 'test',
'_token': $("input[name='_token']").val()
});
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:payload
})
});
There is nothing wrong with your code, but i will love to get the string part by coding it like this
$(document).on("click", '#bt1', function(e)
{
e.preventDefault();
$.ajax({
url:"/insert_",
type:"post",
data:{
"name2":"admin",
_token: $("input[name='_token']").val()
}
})
});
noticed that i changed name2:"admin" to "name2":"admin"

token mismatching ajax in Laravel

$('#id').change(function(){
var a = $('#id_one').val();
var token = '<?php echo csrf_token(); ?>';
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
This is my code.
Getting token mismatch error..!!
I have tried both of the following..
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<script type="text/javascript">
var _globalObj = {{ json_encode(array('_token'=> csrf_token())) }}
Can any one help ??
You can utilize your token from the blade template, just declare your session token in the blade file of your view under the script tag like this:
<script> var token = '{{ Session::token() }}'; </script>
and call the token in ajax, in your code it will be something like this:
$('#id').change(function(){
var a = $('#id_one').val();
$.ajax({
url: "url",
type: 'POST',
data: {'id':a,'_token':token},
success: function(data)
{
// some code
}
});
})
Possibly because the token field name should be _token and not token
Also If this javascript code in a separate javascript file then php function will not work.
Also if the data you are trying to send is of a form then you can do this
$('#id').change(function(){
var data = $("#form").serialize() ;
$.ajax({
url: "url",
type: 'POST',
data: data,
success: function(data)
{
// some code
}
});
})
where your form looks like
<form id="form">
<input type='hidden' value='{{ csrf_token() }}' name='_token'>
<input type="text" name='id'>
</form>
$.ajax({
url: someurl,
type: 'POST',
data : formData,
headers: {
"x-csrf-token": $("#token").data('id')
}
});
}
and in your html
<div id="token" data-id="{!! csrf_token() !!}"></div>

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/

Sending AJAX request before submitting the form

Problem: I'm trying to send ajax reguest, and then submit the form.
Aproaches:
1. I solved the problem by putting
success: function() {
document.myform.submit();
}
But i think it's not the most elegant solution. Can you explain me why it works only if i put document.myform.submit(); in success? Is there any other way to solve this problem?
<div class="buttons">
<div class="right">
<form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get">
<input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>">
<input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" />
</form>
</div>
</div>
<script type="text/javascript">
function startAjax() {
console.log("dafaaaa");
$.ajax({
type: 'get',
url: 'index.php?route=payment/bank_transfer/confirm',
async: 'false',
success: function() {
// location = '<?php echo $continue; ?>';
}
});
} // Calls ajaxComplete() when finished
function ajaxComplete()
{
console.log("dafa");
document.myform.submit();
}
</script>
success's function is called upon the get request receiving a valid response as #harsh pointed out. Thus it will occur after the get request. I believe something similar to the following would do as you request though I haven't tested it:
<script type="text/javascript">
$(function () {
$("#form").on('submit', function () {
var $form = $(this);
$.ajax({
type: 'GET',
url: 'index.php?route=payment/bank_transfer/confirm',
data: $form.serialize(),
async: 'false',
success: function () {
$.ajax({
type: 'GET',
url: 'https://example.com/payment.php',
data: $form.serialize(),
});
}
});
});
});
</script>

Jquery .ajax() function not returning values from codeigniter controller

I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});

Resources