Form doesn't insert into the database using codeigniter - javascript

I'm trying to create a one-page CRUD in CodeIgniter which only consist of not more than 5 fields. My problem is it doesn's insert its data in the database, I've been debugging this but I can't figure it out what is the problem. What did I miss?
Form:
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="activity-item">
<form id="agencyForm" enctype="multipart/form-data" method="POST" class="form-horizontal">
<div class="form-body">
<input type="hidden" value="" name="agency_id" />
<div class="form-group">
<div class="col-md-12">
<input name="agency_name" id="agency_name" placeholder="Agency Name" class="form-control" type="text">
<?php echo form_error('agency_name','<span class="help-block">','</span>'); ?>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="category" id="category" placeholder="Category" class="form-control" type="text">
<?php echo form_error('category','<span class="help-block">','</span>'); ?>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="address" id="address" placeholder="Address" class="form-control" type="text">
<?php echo form_error('address','<span class="help-block">','</span>'); ?>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input name="acronym" id="acronym" placeholder="Acronym" class="form-control" type="text">
<?php echo form_error('acronym','<span class="help-block">','</span>'); ?>
</div>
</div>
</div>
<button type="submit" value="submit " id="btnSave" onclick="save(this.agencyForm); return false" class="btn btn-effect">Save</button>
</form>
</div>
<div class="clear"> </div>
Script:
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
showAllAgency();
//datatables
table = $('#').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
"url": "",
/*<?php echo site_url('agency/list')?>*/
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [{
"targets": [-1], //last column
"orderable": false, //set not orderable
}, ],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function() {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function() {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function() {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_person() {
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show');
$('.modal-title').text('Add Agency');
}
function edit_person(id) {
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url: "<?php echo site_url('agency/edit_agency/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data) {
$('[name="id"]').val(data.id);
$('[name="agency_name"]').val(data.agency_name);
$('[name="category"]').val(data.category);
$('[name="address"]').val(data.address);
$('[name="acronym"]').val(data.acronym);
$('#modal_form').modal('show');
$('.modal-title').text('Edit Agency');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
function reload_table() {
table.ajax.reload(null, false);
}
function save() {
$('#btnSave').text('saving...');
$('#btnSave').attr('disabled', true);
var url;
if (save_method == 'add') {
url = "<?php echo site_url('agency/save_c')?>";
} else {
url = "<?php echo site_url('agency/update_c')?>";
}
console.log($('#agencyForm').serialize());
// alert($(agencyForm).serialize());
$.ajax({
url: url,
// url: "<?php echo site_url('agency/save_c')?>",
type: "POST",
data: $('#agencyForm').serialize(),
dataType: "JSON",
success: function(data) {
if (data.status) {
alert('Successfully added the officer');
reload_table();
} else {
for (var i = 0; i < data.inputerror.length; i++) {
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
}
});
}
function showAllAgency() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url() ?>agency/getAgency',
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<tr>' +
'<td>' + data[i].agency_name + '</td>' +
'<td>' + data[i].category + '</td>' +
'<td>' + data[i].address + '</td>' +
'<td>' + data[i].acronym + '</td>' +
// '<td>'+
// 'Edit'+
// 'Delete'+
// '</td>'+
'</tr>';
}
$('#showagency').html(html);
},
error: function() {
alert('Could not get Data from Database');
}
});
}
</script>
Controller:
public function save_c() {
var_dump($this - > input - > post(NULL, TRUE));
$data = array(
'agency_name' => $this - > input - > post('agency_name'),
'category' => $this - > input - > post('category'),
'address' => $this - > input - > post('address'),
'acronym' => $this - > input - > post('acronym'),
);
$insert = $this - > agency - > save_now($data);
echo json_encode(array("status" => TRUE));
}
Model:
public function save_now($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
NOTE: It inserts data into the database when I change the URL like this:
$.ajax({
// url: url,
url: "<?php echo site_url('agency/save_c')?>",
this is the screenshot

You have ussue here. You haven't specify save_method anywhere. define save_method according to your logic or remove this if condition and assign insertion url directly
if (save_method == 'add') {
url = "<?php echo site_url('agency/save_c')?>";
} else {
url = "<?php echo site_url('agency/update')?>";
}
You can do insertion directly
url = "<?php echo site_url('agency/save_c')?>";

Related

id undefined when details are passed to a modal

I have a table of recipes created by a particular user, and when the pencil mark on each row of the table is clicked, a modal is displayed, showing the details of this particular recipe and it should allow the user to edit the recipe and save the updated version to the database. However, although the details are correctly being passed to the modal, the recipe id doesn't seem to be passed to the modal, since I have tried to output the recipe id into the console and it says the recipe id is undefined. I have tried to debug this error but to no avail. Can anyone provide any insight into why this might be?
//Recipe.js
$('.editThis').on('click', function() {
var recipe_id = $(this).attr('data-id');
var request = $.ajax({
url: "ajax/displayRecipe.php",
type: "post",
dataType: 'json',
data: {recipe_id : recipe_id}
});
request.done(function (response, textStatus, jqXHR){
console.log("response " + JSON.stringify(response));
$('#name').val(response.name);
$('#date').val(response.date);
});
});
$('#editRecipe').click(function() {
var recipe_id = $(this).attr('data-id');
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
});
//Recipe.php
<?php
$recipeObject = new recipeList($database); //Lets pass through our DB connection
$recipe = $recipeObject->getUserRecipes($_SESSION['userData']['user_id']);
foreach ($recipe as $key => $recipes) {
echo '<tr><td>'. $value['name'].'</td><td>'. $value['date'].'</td><td>'.'<a data-id = '.$value['recip_id'].' data-toggle="modal" class="edit editThis" data-target="#editRecipe"><i class="fa fa-pencil"></i></a>'.'</td></tr>';
}
?>
// editRecipe Modal
<div id="recipe" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header recipe">
<h1 class="modal-title">Edit Recipe</h4>
</div>
<div class="modal-body">
<form method="post" id="updateRecipeForm">
<?php
require_once('classes/recipes.classes.php');
$recipeObject = new recipeList($database);
$recipe = $recipeObject->getRecipeDetails(recipe_id);
if(isset($_POST['submit'])) {
$updateRecipe = $recipeObject ->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
if($updateRecipe) {
echo ("Your recipe has been updated!";
}
}
?>
<div class="form-group">
<input type="text" class="control-form" id="name" value = "<?php echo $recipe['name']; ?>">
</div>
<div class="form-group">
<input type="date" class="control-form" id="date" value = "<?php echo $recipe['date']; ?>">
</div>
</div>
<div class="form-group">
<input type="hidden" class="form-control" data-id=".$recipe['recipe_id']." id="recipe_id" name="recipe_id" value = "<?php echo $recipe['recipe_id']; ?>">
</div>
<button type="submit" class="btn recipe" id="editRecipe" data-dismiss="modal">Save</button>
</form>
</div>
</div>
</div>
</div>
//ajax - updateRecipe.php
<?php
require_once('../includes/database.php');
require_once('../classes/recipes.classes.php');
if($_POST['name'] && $_POST['date'] && $_POST['trans_id']){
$recipeObject = new recipeList($database);
echo $recipeObject->updateRecipe($_POST['name'], $_POST['date'], $_POST['recipe_id']);
}
?>
//recipes.classes.php
...
public function getRecipeDetails($recipeid){
$query = "SELECT * FROM recipe WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':recipe_id', $recipeid);
$pdo->execute();
return $pdo->fetch(PDO::FETCH_ASSOC);
}
public function updateRecipe($name, $date, $recipe_id){
$query = "UPDATE recipe SET name = :name, date = :date WHERE recipe_id = :recipe_id";
$pdo = $this->db->prepare($query);
$pdo->bindParam(':name', $name);
$pdo->bindParam(':date', $date);
$pdo->bindParam(':recipe_id', $recipe_id);
$pdo->execute();
}
Try the following:
$(document).on('click', '.editThis',function() {...});
$(document).on('click','#editRecipe',function() {...});
Try this onclik function
Some time you cant get the apt value from this So Try this method.
we can use id but in your case you foreach the a tag so we cant repeat id. Hope Its Works
<a data-toggle="modal" class="recipe_<?php echo $value['recipe_id']; ?> edit editThis" onclick="editRecipe('<?php echo $value['recipe_id']; ?>')" ><i class="fa fa-pencil"></i></a>
function editRecipe(txt) {
var recipe_id = $('.recipe_'+txt).val();
var name_input = $('#name').val();
var date_input = $('#date').val();
var request = $.ajax({
url: "ajax/updateRecipe.php",
type: "post",
data: {name : name_input, date : date_input, recipe_id : recipe_id},
dataType: 'json'
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
};

jQuery load more data on scroll not loading more data

I am working on a jQuery load more data scroll, which when I click on category link it will sort the data based on that category I click, which is working well. It only load first six how can I fix this issue.
index.php
Category
<div class="container">
<div class="row" id="results"></div>
<div id="loader_image" align="center">
<img src="loader.gif" alt="" width="50">
</div>
<div id="loader_message" align="center"></div>
</div>
<script type="text/javascript">
//For The Scroll
var busy = false;
var limit = 6
var offset = 0;
var where = '<?php if(isset($_GET["where"])) {echo $_GET['where'];} else {echo ' ';} ?>';
function displayRecords(lim, off, where) {
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
// $("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
$('#loader_image').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset, where);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
where = '<?php if(isset($_GET["where"])) {echo $_GET['where'];} else {echo ' ';} ?>';
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset, where); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
getrecords.php
$where = '';
if(isset($_GET['where'])){
$search = str_replace('-',' ', $_GET['where']);
$where .= "WHERE category LIKE '%$search%'";
}
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 6;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM users {$where} ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $user->runQuery($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
?>
<div class="col-sm-4 my-4 text-center">
<div class="card">
<img class="rounded-circle img-fluid d-block mx-auto" src="http://placehold.it/200x200">
<h3><?php echo ucwords($res['name']); ?></h3>
<small><?php echo $res['category']; ?></small>
</div>
</div>
<?php
}
}
?>
see below preview it image of the issue
If the loading icon is never removed check the console for any errors. You're setting the loading icon to be shown in the beforeSend function but have no error property in the ajax handler.
Remove $("#results").append(html); from the top of your success: function(html) { .. } and move it into the else portion of your if statement. You do this so you're not attempting to append an empty string, or an unwanted string, for no reason and we have finer control over it via our if/else logic.
You'll also want to remove $('#loader_image').show() from the else statement. You're re-showing it even though the ajax call has been processed successfully.
See the cleaned up success function below.
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#results").append(html);
}
window.busy = false;
}
New ajax call:
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$('#results').append(html);
}
window.busy = false;
},
error: function(error) {
console.log(error);
$('#loader_image').hide();
$('#loader_message').html('There was an error processing your request.').show();
}
});

