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');
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
}
I'm new to ajax and hoping someone can help figure out how to add two form inputs. I have a hidden input that is getting the total sheets from a database. I also have an addSheets input that is getting the total of sheets to add. I'm posting code from my modal as well as the ajax and action. Any advice is greatly appreciated.
(index)
<html>
<body>
<div class="modal fade" id="addSheetsModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add Paper</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body px-4">
<form action="" method="post" id="form-addSheets-data">
<input type="hidden" name="id" id="id">
<input type="hidden" name="sheets" id="sheets">
<div class="form-group">
<input type="text" name="addSheets" class="form-control" id="addSheets" placeholder="">
</div>
<div class="form-group">
<input type="submit" name="addSheetQty" id="addSheetQty" value="Add Paper" class="btn btn-success btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<script language="javascript" type="text/javascript">
// AJAX Edit Paper - Receive (Gets ID)
$("body").on("click", ".receiveBtn", function(e){
e.preventDefault();
r_edit_id = $(this).attr('id');
$.ajax({
url:"action.php",
type:"POST",
data:{r_edit_id:r_edit_id},
success:function(response){
data = JSON.parse(response);
console.log(data);
$("#id").val(data.id);
$("#sheets").val(data.sheets);
}
});
});
// Edit Paper - Update (Sums)
$("#addSheetQty").click(function(e){
if($("#form-addSheets-data")[0].checkValidity()){
e.preventDefault();
$.ajax({
url:"action.php",
type:"POST",
data: $("#form-addSheets-data").serialize()+"&action=addSheetQty",
success:function(response){
console.log(response);
Swal.fire({
title: 'Sheets added successfully!',
icon: 'success',
showConfirmButton: false,
timer: 1500
})
$("#addSheetsModal").modal('hide');
$("#form-addSheets-data")[0].reset();
showAllPapers();
}
});
}
});
</script>
<?php
// ACTION
if(isset($_POST['r_edit_id'])){
$id = $_POST['r_edit_id'];
$row = $db->getPaperById($id);
echo json_encode($row);
}
if(isset($_POST['action']) && $_POST['action'] == "addSheetQty"){
$id = $_POST['id'];
$sheets = $_POST['sheets'] + $_POST['addSheets'];
$db->updateSheetQty($id,$sheets);
}
?>
In the database the sheets column is varchar(255). In the php_error.log I'm getting this response: PHP Warning: A non-numeric value encountered in /Applications/MAMP/htdocs/PaperInventory/action.php on line 116 which is this line ($sheets = $_POST['sheets'] + $_POST['addSheets'];) in my code above.
Thanks for any input and help understanding this.
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 am trying to POST data from a form using jQuery & Ajax. However, when I check on my PHP to see if the form has been "submitted", it shows it has not because the MySQL code does not run. I am guessing my HTML is not setup correctly and therefore the Ajax request is not sending the data to my post-update.php script. Here is my code:
<script type="text/javascript">
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: dataString,
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
HTML:
<form action="">
<div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Remove Completion Date</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to remove the students Completion Date?</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn blue" data-dismiss="modal" id="ajax-remove-completion-date">Yes</button>
<input type="hidden" name="submitted" value="remove-completion-date" />
</div>
</div>
</form>
PHP:
<?
session_id();
session_start();
require_once('assets/includes/mysql-connect.php');
/*Check to see if the completion date is being removed*/
if ($_POST['submitted'] == 'remove-completion-date') {
$query = "UPDATE students SET completion_date = NULL, completed = NULL WHERE student_id = {$_SESSION['student_id']} LIMIT 1";
$result = mysqli_query($dbc, $query);
}
?>
Where does dataString come from?
It's better if you define the data you want to send as an object. It's more readable and it's automatically converted to a query String.
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: {
submitted: 'remove-completion-date'
},
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
If you want to take the value from the field, set submitted as:
$('input[name="submitted"]').val()
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);
.....