I have been working this for a while and have found numerous clues here on SO, but nothing is working yet. I'm trying to create a dynamic drop down in a form that the user can add to by selecting an "add new" option which brings up a modal window in which the new option can be typed. I use jquery to bring up the window and capture the input and ajax to (hopefully) post the text and retrieve it in php. I see on the console that that the new option is captured in the javascript and ajax makes a post, but the post array is empty.
My code is all in the view. When an "add new" is selected a modal window pops up in which text can be entered. I want to capture the entered text in the view without submitting and display it in the updated options list.
<legend>Animal Info</legend>
<div class="control-group <?php if (form_error('animal_species')) { echo 'error'; } ?>">
<label class="control-label">Species</label>
<div class="controls">
<?php # Add "Add New"
$options = $species + array('addnew' => 'Add New');
echo form_dropdown('animal_species', $options,
set_value('animal_species', (isset($my_data->animal_species)) ? $my_data->animal_species: ''),
'id = "animal_species"',
'class', 'addnew');
echo form_error('animal_species', '<span class="help-inline">', '</span>');
?>
</div>
</div>
<?php
if(isset($new_option))
{
$new_option = $_POST['new_option'];
$species = array($new_option => $new_option) + $species;
var_dump($new_option);
}
?>
<script type="text/javascript">
$('#upload_form option[value="addnew"]').click(function(){
// Show modal window
$('#add-new').modal('show');
$('#add-new-submit').on('click', function(){
// Get new option from text field
var new_option = $('#add-new-text').val();
console.log(new_option);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
data: {new_option:'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
$('#add-new').modal('toggle');
});
//});
});
</script>
<!-- add-new field -->
<div class="modal small hide fade" id="add-new" tabindex="-1" role="dialog" aria-labelledby="add-new-fieldLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="add-new-fieldLabel">Add New Field</h3>
</div>
<div class="modal-body">
<p>Would you like to add a new item?</p>
<input type="text" id="add-new-text" name="add-new" placeholder="Type the new option">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="add-new-submit" name="add-new-submit"/>Add</button>
</div>
</div><!-- /add-new field -->
Right now the string new_options gets captured in the console but is NULL in the php, so ajax isn't posting for some reason. Is this because I'm trying to update the same page?
Change it to :
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
dataType: 'text',
data: {new_option : 'new_option'}
}).fail(function (jqXHR, textStatus, errorThrown){
console.error("The following error occured: " + textStatus, errorThrown);
});
if you're going to be able to access it with :
$_POST['new_option'];
in PHP.
Without keys, it would be just $new_option = $_POST; to get the string
since you are taking your posted value as $_POST['new_option']..you need to pass the data object as new_option in ajax...
try this
...
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>main/upload_page",
dataType: 'text',
data:{'new_option':new_option}, //<---here
});
console.log(new_option);
.....
Related
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}
guys, I am trying to submit my form using ajax but I don't know exactly what happened it's not posting the values to my table in the database, This is the first time I am using ajax for form submit can anyone help me what mistake I have done.
Here is my view code:
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script type='text/javascript' src="<?php echo base_url(); ?>assets/theme1/js/jquery-2.1.3.min.js"></script>
<!-- <script type="text/javascript"> -->
<script type = "text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: 'json',
data: { organisation_name: organisation_name },
success: function(res) {
if (res) {
// Show Entered Value
jQuery("div#result").show();
jQuery("div#value").html(res.organisation_name);
}
}
});
});
});
</script>
<div class="modal fade" id="createGroup" tabindex="-1" role="dialog" aria-labelledby="createGroup" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
<form action="" id="user-groups-create" class="form-horizontal" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create a New Organisation</h4>
</div>
<div class="modal-body" id="modal-body">
<div class="form-group">
<label for="group_name" class="col-sm-4 control-label">New Organisation Name : </label>
<div class="col-md-8">
<input type="text" id="organisation_name" name="organisation_name" class="form-control" placeholder="Organisation Name" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="submit" class="btn btn-primary submit" id="submit">Create Organisation</button>
</div>
</form>
</div>
</div>
</div>
Here is my controller's method createOrg:
public function createOrg() {
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('organisation_name', 'organisation_name', 'required|min_length[5]|max_length[15]');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', 'Organisation name need to be more than 3 characters and less than 15.');
redirect('Organisation', $error);
} else {
//Setting values for tabel columns
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
//Loading View
redirect('Organisation');
}
}
Here is my Model's method orgInsert:
function orgInsert($data) {
// Inserting in Table(organisation)
$this->db->insert('organisation', $data);
}
Can anyone help me what mistake I have done and I have checked my code properly I didn't find exactly where I have done a mistake and I want my modal popup should be there after submitting it until a user clicks on the close button. when I try to keep alert after jQuery.ajax({ it is not coming alert.. and I can able to get the value from var organisation_name in alert...
Thanks in advance.
Hope this will work you :
$('#user-groups-create').on('submit',function(e){
var organisation_name = $("#organisation_name").val();
$.ajax({
type: "POST",
url: "<?=site_url('Organisation/createOrg');?>",
dataType: 'json',
data: {'organisation_name': organisation_name},
success: function(res) {
if (res)
{
alert(res);
window.location.href = "<?=site_url('Organisation');?>";
$("div#result").show();
$("div#value").html(res.organisation_name);
}
},
});
e.preventDefault();
});
Your controller's method createOrg should be like this :
public function createOrg()
{
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
echo json_encode($data);
exit;
}
}
Working by changing the script to like this
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: "html",
data: {organisation_name: organisation_name},
success: function(data) {
alert('success');
}
});
});
});
</script>
i had one search box in inside modal body . i created one search option for modal i had the result also but outside of modal search working fine but inside modal search results couldn't display any ideas?
My Modal Code :
<div id="myModal" class="modal fade" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div id="job-title-select2" style="display:none;">
<div class="form-group">
<input type="text" id="jobsearch" name="jobsearch" class="form-control" value="" placeholder="Enter Job Title....">
<input type="submit" id="title-button" class="btn btn-info btn" value="Confirm">
</div>
</div>
</div>
</div>
</div>
</div>
jquery code :
$("#jobsearch").autocomplete({
source: function(request, response) {
$.ajax({
url: "{{route('searchexistingjob')}}",
dataType: "json",
data: {term : request.term},
success: function(data) {
/////
}
});
},
minLength: 3,
});
output result in console :
[{id: 6, value: "Analytical thinker"}]
controller return value :
array (
0 =>
array (
'id' => 6,
'value' => 'Analytical thinker',
),
)
so i need to display the value.
Assuming your server side data will be like
$data = array (array ( 'id' => 6, 'value' => 'Analytical thinker'));
echo json_encode($data);
And in your ajax success pass your data back to ajax source response like below.
response(data);
So your ajax code will be,
$.ajax({
url: "{{route('searchexistingjob')}}",
dataType: "json",
data: {term : request.term},
success: function(data) {
response(data);
}
});
Note: If all works fine but still not displaying surely z-index causing the problem. So add below style and try,
.ui-autocomplete {
position:absolute;
cursor:default;
z-index:4000 !important
}
use the below code in your success function
obj = JSON.parse(data);
$("#jobsearch").val(obj.value);
$("#job-title-select2").show();
$('#myModal').modal('show');
I am listing user's records along with edit link, upon clicking on edit link bootstrap modal form loads
My Page has following code (not sure if there is any better way to create modal dynamically)
after changes when user submits modal form, modal will disappeared and update message will be shown on users.php page
but my alert box shows same form id for every modal's submit button i click (i.e. the first modal's form id) and shows blank datastring (form seriralize)
I want to pass respective form's data to process.php
below is part of my users.php
<?php whlie($row=mysql_fetch_array($result)){?>
<div id="editkey" class="modal hide fade" style="display: none; ">
<div class="modal-header">
<a class="close" data-dismiss="modal">X</a>
<h3>Edit users Details</h3>
</div>
<div>
<form id="keyfrm<?=$row['id'];?>">
<fieldset>
<input type="hidden" name="keyid" value="<?=$row['id'];?>">
<div class="modal-body">
<ul class="nav nav-list">
<li class="nav-header text-left"><p>Name :</p></li>
<li class="nav-header text-left"><p><input type="text" name="name"></p></li>
</ul>
</div>
<fieldset>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-success" id="submit">submit</button>
Close
</div>
I have js file that contains
$(document).ready(function(){
$('#submit').click(function() {
var formID = $('form').attr('id');
alert(formID);
var datastring = $(this).closest('form').serialize(); // may be working
alert(datastring);
$.ajax({
type: 'POST',
url: 'update_user.php',
data: datastring ,
success: function(msg) {
alert(msg);
var data=msg.split('|');
$(data[0]).modal('hide');
$('#result').html('');
$('#result').fadeOut("slow");
if(data[1]==='Success'){
$('#result').css('background-color','#DDF9B3');
$('#result').text("Data is updating...please wait for changes to take effect");
window.setTimeout(function(){location.reload()},3000)
}else{
$('#result').css('background-color','#FE9898');
$('#result').text("Error Occured");}
//$('#result').html(msg);
$('#result').fadeIn("slow");
$("#result").delay(4200).fadeOut(800);
}
});
event.preventDefault();
});
});
any help will be appreciated
Get the formID same way you get the data:
var formID = $(this).closest('form').attr('id');
alert(formID);
var datastring = $(this).closest('form').serialize();
I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>