how to get value by jQuery+Codeigniter and show in input field? - php

I got some problem about receive value from server , and show the value in input .
Sometimes, if I want to show the value in page, I will use the POST method, then set the input'ID in controller and model, and use foreach() in page you want to show , therefore the work is done.
But, if I want to show the value in input'field, how I need to do for it ?
I write some code for this and try to use AJAX receive and show in input, it's not working,can everybody help me to solve this problem , please....... Σ(  ̄□ ̄;)
I try to create a new model and a new page for it, there is a very simple form, the code is below:
view:kungfu.php
<div style="width:250px;float:left;">
<form id="pr_form" action="<?php echo site_url();?>/static_data/kungfu_act" method="post">
NUM:<input id="num" name="num" type="text" class="field_set"><br>
NAME:<input id="name" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" name="kungfu" type="text" class="field_set"><br>
</div>
<div style="float:left;">
<span id="loading" style="display:none">Loading!!</span><br>
<span id="complete" style="display:none">Complete!!</span>
</div>
<div style="clear:both;height:50px;padding-top:10px">
<input id="query" name="query" class="btn" type="button" value="QUERY">
</div>
</form>
</div>
model:pr_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pr_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
}
function pr_query()
{
$query=$this->db->get("kungfu_table");
return $query->result();
}
}
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_query()
{
$this->load->model("pr_model");
$data = array(
"kungfu" =>$this->pr_model->pr_query()
);
echo json_encode($data);
}
}
if I want to show the value in normal page , I will use foreach() but I don't know how to show in input, I try to use getjson() , but no working . can somebody teach me ?
// 2013/11/30 re-edit
dear Suleman:
I try to write some code about .ajax() , but I still got problem , the other section was the same , but the controller had be change :
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_maxquery()
{
$this->load->model("pr_model");
$data = $this->pr_model->pr_maxquery();
$max=json_encode($data);
echo $max;
}
}
model:pr_model.php
function pr_maxquery()
{
$this->db->select_max("num");
$maxquery=$this->db->get("kungfu_table");
return $maxquery->result();
}
and I try to edit a js file for .ajax(),but the Chrome console tell me "Uncaught ReferenceError: maxnum is not defined " , can you tell me how to edit it ?
$("#newone").click(function(){
$("#num").val(function(){
max_response = $.ajax({
type:"POST",
url:"<?php echo base_url()?>/static_data/kungfu_maxquery",
cache:false,
data: "num:"+maxnum
});
max_response.done(function(){
return maxnum;
});
});
});

Make sure your model data is available in view, If available then need to alter your inpup fields:
NUM:<input id="num" value="<?php echo $data_for_first_input_filed; ?>" name="num" type="text" class="field_set"><br>
NAME:<input id="name" value="<?php echo $data_for_second_input_filed; ?>" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" value="<?php echo $data_for_third_input_filed; ?>" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" value="<?php echo $data_for_forth_input_filed; ?>" name="kungfu" type="text" class="field_set"><br>
If you want to append data through AJAX, then here is sample code:
$("#newone").click(function(){
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
data: {
'num':maxnum
},
cache: false,
success: function(data) {
console.log(data);
$("#num").val(data['filed_name_returned']);
$("#name").val(data['filed_name_returned']);
$("#local").val(data['filed_name_returned']);
$("#kungfu").val(data['filed_name_returned']);
}
});
});
AJAX request is not a cheap call, we can get all the data in one request and can set that available data in success function. I do't know your table structure that' why I have appended one line extra console.log(data); that will show your returned data in console.

Related

WordPress and External API

I'm attempting to use an AJAX call to post to an external API. I primarily want to do this to protect the API Key from prying eyes, though I'm a little lost on where to go with this next.
I've defined the API Key in my WP_config.php file and am able to echo that back in a PHP file. I've created a PHP file that creates a shortcode and added it to my custom post page template. I'd like to call a PHP function to handle the AJAX request to obfuscate the API Key and return the result so I can then modify the interface to notify the user that the feedback has been received. The shortcode works well and the form is posting correctly based on the console.log.
This is my page-feedback.php plugin code at the moment but I don't know where to go next. I was investigating the WP Rest API but I don't need to leverage any the WP functionality for this. Can I reference this existing PHP file for handling posting to the API? How would I approach that?
// Initialization
defined('ABSPATH') or die('Unauthorized access.');
add_shortcode('page-feedback', 'page_feedback_shortcode');
add_action('wp_footer', 'load_scripts');
function page_feedback_shortcode()
{ ?>
<div class="page-feedback">
<form id="page-feedback-form__form">
<input name="page" type="hidden" value="<?php echo urlencode(get_the_permalink()) ?>" />
<input name="username" type="hidden" value="<?php echo wp_get_current_user()->user_login ?>" />
<input id="page-feedback-form-helpful" name="helpful" type="hidden" />
<p id="page-feedback-form-helpfulQuestion">Was this page helpful? <button type="submit">Yes</button> or <button type="submit">No</button></p>
</form>
</div>
<?php }
function load_scripts()
{ ?>
<script>
jQuery('#page-feedback-form__form').submit(function(event) {
event.preventDefault();
var form = jQuery(this).serialize();
console.log(form);
jQuery.ajax({
method: 'post',
url: '',
data: form,
success: function(response) {
console.log(response);
}
})
});
</script>
<?php }
?>