Value changed to null in ajax

Value changed to null in ajax after updating the shipping city value from text field. I don't known what is the problem.. please help me Friends.
my php code:
public function updateshippingcity() {
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$json['new_shipping_city'] = $this->request->post['shipping_city'];
$this->db->query("UPDATE " . DB_PREFIX . "order SET shipping_city = '" . $this->db->escape($this->request->post['shipping_city']) . "' WHERE order_id = '" . (int)$this->request->get['order_id'] . "'");
$this->response->setOutput(json_encode($json));
}
}
my ajax code :
<script type="text/javascript">
$("#update-shipping-city").click(function() {
var name_val = $('input[name="new_shipping_city"]').val();
$.ajax({
url: 'index.php?route=sale/order/updateshippingcity&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>',
type: 'post',
dataType: 'json',
data: {
shipping_city: name_val
},
beforeSend: function() {
$('#update-shipping-city').attr('disabled', true);
},
complete: function() {
$('#update-shipping-city').attr('disabled', false);
},
success: function(json) {
}
});
alert("shipping city has changed");
});
my html code:
<div class="col-md-12">
<input name="new_shipping_city" value="<?php echo $shipping_city; ?>"></input>
<button id="update-shipping-city" > update </button>
</div>
I had achieved finally by post method.
<script type="text/javascript">
$(function() {
$("#update-shipping-city").click(function(e) {
e.preventDefault();
var scity_val = $('input[name="new_shipping_city"]').val();
$.post("index.php?route=sale/order/updateshippingcity&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>", {
shipping_city: scity_val
}, function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
});
Finally, my problem cleared. thank guys for contributing on my question :)

Removing cart products from input with product id value

I wanted to work with input type ="hidden" so I can do a check. I have a slider which displays products of a category and through two Ajax requests I add and remove them through clicks on buy and remove buttons, however that does not have as much relevance in this question.
Only one such product on the slide can be purchased by order, but if one of them is added and the page is updated and the buy button is clicked again, another of that product is added, which should not happen. I wanted to make sure that in the update of the page, if there is already one of these products added, it is removed, but I do not know where to follow it to complete it.I think I should use an input type ="hidden", so that through it I can save the value of the id of the added product, but I do not know how to do this verification.
Below I will add the code of the buttons and the input that I have already made and are correct, besides the code of the Ajax requisitions. If necessary, I add the code of the controllers I use.
Button and input code:
<button style="margin-left: 11%;" type="button" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none; margin-left: 11%;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remove</span></span></button>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="" />
Ajax requisition code:
var productSelected = "";
function addCartao(product){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
What you should do is make a small php code to do the verification, where it contains the SKUs of these products and if they are in the cart, assign a value to a boolean variable and insert it into an input to work this value in jQuery.
Php code for verification:
<?php
$array_de_skus_de_cartoes = array(45,60,80,90,102,103,104,105); //SKUs of products
$isCartaoAdicionado = 0;
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
foreach ($array_de_skus_de_cartoes as $sku) {
if($sku == $item->getProduct()->getSku()) {
$isCartaoAdicionado = 1;
$cartao_id = Mage::getModel("catalog/product")->getIdBySku($sku);
}
}
}
if($isCartaoAdicionado == 1) {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="1" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="<?php echo $cartao_id ?>" />
<?php
}
else {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="0" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="" />
<?php
}
?>
Ajax request code updated:
var isCartaoAdicionado = $j('#cartao_adicionado').val();
var isCartaoAdicionadoProductId = $j('#cartao_adicionado_product_id').val();
var productSelected = "";
function addCartao(product){
if(isCartaoAdicionado == 1){
removeCartaotoCart(isCartaoAdicionadoProductId);
}
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado'+product).val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId); $j('#cartaoMensagemAdicionado'+itemId).val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}

Form action statement in PHP

I've got following problem with my PHP code:
my form is divided into two divs: first div shows up when the page is opened, second div displays after clicking a button (and this first one, thanks to Ajax, hides). My plan is to check a few statements, if true then create POST, get from it data and then dynamically create table, switching the content using Ajax again. BUT. I cannot use the 'action' thing because of the statements. When I've got 'submit' type - it creates POST, but reloads the page. If I replace it with 'button' type - Ajax works, but POST is empty.
Here's my code:
function formu ($w="1", $sr="on", $comma="",
$space ="", $other =""){?>
<form id="options" action="" method="POST" >
<div id = "first">
<h1 id = "title"> Choose a file </h1>
<input type = "radio" name="radio" id ="radio" value="op1" class ="radio"> ONE
<br>
<input type ="radio" name="radio" id="radio" value ="op2" class = "radio"> TWO
<br>
<input type ="radio" name="radio" id="radio" value="op3" class = "radio"> THREE
<br>
<input type = "button" id="Submit" Value = "Show">
</div>
<div id = "sec">
<h1 id = "title2"> Choose options </h1>
<p id="odwiersza"> Cut: </p>
<input type="text" name="w" value=""> <br>
<p id="Separators"> Separator: </p>
<input type = "checkBox" name="sr"> sr
<input type= "checkBox" name="comma"> comma
<input type = "checkBox" name = "space"> space
<input type = "checkBox" name ="other"> other (which?) <input type="text" name="such">
<br>
<input type="submit" id="choose" value = "Enter">
</div>
</form>
<?php }
formu();
?>
<div id= "here"> </div>
And then my ideas:
if($_SERVER["REQUEST_METHOD"] == "POST"){
$w = $_POST['w'];
$sr = $_POST['sr'];
$comma = $_POST['comma'];
$space = $_POST['space'];
$other = $_POST['other'];
if (empty($w) || !($sr || $comma || $space || $other)){
echo "You have to enter the number and choose at least one separator!";
} else {
**/* here I've tried:
?> <script>
window.location = 'third.php'; //but it doesn't create POST table
</script>
<?php
require_once("third.php"); //but it attaches value with reloading the page, so first div shows up above my table
include "third.php"; //same as above
*/**
}
}
I've also tried Ajax script but it doesn't work as well:
<script>
var SubmitBtn2 = document.getElementById('choose');
SubmitBtn2.onclick = function(){
var formularz = document.getElementById('sec');
formularz.style.display = 'none';
var formularz1 = document.getElementById('first');
formularz1.style.display = 'none';
var title2 = document.getElementById('title2');
$(title2).hide();
var FormData = {plik: "<?php echo $_POST['radio']; ?>",
wiersz: "<?php echo $_POST['w']; ?>",
średnik: "<?php echo $_POST['sr']; ?>",
przecinek: "<?php echo $_POST['comma']; ?>",
spacja: "<?php echo $_POST['space']; ?>",
inne: "<?php echo $_POST['other']; ?>",
jakie: "<?php echo $_POST['such']; ?>"};
$(document.getElementById('back')).hide();
$.ajax({
type: 'POST',
url: "third.php",
data: FormData,
complete: function (reply) {
$.ajax({
type: 'POST',
url: "third.php",
complete: function (reply) {
$('here').append(reply);
}
});
}
});
}
</script>
EDIT:
I've tried to use event.preventDefault(); and now my code looks as below:
$(document.getElementById('choose')).click(function()
{ event.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$.get("test5new.csv", function(data) {
var build = '<table border="1" cellpadding="2" cellspacing="0" width="100%">\n';
var rows = data.split("\n");
var cut = rows.slice(<?php echo $w; ?>); //ponieważ tablice liczy się od 0
cut.forEach( function getvalues(thisRow) {
build += "<tr>";
var columns = thisRow.split("<?php echo $pattern; ?>");
for(var i=0;i<columns.length;i++){ build += "<td>" + columns[i] + "</td>"; }
build += "</tr>";
})
build += "</table>";
$(document.getElementById('wrap')).append(build);
});
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
but, although it does not refresh, it doesn't create POST neither. Please please help.

Categories