On comment form submit, JSON syntax error: unexpected token < - ajax

I can't figure out why JSON isn't working in my comment system. Any help would be much appreciated.
Currently when I submit the comment form, the ajax-loader flashes and spins, but the comment doesn't load and I get the "unexpected token" syntax error. When I refresh the page however the comment appears.
Here is my AJAX event handler that goes directly to my controller (following code snippet):
($('document').ready(function(){
$("button.submit").bind('click', function (e){
e.preventDefault();
var form = $('form');
var submit = $('button#submit');
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="/img/ajax-loader.gif" />');
$.ajax({
type: 'POST',
cache: false,
url: '?comment='+comment+'&item='+item+'&author='+author+'&rating='+rating,
data: form.serialize(),
dataTYPE: 'json',
success: function( data ){
comment_insert( jQuery.parseJSON( data ) );
console.log( "ResponseText: " +data );
form.trigger('reset');
$("#flash").hide();
}
});
});
});
function comment_insert( data )
{
var insert = '';
insert += '<article>';
insert += '<p>';
insert += ''+data.comment+'';
insert += '—';
insert += ''+data.author+'';
insert += ' | Reply';
insert += '</p>';
insert += '</article>';
$('.comment_block').prepend( insert );
}
Controller:
if($this->request->is('post')) {
$comments = ItemComments::create($this->request->data);
$comments->author_id = $this->user->id;
$comments->comment = $this->request->data['comment'];
$comments->item_id = $this->request->data['item'];
$comments->author_id = $this->request->data['author'];
$comments->rating = $this->request->data['rating'];
$comments->save();
echo json_encode($comments);
}
view page:
<div class="col-lg-12">
<h4>Comments and questions:</h4>
<?php if (count($comments)): foreach ($comments as $feedback): ?>
<article>
<p>
<?=$feedback->comment?>
—
<a href="/users/<?=$feedback->author->url?>">
<?=$feedback->author->firstname?>
<?=$feedback->author->lastname?>
<?=$feedback->id?>
</a>|
Reply
</p>
</article>
<?php endforeach;?>
<?php else: ?>
<div class="col-lg-12">
<div class="well-sm text-center">
<i class="fa fa-comments fa-2x"></i>
<h4>No comments yet.</h4>
</div>
</div>
<?php endif; ?>
<div class="comment_block"></div>
<div id="flash"></div>
</div>

Related

How to pass a parameter from a view to the controller with Ajax? Codeigniter

I am just learning and I would like you to help me solve this problem: I have two views, in view 1 it shows me a list of users, when clicking on any of them you must open another view showing the information about that user in view 2 .
To do that in view 1 with js I capture the user's id and send it to the controller by ajax, and in the controller it sends it to the model and the model response returns to the controller and sends it to view2, to show only the information of the selected user, the question is that it does not work, could you help me, what am I doing wrong?
View 1: This is the paragraph where you click and capture the id and the ajax that sends that id to the controller.
View1
<p onclick="detalles('<?=$p->usuarioId?>');"> <?=$p->usuarioId?><i class="fa fa-check-circle"></i> <?php echo $p->user ?></p>
<script>
function detalles(id=null){
$ (document) .ready (function () {
console.log(id);
$.ajax({
type: "POST",
data : {'id': id},
dataType:"html",
url: "usuarios_admin/ver",
success: function(result)
{
alert("good");
console.log("result",result);
}
});
});
}
</script>
Controller
public function ver(){
$id = $this->input->post("id");
if($id != null) {
$data = $this->PostUser->find($id);
echo json_encode($data);
$this->load->view('usuarios/vista2', $data);
}
}
model:
function find($id){
$this->db->select();
$this->db->from($this->table);
$this->db->where($this->table_id, $id);
$query = $this->db->get();
return $query->row();
}
view2:
here you must see the user data
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 lininfo">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 sinpa">
<p class="colorp">Name:</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 sinpa">
<p class="colorpi"><?php $data['name'] ?></p>
</div>
</div>
try this, i think there should be typo mistake
<p onclick="detalles('<?php echo $p->usuarioId ?>');"> <?php echo $p->usuarioId; ?>
<i class="fa fa-check-circle"></i> <?php echo $p->user ?></p>
Is your 2nd view load after ajax call?
Have you print your return data in ajax success,because you define dataType:"html" in ajax but you return json data from controller.
Thank you for your answers, it came out.
I had to print on the view this way to see the data:
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 lininfo">
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5 sinpa">
<p class="colorp">Name :</p>
</div>
<div class="col-lg-7 col-md-7 col-sm-7 col-xs-7 sinpa">
<p class="colorpi"><?php echo $user->name ?></p>
</div>
</div>
controller:
public function ver(){
$id = $this->input->post("id");
if($id != null) {
$data['user'] = $this->PostUser->find($id);
$this->load->view('usuarios/vista2', $data);
}
}
ajax y view 1
<div class="hi">
<!-- here you would see the result of ajax -->
<div>
<script>
function detalles(id=null){
$ (document) .ready (function () {
console.log(id);
$.ajax({
type: "POST",
data : {'id': id},
dataType:"html",
url: "usuarios_admin/ver",
success: function(result)
{
$('.hi').html(result);
}
});
});
}
</script>

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

Redirect to same ajax page after reload or form submission with old input data

I have a dashboard with some side menus. Each menus loads a page through ajax call after it is clicked.
By default when dashboard is loaded it loads the page, there is also a "dashboard" menu to switch between others like profile and add student.
But if I am at profile page and I refresh It goes back to dashboard page. Also if I try to add student by filling the form and if the form has any error it goes back to dashboard again with all old input data lost.
Web.php
Route::prefix('admin')->group(function(){
Route::get('/dashboard','AdminController#dashboard')->name('admin.dashboard');
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::post('/add_student','AdminController#add_student');
Route::middleware('ajax')->group(function(){
Route::get('/summary','AdminController#summary')->name('admin.summary');
Route::get('/profile', 'AdminController#profile')->name('admin.profile');
Route::get('/add_student_form','AdminController#add_student_form')->name('admin.add_student');
});
});
AdminController.php
public function add_student_form(){
return view('admin.add_student');
}
public function add_student(Request $request)
{
$this->validate($request,[
'name'=>'required|string',
'course_id'=>'required',
'dob'=>'required|date',
'gender'=>'required|string',
'category'=>'required|string',
'qualification'=>'required|string',
'fathername'=>'required|string',
'mothername'=>'required|string',
'mob_no'=>'required|string|max:10',
'address'=>'required|string',
'email'=>'required|email',
'PIN'=>'required|string|max:6',
]);
$student = new Student;
$student->name = $request['name'];
$student->roll_no ='NITTI'.rand(10000,99999);
$student->password = Hash::make($student['mob']);
$student->fees = new StudentFees;
$student->fees->paid_fees = $request['paid_fees'];
$student->fees->balance_fees = 7000;
$student->detail = new StudentDetail;
$student->detail->course_id = $request['course_id'];
$student->detail->gender = $request['gender'];
$student->detail->category = $request['category'];
$student->detail->qualification = $request['qualification'];
$student->detail->fathername = $request['fathername'];
$student->detail->mothername = $request['mothername'];
$student->detail->mob_no = $request['mob_no'];
$student->detail->email = $request['email'] ;
$student->detail->address = $request['address'];
$student->detail->PIN=$request['PIN'];
$student->detail->dob = $request['dob'];
$student->push();
return redirect()->back();
}
add_student.blade.php
<form action="/admin/add_student" method="POST">
#csrf
//It has all the fields here and a submit button
</form>
dashboard.blade.php
<div class="container-fluid">
<div class="row">
<div class="col-2 sidebar">
<img src="{{asset('/img/admin.jpg')}}" class="fit-image">
<p class="text-center">{{Auth::user()->name}}</p>
<hr>
<ul class="list-group">
<li class="list-group-item" id="summary">Dashboard</li>
<li class="list-group-item" id="admin_profile">Profile
</li>
<li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
<ul class="sidenav list-group">
<li class="list-group-item" id="add_student">Add Student</li>
<li class="list-group-item" id="viewall">View All </li>
</ul></li>
</ul>
</div>
<div class="col-10 dashboard" id="admin">
</div>
</div>
</div>
dashboard.js
$(document).ready(function(){
$.ajax({
url:'/admin/summary',
type: "GET",
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
});
$(document).on('click','#summary', function(){
$.ajax({
url:'/admin/summary',
type: "GET",
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
});
$(document).on('click','#admin_profile', function(){
$.ajax({
url:'/admin/profile',
type: "GET",
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
});
$(document).on('click','#add_student', function(){
$.ajax({
url:'/admin/add_student_form',
type: "GET",
success: function(data){
$data = $(data); produced
$('#admin').html($data).fadeIn();
}
});
});
I tried to redirect()->back->withInput('the fields');, but it didn't work.
If there is better way to load the pages which holds the same page after reloading or form submission I would welcome that.
You could use ajax form posting.
I rewrote code to abstract ajax load.
JS:
$(document).ready(function(){
//load summary by default
loadPage('summary');
//load on click menu item
$(document).on('click','.menu-item', function(){
loadPage($(this).attr('data-page'));
});
//send xcrf token in ajax header
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//submit form
$(document).on('submit', 'form', function(){
let form = $(this);
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
success: function(data){
if(data.page){
//load page returned in controller
loadPage(data.page);
}
},
error: function(data){
if(data.responseJSON && data.responseJSON.errors){
$.each(data.responseJSON.errors, function(key, value){
//convert laravel dotted rules to jquery selectors
key = key.replace('.', '[').replace(/\./g, '][');
if(key.indexOf('[') !== -1){
key += ']';
}
//do something with errored elements
form.find('*[name="' + key + '"]').addClass('error');
});
}
}
});
return false;
});
});
function loadPage(page){
$.ajax({
url:'/admin/' + page,
type: 'GET',
success: function(data){
$data = $(data);
$('#admin').html($data).fadeIn();
}
});
}
HTML:
Add to <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">
Change sidebar menu:
<ul class="list-group">
<li class="list-group-item menu-item" data-page="summary">Dashboard</li>
<li class="list-group-item menu-item" data-page="profile">Profile</li>
<li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
<ul class="sidenav list-group">
<li class="list-group-item menu-item" data-page="add_student_form">Add Student</li>
<li class="list-group-item menu-item" data-page="viewall">View All </li>
</ul>
</li>
</ul>
Controller method:
Replace return redirect()->back(); with return ['page' => 'viewall'];

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

how can i show this $data value in the form input field?

how to show $data value in form input field?
<head>
<script>
$(function () {
$("#task_id").change(function () {
var task_id = $(this).val();
var url = "status/tasks/get_task_info/" + task_id;
$.ajax({
url: url,
beforeSend: function () {
$(".load-taskinfo").html('<img src="images/ajax/ajax-loader10.gif">');
},
success: function (response) {
$data = JSON.parse(response);
}
});
});
});
</script>
</head>
<body>
<div class="span3">
<div class="control-group <?php echo (form_error('progress_percent')) ? 'error' : ''; ?>">
<label class="control-label" for="progress_percent">Progress (In %) :</label>
<div class="controls">
<?php echo form_input(array(
'name' => 'progress_percent',
'id' => 'progress_percent',
'maxlength' => 160
)); ?>
<?php if (form_error('progress_percent')) : ?>
<span class="help-inline">
<?php echo form_error('progress_percent'); ?>
</span>
<?php endif; ?>
</div>
</div>
</div>
</body>
In your success callback, use jQuery selector to select the input by ID or by name, and fill its value.
success: function (response) {
var $data = JSON.parse(response);
$('#progress_percent').val($data);
}

Resources