Codeigniter SQL table update with Ajax param not working

I hope someone can give me a hand because I've tried and tried to find the error with no luck, I'm trying to execute an update SQL statement which gets the values from a POST AJAX request and everything seems to work ok but the table's values doesn't get updated.
The App flow is like this (and it actually works, just without the data update):
In my view I have a button which detonates a modal window for the user to input values in 4 text fields, then the user can click on a button and it sends such values through a POST AjAX call, then the controller and the method takes care of the update, then the user is sent back to the same page where he/she originally clicked the button.
As additional information, paths are correct, the flow works correctly, the values are being sent correctly through the AJAX call to the controller but I'm lost from that point on... :S
Not sure what I'm doing wrong, any help is appreciated
// My View - HTML button //
<i class="fa fa-file fa-2x" aria-hidden="true" ></i>
// My View - HTML modal window code //
<div id="confirmation_box_service_report_additional_data" title="" style="display:none;">
<h1 align="center" style="color: #333333"><?php echo $this->lang->line('service_report_title') ?></h1><br />
<h2 align="center" style="color: #DF9E0A"><strong><?php echo $this->lang->line('project_service_comments') ?></strong></h2><br />
<form id="form_service_report_additional_data" name="form_service_report_additional_data" method="post" action="">
<table width="100%">
<tr>
<td width="45%" class="red_cell_background">
<div class="form-group">
<label for="client_images_comments"><?php echo $this->lang->line('client_images_comments') ?></label>
<textarea class="form-control" rows="5" id="client_images_comments"></textarea>
</div>
</td>
<td width="5%" class="purple_cell_background"> </td>
<td width="45%" class="purple_cell_background"><div class="form-group">
<label for="specialist_images_comments"><?php echo $this->lang->line('specialist_images_comments') ?></label>
<textarea name="specialist_images_comments" rows="5" class="form-control" id="specialist_images_comments"></textarea>
</div></td>
</tr>
<tr>
<td class="red_cell_background"><div class="form-group">
<label for="spare_parts_comments"><?php echo $this->lang->line('spare_parts_comments') ?></label>
<textarea name="spare_parts_comments" rows="5" class="form-control" id="spare_parts_comments"></textarea>
</div></td>
<td class="purple_cell_background"> </td>
<td class="purple_cell_background"><div class="form-group">
<label for="final_comments"><?php echo $this->lang->line('final_comments') ?></label>
<textarea name="final_comments" rows="5" class="form-control" id="final_comments"></textarea>
</div></td>
</tr>
</table>
</form>
</div>
// My Javascript modal window code //
function service_report_additional_data(jobId) {
$("#spare_parts_comments").val("<?php echo $jobDetails[0]['spare_parts_description']; ?>");
$("#confirmation_box_service_report_additional_data").dialog({
autoOpen: false,
resizable: false,
width: 900,
heightStyle: "content",
modal: true,
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
buttons: [
{
text: "<?php echo $this->lang->line('save_and_close'); ?>",
class: "btn btn-warning",
click: function() {
var clientImagesComments = $('#client_images_comments').val();
var technicianImagesComments = $('#specialist_images_comments').val();
var sparePartsDescription = $('#spare_parts_comments').val();
var finalThoughts = $('#final_comments').val();
//alert(finalThoughts)
servicereportadditionaldatasaving(jobId, clientImagesComments, technicianImagesComments, sparePartsDescription, finalThoughts);
},
},
{
text: "<?php echo $this->lang->line('Cancel'); ?>",
class: "btn btn-default",
click: function() {
$(this).dialog("close");
}
}
],
close: function() {
$(this).dialog("close");
}
});
$("#confirmation_box_service_report_additional_data").dialog('open');
}
//My AjAX call //
function servicereportadditionaldatasaving(jobId, clientImagesComments, technicianImagesComments, sparePartsDescription, finalThoughts) {
//alert(clientImagesComments)
$.ajax({
type: "POST",
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>",
data: {
'jobId': jobId,
'clientImagesComments': clientImagesComments,
'technicianImagesComments': technicianImagesComments,
'sparePartsDescription': sparePartsDescription,
'finalThoughts': finalThoughts
},
success: function (data){
//alert(data);
location.href = '<?php echo base_url() . DISPATCHERADMIN . '/myjob/details/' ?>' + jobId;
},
error: function (jqXHR, textStatus, errorThrown){
console.log('error:: ' + errorThrown);
}
});
}
// My Controller //
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Jobs extends CI_Controller {
public function __construct() {
// Construct the parent class
parent::__construct();
$this->lang->load('message', 'english'); // language file
$this->load->model('dispatcher/jobs_model');
}
public function servicereportadditionaldatasaving() {
$postData = $this->input->post();
$data = array(
'table_name' => 'jobs',
'job_id' => $postData['jobId'],
'client_images_comments' => $postData['clientImagesComments'],
'technician_images_comments' => $postData['technicianImagesComments'],
'spare_parts_description' => $postData['sparePartsDescription'],
'final_thoughts' => $postData['finalThoughts']
);
$this->jobs_model->update_job_service_report_additional_data($data);
}
}
?>
// My Model //
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Jobs_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function update_job_service_report_additional_data($data) {
extract($data);
$this->db->where("job_id", $job_id);
$success = $this->db->update($table_name, array('client_images_comments' => $client_images_comments,
'technician_images_comments' => $technician_images_comments,
'spare_parts_description' => $spare_parts_description,
'final_thoughts' => $final_thoughts
));
if($success) {
return $success;
} else {
return false;
}
}
}
?>
I found the answer myself, after many attempts of looking into the code here and there I found that the problem was at the Ajax call at the following line:
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>",
it was expecting an ID to be passed as part of the original URL as follows:
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>" + jobId,
To be honest I need to review my code more in detail but that was the issue, everything is working as expected.

