How to get data from controller to view using ajax in codeigniter - ajax

View:
<select class="form-control" id="emp_id" name="emp_id">
<option value="">--- Select Emp id ---</option>
<?php foreach($employee as $emp){?>
<option value="<?php echo $emp->id;?>"><?php echo $emp->id;?></option>
<?php }?>
</select>
<div id="home"></div>
<script>
$('select[name="emp_id"]').on('change', function() {
var id=$("#emp_id").val();
$.ajax({
url: "<?php echo base_url(); ?>/employee_master"+id,
dataType: 'json',
type: 'post',
success: function(data) {
alert("hi");
console.log(data.res);
},
error: function( error )
{
alert( error );
}
});
return false;
});
</script>
Controller:
public function employee_master($id)
{
$data['res']=$this->payslip_model->fetch_employee_name($id);
echo json_encode($data);
}
Model:
public function fetch_employee_name($id)
{
$this->db->select('name');
$this->db->from('employee_master');
$this->db->where('id',$id);
$res=$this->db->get();
return $res->result();
}
In above code,I am using dataType:'json' in ajax, it will always execute error function in ajax.If I am not using dataType:'json' it works fine, but I cannot know how to retrieve the data from controller to ajax.Please help me to find out the error.

yes it will give you error when you use data type json. it means that on ajax call the data will be pass to controller in json format..
while you are passing a simple post data...
remove the datatype json. every thing is ok...
and more mistake use this line
url: "<?php echo base_url(); ?>/contorller_name/employee_master/"+id,

Related

405 (Method Not Allowed) error on ajax in Laravel 8

I am trying to call an ajax function in my Laravel 8 Project. But on every call I am getting error POST http://127.0.0.1:8000/getReasonForVisit 405 (Method Not Allowed). I have tried many options like changing post method to get, change url etc. but no use. It would be helpful if someone can help me.
Here is my code.
JS File
function getReasonForVisit(catId) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
}
$('#treatment-category').on('change', function (){
var catId = $(this).val();
getReasonForVisit(catId);
});
View
<select class="form-control form-select" name="category" id="treatment-category">
<?php $categories = App::make("App\Http\Controllers\AppointmentsController")->getTreatmentCategories(); ?>
#foreach($categories as $cat)
<option value="{{ $cat->id }}">{{ $cat->category_name }}</option>
#endforeach
</select>
Route
Route::post('/getReasonForVisit', [App\Http\Controllers\AppointmentsController::class, 'getReasonForVisit'])->name('getReasonForVisit');
Controller
class AppointmentsController extends Controller
{
public function getTreatmentCategories() {
$categories = DB::table('treatment_category')->get();
return $categories;
}
public function getReasonForVisit() {
echo 111;
}
}
EDIT
I did cleared my route cache. now it's showing error CSRF token mismatch
Please change option type to method
$.ajax({
method: 'POST',
url : '/getReasonForVisit',
data : {'catId' : catId },
dataType: 'json',
success:function(data) {
console.log(data);
}
});
I resolved my issue. Actually I am missing csrf meta tag in my blade. So Now I added this code in view blade file in the <head> tag.
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>

Update meta_key with ajax in Wordpress

