I want to sent some data with ajax to a php file. I created a FormData, and then, i append all the data to it, that i want to send. I dont get any error message in the console.
My problem is, that the formdata is always empty, and the php file is not getting any data also.
The form:
<div class="tab-pane show" id="tab5">
<form id="AllapotForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<table id="products" class="table table-hover">
<thead>
<tr class="tr_bold">
<!--width="33.3%"-->
<td class="left" >Létrehozva</td>
<td class="left" >Állapot</td>
<td class="left" >A megrendelő értesítve email-ben</td>
<td class="left" >Megjegyzés</td>
</tr>
</thead>
<tbody id="allapotok">
<?php
$get_r_allaptok = mysqli_query($kapcs,
"
SELECT
rendeles_allapot.*,
rendeles_allapotok.rendeles_allapotok_nev
FROM rendeles_allapot
LEFT JOIN rendeles_allapotok ON rendeles_allapot.allapot_allapot_id = rendeles_allapotok.rendeles_allapotok_id
WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id ASC
")
or die(mysqli_error($kapcs));
if(mysqli_num_rows($get_r_allaptok) > 0 )
{
while($r_allapot = mysqli_fetch_assoc($get_r_allaptok))
{
if($r_allapot['allapot_notify'] == 0 ) { $ertesitve = "Nem"; }
if($r_allapot['allapot_notify'] == 1 ) { $ertesitve = "Igen"; }
echo '<tr>
<td class="left">'.$r_allapot['allapot_datetime'].'</td>
<td class="left">'.$r_allapot['rendeles_allapotok_nev'].'</td>
<td class="left">'.$ertesitve.'</td>
<td class="left">'.$r_allapot['allapot_comment'].'</td>
</tr>';
}
}
?>
</tbody>
</table>
<img src="<?php echo $host; ?>/images/assets/preloader.gif" id="preloaderImage2" style="display:none" class="img-responsive" style="margin:10px auto;">
<div class="form-group row">
<label class="control-label col-md-2">Állapot:</label>
<div class="col-md-2">
<select name="allapot" id="allapot" class="input input-select form-control">
<?php
$check_allapot = mysqli_query($kapcs, "SELECT allapot_allapot_id FROM rendeles_allapot WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id DESC LIMIT 1");
if(mysqli_num_rows($check_allapot) > 0 )
{
$allapot_fetch = mysqli_fetch_assoc($check_allapot);
$ertek = $allapot_fetch['allapot_allapot_id'];
}
else
{
$ertek = intval($a['status']);
}
$get_allapotok = mysqli_query($kapcs, "SELECT rendeles_allapotok_id, rendeles_allapotok_nev FROM rendeles_allapotok WHERE rendeles_allapotok_status = 1 ORDER BY rendeles_allapotok_nev ASC");
if(mysqli_num_rows($get_allapotok) > 0 )
{
while($allapot = mysqli_fetch_assoc($get_allapotok))
{
$selected = $ertek == $allapot['rendeles_allapotok_id'] ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $allapot['rendeles_allapotok_id'] . '">' . $allapot['rendeles_allapotok_nev'] . '</option>'."\n";
}
}
?>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megrendelő értesítése email-ben:</label>
<div class="col-md-2">
<input type="checkbox" name="notify" id="notify" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés hozzáadása az email-hez:<span class="help">Amennyiben ezt bepipálja, a megjegyzés az ügyfélnek kiküldött üzenetbe is bele fog kerülni.</span></label>
<div class="col-md-2">
<input type="checkbox" name="add_text" id="add_text" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Fájl csatolása az email-hez:</label>
<div class="col-md-2">
<input type="file" name="file" id="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés:</label>
<div class="col-md-8">
<textarea name="comment" id="comment" style="width:100%;height:200px;"></textarea>
<div style="margin-top: 10px; text-align: center;">
<a class="saveButton btn btn-primary" style="color:#fff" onclick="allapot_modosit();" id="history_button">Állapot módosítása</a>
</div>
</div>
</div>
</form>
</div>
I call this function on a button click event.
function send_data()
{
var html;
var RendelesID = <?php echo $id; ?>;
var RendelesUserEmail = "<?php echo html($a['email']); ?>";
var RendelesUserName = "<?php echo html($a['nev']); ?>";
var webshopEmail = "<?php echo $webshopEmail; ?>";
var webshopName = "<?php echo $webshopName; ?>";
var Allapot = $( "#allapot option:selected" ).val();
var Comment = CKEDITOR.instances['comment'].getData();
if($("#notify").is(':checked')){var Notify = 1;}else{var Notify = 0;}
if($("#add_text").is(':checked')){var AddToEmail = 1;}else{var AddToEmail = 0;}
var formData = new FormData($('#AllapotForm')[0]);
formData.append('fileName', $('#file')[0].files[0]);
formData.append(RendelesID, RendelesID);
formData.append(RendelesUserEmail, RendelesUserEmail);
formData.append(RendelesUserName, RendelesUserName);
formData.append(webshopEmail, webshopEmail);
formData.append(webshopName, webshopName);
formData.append(Allapot, Allapot);
formData.append(Comment, Comment);
formData.append(Notify, Notify);
formData.append(AddToEmail, AddToEmail);
console.log(formData);
$.ajax({
type: 'POST',
cache: false,
url: 'files/update_rendeles_allapot.php',
//dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: { formData:formData },
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
alert(data);
},
complete: function(){
$('#preloaderImage2').hide();
},
error: function (e) {
alert(e.responseText);
console.log(e);
}
});
}
data: { formData:formData },
You need to pass the form data object itself, not a plain object.
data: formData
Have you already seen this?
FormData created from an existing form seems empty when I log it
If yes try to check your network look to the Network then take a look at your request.
You can also try to check your API via Postman if it's working properly.
Related
I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>
I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
alert(data);
var url = '/PubDev/updatePubDev';
$.post(url, data, null, 'json')
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error");
}
})
.fail(function (data) {
alert("ajax error");
})
.always(function () {
});
});
<div class="md-modal md-effect-1" id="updatePubDevModal" >
<div class="md-content">
<div class="modal-header">
<button class="md-close close">×</button>
<h4 class="modal-title">Update Publisher/Developer</h4>
</div>
<form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="row dropzone">
<div class="col-lg-5">
<div class="form-group">
<label for="pubDevName">System Id of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
<input type="hidden" name="pubDevId" id="pubDevId" >
</div>
<div class="form-group">
<label for="pubDevName">Name of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
</div>
<div class="form-group">
<label for="date-founded">Date Founded</label>
<input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
</div>
<div class="form-group">
<label>What type of company is this?</label>
<div class="checkbox-nice">
<input type="checkbox" name="isPub-update" id="isPub-update">
<label for="date-founded-update">
This company is a publisher
</label>
</div>
<div class="checkbox-nice">
<input type="checkbox" name="isDev-update" id="isDev-update">
<label for="isDev-update">
This company is a developer
</label>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="main-box clearfix main-box-frame" >
<header class="main-box-header clearfix">
<h2>Upload Publisher /Developer Logo</h2>
</header>
<div class="main-box-body clearfix imgcontainer center">
<img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
<div class="main-box-body clearfix">
<div id="dropzone" class="drop-zone-frame" >
<input type="file" name="image2" id="image2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
</div>
</form>
</div>
</div>
Here is the php code:
public function updatePubDev() {
$fields = array();
$fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
$fields['name'] = $this->input->post('pubDevName-update');
if ($this->input->post('date-founded'))
$fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
if ($this->input->post('isPub-update'))
$fields['publisher'] = 1;
else
$fields['publisher'] = 0;
if ($this->input->post('isDev-update'))
$fields['developer'] = 1;
else
$fields['developer'] = 0;
$row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());
$file = $_FILES['image2'];
//$idPubDev = $this->input->post("pubDevName");
$ds = DIRECTORY_SEPARATOR;
$path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
//print_r($file);
$info = new SplFileInfo($file['name']);
//var_dump($info->getExtension());
$filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
$result = $this->upload->uploadfile($file, $path, $filename);
//echo "test";
if ($result['status'] === "OK") {
$logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
$this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
$result['message'] = "file saved successfully";
$result['query'] = $this->db->last_query();
}
$result['update_rows']= $row_count;
echo json_encode($result);
}
I tried the .ajax version, but the problem persist, here is the modified jquery:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = '/PubDev/updatePubDev';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false
})
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error!");
}
})
.fail(function (data) {
alert("ajax error!");
})
.always(function () {
});
});
It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:
processData: false,
contentType: false
This way, it solved my problem.
Use FormData as data instead of $(this).serialize();, set processData and contentType to false
var data = new FormData();
data.append("file", $(":file", this)[0].files[0]);
$.ajax({
url: "/PubDev/updatePubDev",
type: "POST",
data: data,
processData: false,
contentType: false
})
Please try to use file_get_contents('php://input'); to get the upload content.
The code below auto fills the Full name and Email when the user enters their ID. I also want to display the user's image but i'm having issues.
<script type="text/javascript">
$(function() {
$( "#techid" ).on( 'blur' , function() {
searchString = $(this).val();
var data = 'telefoon='+searchString;
if(searchString) {
$.ajax({
type : "POST",
url : "query2.php",
data : data,
success : function(html){
result = String(html).split("|");
$("#name").val(result[0]);
$("#mail").val(result[1]);
$("#avatar").val(result[2]);
}
});
}
return false;
});
});
</script>
I know I can display the image like this but how do i integrate it with the AJAX?
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include_once("connection.php");
$result = mysql_query("SELECT * FROM players3");
while($res = mysql_fetch_array($result)) {
echo '<img height="80px" width="100px" src="data:image/jpeg; base64,'.base64_encode( $res['image'] ).'"/>';
?>
I tried this:
<div class="form-group">
<label for="telefoon" class="col-sm-2 control-label">Avatar</label>
<div class="col-sm-10">
<img height="80px" width="100px" id="avatar" src="data:image/jpeg;base64,'.base64_encode( )"/>
</div>
</div>
<div class="form-group">
<label for="telefoon" class="col-sm-2 control-label">Tech ID</label>
<div class="col-sm-10">
<input type="text" name="techid" class="form-control" id="techid" placeholder="TechID" >
</div>
</div>
<div class="form-group">
<label for="naam" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="mail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="mail" class="form-control" id="mail" placeholder="email">
</div>
</div>
Like this?
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include_once("connection-db2.php");
$result = mysql_query("SELECT * FROM TechID");
while($res = mysql_fetch_array($result)) {
echo '<li><img height="80px" width="100px" src="data:image/jpeg;base64,'.base64_encode( $res['image'] ).'"/>';
}
?>
JS
$("#image").attr('src', result[4]);
when upload the image, save the image path with image file name. like "images/image1.jpg"
like the name and email, query the path of the image.
make a empty
after ajax success you get the path of the image. right? use this path like this. $("#image_to_show").html("");
<img> tag doesn't have value attribute
You should probably echo just image url and set it as a src attribute of your img tag
PHP:
while($res = mysql_fetch_array($result)) {
echo $res['image'];
// ...
}
JS:
$("#avatar").attr('src', result[2]);
On a side note - it would be better to json_encode response and use it instead of .split("|"). Something like this:
PHP:
$response = array();
while($res = mysql_fetch_array($result)) {
$response['name'] = $res['name'];
$response['email'] = $res['email'];
$response['image'] = $res['image'];
}
echo json_encode($response);
JS:
$.ajax({
type : "POST",
url : "query2.php",
data : data,
dataType : "json",
success : function(result){
$("#name").val(result.name);
$("#mail").val(result.email);
$("#avatar").attr('src', result.image);
}
});
I have a list product's category and want to edit.
when i click on edit button of particular category open a Bootstrap modal for click ID to update content.
Popup is coming but view is not loading on it.
List of data:
<?php if (is_array($category_list)) {
foreach ($category_list as $item): ?>
<tr>
<td>
<?=$item->category_name?></td>
<td>
<a href="#" class="btn btn-small z-depth-0" data-toggle="modal" data-target="#categoryModal" id="category_modal" data-id="<?=$item->cat_id?>" data-url="<?php $this->config->base_url();?>admin_panel/get_category/<?=$item->cat_id?>">
<i class="mdi mdi-editor-mode-edit"></i>
</a>
</td>
</tr>
<?php endforeach;}
?>
Javascript Function :
<script type="text/javascript">
$(document).on("click", "#category_modal", function () {
var url = $(this).data('url');
alert(url);
jQuery.ajax({
url: url,
success: function(response)
{
alert(response);
jQuery('#categoryModal .modal-content').html(response);
jQuery('#categoryModal').modal('show', {
});
}
});
});
</script>
Controller Function :
public function get_category() {
$cat_id = $this->uri->segment(3);
$data['category'] = $this->admin_model->get_category($cat_id);
$this->load->view('backend/category_popup', $data);
}
category_popup.php View:
<?php
if (is_array($category)) {
foreach ($category as $item) {
$cat_id = $item->cat_id;
$cat_name = $item->category_name;
}
} else {
$cat_id = '';
$cat_name = '';
}
?>
<form action="#" method="post" name="form" style="margin-top: -200px;width: 100%;height: 100%" class="z-depth-4">
<div class="card-panel">
<div class="card-panel cyan lighten-3">
<h4 style="text-align: center">Update Category - <strong><?=$cat_name?></strong></h4>
</div>
<div class="row">
<div class="col l6 s12">
<label for="subcat_name">Category Name</label>
<div class="input-field">
<input id="cat_names" name="cat_name" type="text" class="validate" value="<?=$cat_name?>">
</div>
</div>
</div>
<div class="row">
<div class="col l4 s12">
<button class="btn" type="button" name="action" onclick="update_cat()">Update</button>
</div>
</div>
</div>
</form>
append to ajax the data attribute:
$('#category_modal').on('show.bs.modal', function(e) {
var url = $(this).data('url');
alert(url);
jQuery.ajax({
url: url,
data:{data_id:$(this).attr('data_id')},
success: function(response)
{
alert(response);
jQuery('#categoryModal .modal-content').html(response);
}
});
});
and your controller change:
$cat_id = $this->input->get('data_id');
I create a search form that using ajax as the action. In success ajax, how can I just load some specific div without load all refresh page.
This is my form
<?php
$properties = array('id' => 'form1');
echo form_open("", $properties);
?>
<fieldset>
<div class="controls" id="chekboxes">
<label class="checkbox "><input type="checkbox" name="criteria[]" id="nomorcb"/> Nomor Request </label>
<input type="text" class="input-xlarge focused" id="no" name="no" placeholder="Masukkan No Request..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="namacb"/> Nama User </label>
<input type="text" class="input-xlarge focused" id="nama" name="nama" placeholder="Masukkan Nama User..."/>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="departementcb" /> Departement</label>
<div class="control-group">
<div class="controls">
<select class="input-xlarge" id="selectError" name="dep">
<option value="">-- Pilih departement --</option>
<?php
foreach ($dep as $data) {
echo "<option value='" . $data['nama_departement'] . "'>" . $data['nama_departement'] . "</option>";
}
?>
</select>
</div>
</div>
<label class="checkbox "><input type="checkbox" name="criteria[]" id="rentangcb"/> Rentang waktu</label>
<div class="controls" id="tanggal-rentang">
<input type="text" class="input-small datepicker" id="tanggal" value="" name="tgl_awal"><span> s/d </span>
<input type="text" class="input-small datepicker" id="tanggal2" value="" name="tgl_akhir">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" id="submit">Cari</button>
<button type="reset" class="btn" id="cancel">Cancel</button>
</div>
</fieldset>
<?php echo form_close(); ?>
this is the action's code for execute the form.
public function search() {
$id_request = $this->input->post('nomor');
$nama_user = $this->input->post('nama');
$departement = $this->input->post('departement');
$awal = $this->input->post('tgl_awal');
if ($awal != "") {
$awal = $this->input->post('tgl_awal');
} else {
$awal = "2014-01-01";
}
$timestamp_awal = strtotime($awal);
$tgl_awal = date("Y-m-d H:i:s", $timestamp_awal);
$akhir = $this->input->post('tgl_akhir');
if ($akhir != "") {
$akhir = $this->input->post('tgl_akhir');
} else {
$akhir = "2020-01-01";
}
$timestamp_akhir = strtotime($akhir);
$tgl_akhir = date("Y-m-d H:i:s", $timestamp_akhir);
$data = $this->model_request->search($id_request, $nama_user, $departement, $tgl_awal, $tgl_akhir);
echo json_encode($data);
}
and this is the Ajax jquery for form above :
$('form').on('submit', function() {
var nomor = $('#no').val();
var nama = $('#nama').val();
var departement = $('#selectError').val();
var tgl_awal = $('#tanggal').val();
var tgl_akhir = $('#tanggal2').val();
$.ajax({
url: '<?php echo base_url() . 'it_team/control_it/search' ?>',
type: 'POST',
data: {nomor: nomor,
nama: nama,
departement: departement,
tgl_awal: tgl_awal,
tgl_akhir: tgl_akhir},
dataType: 'json',
success: function(obj) {
//Please give me an idea
}
});
return false;
For testing, I try seearch and thank God, it gives me a success on json like this:
[{"id_request":"015","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 02:51:05"},
{"id_request":"017","nama_user":"Dzil","departement":"IT","waktu_it_terima":"2015-06-19 13:32:46"}]
My problem is, the result of search form above will be displaying into a table in same page with the form above. You know, in tbody's table will be generate the object on based the return of json. I am newbie using json. The table looked like this
<div class="box-content" id="things_table2">
<table class="table table-bordered table-striped table-condensed" id="table1">
<thead>
<tr>
<th>No. </th>
<th>No Request</th>
<th>Nama user</th>
<th>Departement</th>
<th>Tanggal Request</th>
<th>Action</th>
</tr>
</thead>
<tbody id="hasil-pencarian">
// Result will be showing here
</tbody>
</table>
</div>
Any help it so appriciated.
Try like this (beware there are less fields in your json than in your table):
var data = [
{
'id_request': '015',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 02:51:05'
},
{
'id_request': '017',
'nama_user': 'Dzil',
'departement': 'IT',
'waktu_it_terima': '2015-06-19 13:32:46'
}
];
var html = '';
for (var i = 0; i < data.length; i++) {
var td="";
for(var key in data[i]){
td+='<td>'+data[i][key]+'</td>';
}
html+="<tr>"+td+"</tr>";
}
$('#hasil-pencarian').html(html);
There is nothing special about json. Treat it like any js object, ie after parsing it.
Since its just an array of objects, you can iterate over it and do whatever.
var html = '';
$.each(data, function (index, element) {
// build your html
html += '<tr>;'
html += '<td>'+ index + 1 + '</td>';
html += '<td>'+ element.id_request + '</td>';
// same for other elements use `element.<key-name>`
// end tr after all the td's are done
html += '</tr>;'
});
Once you have iterated over all the elements, inject it in the dom.
$('.DOM-ELEMENT').html(html);