Passing POST data from ionic framework to CodeIgniter Rest API

From last two days i'm try to post the data from my Ionic app to CodeIgniter rest api using $http. But my post data goes empty. I refere some link. But failed to seolve. Below is my code.
My ionic view
<div class="list">
<label class="item item-input item-md-label" placeholder="Username" highlight-color="balanced" type="text">
<input class="md-input" type="text" ng-model="user.name">
<span class="input-label">Username</span>
<div class="hightlight hightlight-calm"></div>
</label>
<label class="item item-input item-md-label" placeholder="Password" highlight-color="energized" type="password">
<input class="md-input" type="password" ng-model="user.password">
<span class="input-label">Password</span>
<div class="hightlight hightlight-calm"></div>
</label>
</div>
<div class="padding">
<button ng-click="doLogin(user)" class="button button-full button-assertive ink">Login</button>
</div>
Ionic Controller code :
.controller('LoginCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk, $http, baseUrl) {
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.doLogin = function(user) {
$http({
method : "POST",
url : "http://localhost/vas_api/index.php/api/User/index/"+user.name
}).then(function mySucces(response) {
console.log(response)
});
}
})
CodeIgniter controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class User extends REST_Controller {
public function index_post() {
if(!$this->input->post('name')) {
$this->response(null, 400);
}
$data = array(
'name' => $this->input->post('name')
);
$id = $this->User_model->insertUser($this->input->post('name'));
if(!is_null($id)) {
$this->response(array('response' => $id), 200);
} else {
$this->response(array('response', 'Null values'), 400);
}
}
}
Codeigniter model code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
function insertUser($data) {
$this->db->insert('user',array('name' => $data));
$userId = $this->db->insert_id();
return $userId;
}
}
?>
Please help me to solve this issue. I'm using advance CodeIgniter version 3 Thanks in advance
Please use following approach
$http({
method : "POST",
url : "http://localhost/vas_api/index.php/api/User/index/",
data:{ name:user.name }
}).then(function(response) {
console.log(response)
});

ajax post send is not working in codeigniter

I'm having problem how to solve ajax post in codeigniter. GET method is working well but when I changed it to post, it is no longer working. I observed that when I disabled my csrf_protection in config file, it is working, but when I enabled it, it is NOT WORKING. I want to use csrf_protection enabled while post method is working. Can anybody help me? Thanks..
<script>
$(document).ready(function(){
$('#submit').click(function(event) {
$.ajax({
type: 'POST',
url: '/common/test',
data: {
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>'
<?php endif ?>
},
success: function(response) {
alert(response);
}
});
return false;
});
});
</script>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
On my Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Common extends CI_Controller {
function test(){
echo 'test';
}
}
jQuery expects the headers to not be default HTTP headers. you need to change the headers of content-type i believe to match your output. See the attached documentation for how to use codeigniters output class to do this. http://ellislab.com/codeigniter/user-guide/libraries/output.html