I want to update meta_key with ajax in wordpress i use this form
this is my code but not work for me
<?php
add_action( 'wp_head', 'ajax_the_clike' );
function ajax_the_clike() {
?>
<script>
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var formd = "#like";
$(formd).submit(function(event) {
event.preventDefault();
$.ajax({
url: $(formd).attr('action'),
type: $(formd).attr('method'),
data: $(formd).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
</script>
<?php
}
add_action('wp_ajax_the_clike', 'the_clike'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_the_clike', 'the_clike');
function the_clike() {
echo '<form action="'.site_url() .'/wp-admin/admin-ajax.php" method="post" id="like">';
echo '<input type="submit" value="VoteUp" id="submit" name="submits">';
if(isset($_POST['submits'])){
$postsid = get_the_ID();
$addone = get_field('like');
$addone++;
update_field('field_5f009fe6d7067' ,$addone, $postsid);
}
echo '</form><p> Like : '; if(get_field('like')) { the_field('like');}else{echo '0';} echo '</p>';
}
?>
I using a Advanced custom field plugin
Where is wrong? How do I solve this problem?
Thanks for any help

Select2 event after ajax replace

I'm trying to create filters using a Select2 dropdown and I do not know why the Select2:select event stop working after updating the html with the data that comes via Ajax.
Please help - My PHP is:
<div class="select-yellow fecha-container">
<select id="fecha" class="select2 fecha-addon" data-minimum-results-for-search="Infinity">
<?php foreach($fechas as $fecha): ?>
<option value="<?php echo $fecha; ?>"><?php echo formatDate($fecha); ?></option>
<?php endforeach; ?>
</select>
</div>
The JS file:
$('#fecha').on("select2:select", function(e) {
// here it's working
var fecha = $('#fecha').val();
var provincia = $('#provincia').val();
var request = $.ajax({
url: app.base_url + "/ajax-gallery/",
method: "GET",
data: {
provincia: provincia,
fecha: fecha,
tag: provincia
},
dataType: "html"
});
request.done(function (msg) {
if($.trim(msg).length) {
$('.gallery-container').html(msg);
var $filter = $('.gallery-container').find('.fecha-addon');
$('.fecha-container').html($filter);
$("#fecha option").each(function(){
if($(this).val()==fecha){
$(this).attr("selected","selected");
}
});
$('#fecha').select2({
minimumResultsForSearch: -1
});
//after rebind the event doesn't work
}else{
$('#gallery-notices').html('<strong>No hay más imagenes con esta fecha</strong>');
}
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

cross-domain form post with ajax jsonp returns error: {"readyState":4,"status":200,"statusText":"success"}

I'm trying to post form data to a php file that will then handle a mysql request. But before I do the mysql, I'm trying to connect to the php file.
The request is Cross-Domain.
When i submit the form, i get the error: {"readyState":4,"status":200,"statusText":"success"}
You can see the test page here: http://jonathan-tapia.mybigcommerce.com/store-locator/
form code:
<div class="map-search">
<h1>Give us your zip code. We'll tell you where to find us.</h1>
<div id="map-form">
<form id="lookup-form" action="http://dev.visioncourse.com/customers/baldguy/index.php" method="post">
<p>Within
<select id="distance" name="distance">
<option value="10">10</option>
<option selected="selected" value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
miles of
<input id="zipcode" type="text" name="postalcode" value="" size="8" />
<input id="lookup" type="submit" value="Look Up" />
</p>
</form>
</div>
</div>
<div class="map-results"> </div>
updated JS:
<script type="text/javascript">// <![CDATA[
//submit form
$('#lookup-form').submit(function(event) {
event.preventDefault();
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
console.log('.\n..\n...\n....\nSubmitting Form\n....\n...\n..\n.');
$.ajax({
crossDomain: true,
type: 'POST',
url: link,
data: {
'distance': distance,
'postalcode': zipcode
},
dataType: 'jsonp',
error: function(data) {
console.log('error: ' + data);
},
success: function(data) {
console.log('success: ' + data);
},
xhrFields: {
withCredentials: true
}
});
});
// ]]>
updated php file:
<?php
$arr = array();
$distance = $_POST['distance']
$zip = $_POST['postalcode'];
if(isset($distance) && isset($zip)) {
array_push($arrr, {'d': $distance, 'z': $zip});
}
echo json_encode($arr);
?>
error i'm receiving from console:
GET http://dev.visioncourse.com/customers/baldguy/index.php?callback=jQuery17203092896034941077_1451698154204&distance=25&postalcode=85251 jquery.min.js:4
EDIT:
The php file will get the distance and zip code from the form and connect to a mysql database for a google maps store locator. so when a person submits the radius and the zip code it will display results. but all of this will be on the php file.
The file doing the form submission will submit the form, wait for the php to do it's work, then display the php file with the results
Try it with data: {"distance": distance, "zipcode": zipcode},.
In your code you insert the value of the variables twice instead of a name and a value.
Also, you need to send the zipcode with the name of 'postalcode'. Otherwise your phpscript wouldn't find it.
you can try this way:
javascript:
<script>
var formdata = $(this);
var link = formdata.attr('action');
var distance = $('#distance').val();
var zipcode = $('#zipcode').val();
$.ajax({
type: 'GET',
url: link,
data: {"distance": distance,"postalcode": zipcode},
async: false,
jsonpCallback: 'jsonp_callback',//name of function returned from php
contentType: "application/json",
dataType: 'jsonp',
success: function(r) {
console.log(r);
},
error: function(e) {
alert(e.message);
}
});
</script>
php:
<?php
$arr = array();
$distance = $_GET['distance'];//sample 123
$zip = $_GET['postalcode'];//sample 65455
if(isset($distance) && isset($zip)) {
$arr = array('d'=> $distance, 'z'=> $zip);
}
$json = 'jsonp_callback(';
$json .= json_encode($arr);
$json .= ');';
echo $json;
?>
response:
jsonp_callback({"d":123,"z":65455});

Resources