I try to test the controller validation without ajax and it worked.
I try to test ajax out side form validation and it work.
but when I try to get form validation result in ajax it not work.
Tris is my controller
function ajax_form() {
$this->load->helper('form');
$this->load->view('ajax/ajax_input');
}
function test() {
$this->load->library('form_validation');
$this->form_validation->set_rules('myname', 'Name', 'required');
if ($this->form_validation->run() == TRUE) {
echo 1;
} else {
echo validation_errors();
}
}
This is my view
<div id="test"></div>
<?php
echo form_open('ajax/test', array('id'=>'sub'));
echo form_input('myname');
echo form_submit('submit','Submit');
echo form_close();
?>
<script>
$(document).ready(function(){
$('#sub').submit(function(event){
event.preventDefault();
$.ajax({
url:'test',
type:'POST',
data:{myname:$('#myname').val()},
success:function(data)
{
console.log(data);
}
});// end ajax
});//end btn click
});//end ready
</script>
I already spent 3 hours try to fix this but still not work. Hope u guy can help.
Update type.
Related
I have a simple app in codeigniter. In my view I have ajax POST request to the controller, but I don't receive response data. I checked in the chrome dev tool in network tab the response and the message is: No response data available for this request :
My view:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>First</td>
<td>Sec</td>
<td>Th</td>
<td>Th</td>
</tr>
</thead>
<tbody>
<?php
if(isset($result))
{
foreach($result as $value)
{
echo "<tr><td>". $value->cai . "</td><td>". $value->partner ."</td><td>". $value->spot ."</td><td><button type='button' id='".$value->cai."' class='btn btn-danger delete'>Delete</button></td></tr>";
}
}
?>
</tbody>
</table>
<?php echo $this->pagination_bootstrap->render(); ?>
<script>
$('.table').on('click','.delete',function(){
var id=$(this).attr('id');
var confirm_box=confirm('Sure?');
if(confirm_box === true)
{
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
type: 'POST',
data: {
key: id
},
dataType: 'json',
success: function(data) {
console.log(JSON.parse(data));
}
});
}
});
</script>
My controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Tires_Crud extends MY_Controller
{
public function deleteCai()
{
$status = array(
"STATUS" => "true"
);
return json_encode($status);
}
}
In my config file CSRF protection is DISABLED! Because when its enabled the ajax request is not working. Thanks for your help in advance!
Some issues with this code.
#1: The way you're forming the ajax request. Where you have type: 'POST' should be method: 'POST' - but more than a typo, it's important that you understand these are referred to as the HTTP method - same way you'd specify that in a <form method='post' tag. If you don't provide a method, it's assumed to be GET.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
Also, because you specified dataType:'json' - jquery will deliver a ready to use parsed JSON object. No need for you to parse it yourself
$.ajax({
url: '<?php echo site_url('Tires_Crud/deleteCai'); ?>',
method: 'POST', // <-- change this from 'type' to 'method'
data: {
key: id
},
dataType: 'json',
success: function(data) {
// console.log(JSON.parse(data)); // <-- no need to parse - you have set dataType to be json, which means it will come to you already parsed
console.log(data);
})
#2 - In your PHP, you'd catch your key variable (you sent in ajax) with $_POST['key'] - though in codeigniter you get it like this:
// codeigniter 2.x and 3.x
$this->input->post('key');
// codeigniter 4
use CodeIgniter\HTTP\IncomingRequest;
$request = service('request');
$request->getPost('key');
#3 - With ajax, you actually echo the response, rather than return it:
public function deleteCai(){
$status = array(
"STATUS" => "true"
);
echo json_encode($status);
}
I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);
ajax code
function autocomplet(){
var countryname= $('#countrysearch').val();
$.ajax({
type: 'POST',
url: 'My_commonlib', // My_commonlib is library file in library folder
data: "countryname=" + countryname,
success: function(data){
}
});
}
html code
<input type="text" onkeyup="autocomplet()" class="inputs form-control " style=" border-bottom: .5px solid;" id="countrysearch" name="countrysearch" placeholder=" Search">
I send a request to My_commonlib in library folder
php code
Pass ajax request to this class My_commonlib or method getcountry
class My_commonlib {
private $ci;
public function __construct()
{
$this->ci=& get_instance();
$this->ci->load->database();
// parent::__construct();
}
function getcountry(){
$this->ci->db->from('countries');
$this->ci->db->order_by("country", "ASC");
return $this->ci->db->get()->result();
}
}
and get in view file as
$a = new My_commonlib();
$results=$a->getcountry();
foreach ($results as $row)
{ ?>
<?php echo $row->country ; ?><br>
<?php }
?>
Change :
url: 'My_commonlib',
to
url: '<?php echo base_url('My_commonlib/getcountry');?>',
CodeIgniter uses the url to decide which controller to load. You will always handle requests with a controller. The controller can be a very thin object that loads the library and passes the request on to it.
I'm setting up a plugin. Now I'm trying to get an AJAX-PHP code working but I don't get the succeed data and all end with an error.
tracker.php is the main plugin file.
This is the function on my tracker.php that prints the title and some HTML code:
require_once dirname(__FILE__) . '/user-listing.php';
function trez_tracker_user_listing(){
?>
<h1>Tracker - User List</h1>
<div class="clicker">Click here</div>
<div id="printer"></div>
<?php
}//trez_tracker_user_listing
So in user-listing.php I added the following code:
function user_listing_enqueuer() {
wp_register_script( "ajax_user_request", WP_PLUGIN_URL.'/tracker/script/ajax_user_request.js', array('jquery') );
wp_localize_script( 'ajax_user_request', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_user_request' );
}
add_action( 'init', 'user_listing_enqueuer' );
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
add_action("wp_ajax_user_fetcher", "user_fetcher");
And finally the javascript code in /script/ajax_user_request.js:
/* ajax_user_request.js */
jQuery(document).ready( function() {
jQuery(".clicker").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "user_fetcher"},
success: function(response) {
if(response.type == "success") {
jQuery("#printer").html(response)
}
else {
alert("AJAX error")
}
}//success
})//jQuery.ajax
})//Clicker function
})//document ready
When clicking on the <div>, I just get the alert message "AJAX error".
How can I fix it?
Thank you!
You are getting the error because you are not returning the JSON data, you are return string through your user_fetcher function.
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
Change the user_fetcher function so that it will return the JSON data to the AJAX call.
function user_fetcher(){
$result = 'Message to display';
echo json_encode(array('type'=>'success', 'message'=>$result));
die(0);
}//user_listing
And in jquery check the response like this:
success: function(response) {
if(response.type == "success") {
// Add message
jQuery("#printer").html(response.message)
}
else {
alert("AJAX error")
}
}//success
For the hook wp_ajax_user_fetcher, make sure you are using this after logged in, if you are not logged in in the admin section then you have to use wp_ajax_nopriv_user_fetcher. Or you can use both:
// Work if user is login
add_action("wp_ajax_user_fetcher", "user_fetcher");
// Work if user is not login
add_action("wp_ajax_nopriv_user_fetcher", "user_fetcher");
I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:
//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>
//after the form
<script type="text/javascript">
function check_username(un) {
$.ajax({
type: 'POST',
url: '/oes/users/check_username',
data: {username:un},
cache: false,
dataType: 'HTML',
beforeSend: function(){
$('#na').html('Checking...');
},
success: function (html){
$('#na').val(html);
}
});
}
</script>
//and my check_username() is
public function check_username(){
return 'Test string';
}
But this isn't working. Anybody know why or how to modify it so that it works?
It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.
This method is recommended for your needs, but not obligated, of course.
Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:
public function check_username(){
$this->autoRender = false;
echo 'Test string';
}
Also, try not to use such code construction in the future.
CakePHP has a JS Helper to help write aJax functions. The only catch is to include jquery in your head our cake will throw jQuery errors.
Your Form:
<?php
echo $this->Form->create('User', array('default'=>false, 'id'=>'YourForm'));
echo $this->Form->input('username');
echo $this->Form->submit('Check Username');
echo $this->Form->end();
?>
The Ajax Function:
<?php
$data = $this->Js->get('#YourForm')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#YourForm')->event(
'submit',
$this->Js->request(
array('action' => 'checkUsername', 'controller' => 'user'),
array(
'update' => '#na',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST'
)
)
);
echo $this->Js->writeBuffer();
?>
The Function in User Controller
function checkUsername(){
$this->autoRender = false;
//run your query here
if ( $username == true )
echo 'Username is taken';
else
echo 'Username is not taken';
}
There are many examples through google. Here is a good one to visit.