Codeigniter - Call another controller from a view using ajax

Initially I am trying to load two views from one controller.
On submission I am passing one view to one controller and another view to another controller using ajax dynamically. Here is the skeleton of the controller
function edit(){
if (!$this->login_model->is_logged_in())
{
redirect('auth/login', 'refresh');
}
$this->load->library('form_validation');
$this->data['custom_error'] = '';
//------------- Getting Student data----------------
if ($this->form_validation->run('students') == false)
{
$this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
} else
{
$data = array(
'username' => $this->input->post('username'),
'city' => $this->input->post('city')
);
if ($this->student_model->edit('students',$data,'id',$this->input->post('id')) == TRUE)
{
redirect(base_url().'index.php/students/manage/');
}
else
{
$this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';
}
}
$this->data['result'] = $this->codegen_model->get('students','id,username,city,created_on,date_created','id = '.$this->uri->segment(3),NULL,NULL,true);
$this->data['message'] = $this->db->get('messages')->result();
//---------------------- Posting student data for Edit--------------
$this->load->view('pheader');
$this->load->view('/students/students_edit', $this->data);
//-------- loading comment controller for comment box --------------
$msg_data['result'] = $this->db->get('messages')->result();
$this->load->view('commentView', $msg_data);
}
So the problem is when I m submitting the messages_view both the controllers are loaded , but I need to load only one controller
Here is my student_edit view where I edit my details
<?php
echo form_open(current_url()); ?>
<?php echo $custom_error; ?>
<?php echo form_hidden('id',$result->id) ?>
<p><label for="username">Username<span class="required">*</span></label>
<input id="username" type="text" name="username" value="<?php echo $result->username ?>" />
<?php echo form_error('username','<div>','</div>'); ?>
</p>
<p><label for="city">City<span class="required">*</span></label>
<input id="city" type="text" name="city" value="<?php echo $result->city ?>" />
<?php echo form_error('city','<div>','</div>'); ?>
</p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
Here is the commentView that I am loading separately from the controller
<div id="content-table-inner">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<?php foreach ($result as $comment): ?>
<tr valign="top">
<p>Posted By : <?=$comment->created_by?></p>
<p>Posted On : <?=$comment->created->on?></p>
<p>Message : <?=$comment->message?></p>
</tr>
<br/>
<?php endforeach; ?>
</table>
<div class="submitComment" id="insertbeforMe">
<h3>Add a message</h3>
<form id="form" method="POST" action="">
<p>
<textarea name="message"></textarea>
</p>
<input type="hidden" value="<?=base_url()?>" id="baseurl"/>
<button name="submit comment">Submit Comment</button>
</form>
</div>
<script type="text/javascript">
function comment(){
var baseurl = $('#baseurl').val();
$('.submitComment').click(function(){
$.ajax({
url : baseurl + 'index.php/comment/insert',
data : $('form').serialize(),
type: "POST",
success : function(comment){
$(comment).hide().insertBefore('#insertbeforMe').slideDown('slow');
}
})
return false;
})
}
</script>
</div>
Can anyone tell me whats the problem ?
If I understand correctly...
The event you should be capturing is the form's "submit", not the submit-button's "click". You're essentially running the AJAX request and submitting the form.
Try something like this instead:
$('form').on('submit', function(e) {
e.preventDefault(); // this prevents the form from submitting
// do AJAX stuff
});
Unless I am mistaken you are attaching the event to a click event on the '.submitComment' div.
Should you not give the button an id and attach the .click event to it ?
Then you need to define the view you want to call via ajax to return some json which your function can use:
The Javascript:
$('#button').click(function(){
$.ajax({
url : baseurl + 'index.php/comment/insert',
data : $('form').serialize(),
type: "POST",
dataType: "json",
success : function(comment){
$('table').append('<tr><p>'+comment.createdby+'</p><p>'+comment.createdon+'</p><p>'+comment.message+'</p></tr>');
}
})
return false;
})
The Controller method (comment/insert):
function insert() {
$comment = $this->input->post('message');
$result = $this->commentModel->insert($comment);
if($result["OK"]) {
$data['json'] = json_encode(array('createdon' => $result["createdon"], 'createdby' => $result["createdby"], 'message' => $result["message"]));
$this->load->view('json_comment_view', $data);
}
//ELSE deal with errors (flashdata etc...)
}
The View (loaded via ajax):
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>
I haven't tested this code - or used codeigniter extensively in about a year, but the concepts covered should put you on the right track for what you want to achieve. Let me know!

Categories