Usually with PHP and editing you click on a link that goes to a separate PHP page that has the "ID" of the entry you want to edit, you get the ID and populate your form base on this.
I would like to know how to do this if I am using a modal form? How do I get the ID get the records associated with it then populate the modal form.
sort of like this
//dropdown behavior for resp task and sub_task
$('#r_task_id').change(function() {
var selected_task_id = $('#r_task_id').val();
$.post("Assignment/populateSubTaskDropDown", { 'selected_task_id' : selected_task_id },//$_POST['selected_task_id']
function(data){
$('#r_sub_task_id').empty();
$.each(data, function(val, text) {
$('#r_sub_task_id').append(
$('<option></option>').val(val).html(text)
);
});}, "json");
});//task
PHP code is:
$this->session->set_userdata('selected_sub_task_id', $this->input->post('selected_sub_task_id'));
$json_resp_user = $this->assignmentModel->getResponsibleUsers($this->session->userdata('selected_sub_task_id'));
$json = array();
$json[0] = "-Select-";
if( count($json_resp_user) >= 1 ){ //if there is more in the result than the -Select-
foreach($json_resp_user as $detail){
//$json[$detail->user_id] = $detail->first_name." ".$detail->middle_name." ".$detail->last_name;
$json[$detail->user_id] = $detail->first_name." ".$detail->last_name;
}
}
echo json_encode($json);
but for the whole form not just a dropdown.
When you open the modal window set the id of the record in a public javascript variable, and on submit of the modal form pass the id parameter through url.
Another way is to have a hidden variable inside the form in the modal window and set it with the while opening the modal window. So it will be get passed the update form on the modal window is submitted.
<script>
id ='' //Set this when opening the modal window
function appendId(myform)
{
myform.action = myform.action + "/" + id;
return true;
}
</script>
<div id='modalWindow'>
<form onsubmit='return appendId(this)'>
//other elements
</form>
</div>
I had a quick read of $.post() of jQuery and apparently that was what I meant =p
the part on your script with
id ='' //Set this when opening the modal window
was where I was stuck on how to read that.
http://api.jquery.com/jQuery.post/
sorry if I wasn't clear but thank you for taking the time and trouble to answer me.
Related
I have multiple information boxes, with short info echoed from the database. at the bottom of each box is "more information" when click this triggers a modal.
The issue: at the moment when "more information" is clicked it displays the same information regardless of which info box was clicked.
The objective: When more information is clicked i need the respective information to be displayed. Some how referencing that row number X needs to be displayed when "more information" is click on that information box.
I tried is, but it didn't work:
jQuery(document).ready(function($) {
$('.moreinfo').click(function(event) {
var a = $(this);
// Get ID
var currentID = parseInt(a.data('id'));
$.ajax({
type : 'post',
url : 'ajax.php', // in here you should put your query
dataType: 'json',
data: {'vac_id': currentID}, // here you pass your id via ajax .
// in php you should use $_POST['post_id'] to get this value
success : function(json)
{
// Change the ID in modal
var m = $('#moreinfo'), mBody = m.find('.panel-body');
// Update new content
$('#vac_id').text(json.vac_id);
$('#vac_post_date').text(json.vac_post_date);
$('#vac_job_title').text(json.vac_job_title);
$('#vac_comp_name').text(json.vac_comp_name);
$('#job_description').text(json.job_description);
$('#vac_ess_one').text(json.vac_ess_one);
$('#vac_ess_two').text(json.vac_ess_two);
$('#vac_ess_three').text(json.vac_ess_three);
$('#vac_ess_four').text(json.vac_ess_four);
$('#vac_ess_five').text(json.vac_ess_five);
$('#vac_ess_six').text(json.vac_ess_six);
$('#vac_ess_seven').text(json.vac_ess_seven);
$('#vac_ess_eight').text(json.vac_ess_eight);
$('#vac_ess_nine').text(json.vac_ess_nine);
$('#vac_ess_ten').text(json.vac_ess_ten);
$('#vac_des_one').text(json.vac_des_one);
$('#vac_des_two').text(json.vac_des_two);
$('#vac_des_three').text(json.vac_des_three);
$('#vac_des_four').text(json.vac_des_four);
$('#vac_des_five').text(json.vac_des_five);
$('#vac_des_six').text(json.vac_des_six);
$('#vac_des_seven').text(json.vac_des_seven);
$('#vac_des_eight').text(json.vac_des_eight);
$('#vac_des_nine').text(json.vac_des_nine);
$('#vac_des_ten').text(json.vac_des_ten);
$('#vac_deadline').text(json.vac_deadline);
$('#apply_link').text(json.apply_link);
m.modal('show');
}
});
event.preventDefault();
});
});
Here you can see the modal and modal trigger: FIDDLE
Any help is genuinely appreciated.
Here's how I used to create dynamic modal/dialog:
var modal = $('#mymodal');
modal.find('.modal-title').text(newTitle); // Change modal title (optional)
modal.find('.modal-body').html(somethingNew); // Change modal content
modal.show();
For example: https://jsfiddle.net/3ey8tyz3/
I suppose when you load modal for the first time it gets cached and every time returns the same content.
You might need to clear the modal first and then reload on the basis of your id.
You can do-
$('#myModal').on('loaded.bs.modal',function(e){
}).on('hidden.bs.modal',function(e){
$(this).removeData('bs.modal');
});
Wrap this into a function and call it on document.ready
Im probably overlooking something very obvious but at this point i surrender and need help.
Here is my situation. When my page loads, in a while loops, PHP generates a table with data from my server. Each table row has a name column, phone, etc. One of the columns is an icon that when clicked allows the user to view a popup with notes on this particular lead. Easy stuff.
The icons in each row have the same class name and their ID's are unique.
I have an AJAX request that should be pulling the notes data from the server and displaying it in the popup when the user clicks on the relative icon. I am trying to use $('.class').click(this).attr('id'); to set a variable in my AJAX request with the id that needs to be submitted to my PHP script.
PROBLEM: The AJAX request and return seems to be working fine but no matter which row icon I click on it only displays the data that belongs to the first row, or the first instance with the class name 'homelead' Example: I click on row 1 icon and i get a popup with row 1's notes, GREAT!. I click on any other row and it only shows the 1st rows data, :(. I have confirmed that the ID's associated with each row icon are correct by doing a simple click.(this).(id) and alerting the id belonging to the row icon. All is correct, just can't seem to get the JS variable to update with the correct ID.
Im confused why this is. Any help would be appreciated. Here is my current code.
HTML:
<td>
<img class="homelead" id="<?php echo $leadsfetch['unit_id'];?>"
onclick="ajax_unitnotes();" src="images/list-view.png">
</td>
<?php echo "</tr>"; } ?>
AJAX request:
function ajax_unitnotes(){
var hr = new XMLHttpRequest();
var url = "PHP/getnotes.php";
// this variable should update with clicked rows id before submitting to PHP script
var unitidnotes = $('.homelead').click(this).attr('id');
var vars = "unitidnotes="+unitidnotes;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("unitnotes").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("unitnotes").innerHTML = "processing...";
}
As you are using an onclick trigger in the tag itself - which is usually un common when using jQuery. You can do this:
<img class="homelead" id="<?php echo $leadsfetch['unit_id'];?>"
onclick="ajax_unitnotes($(this));" src="images/list-view.png">
And the in your function
function ajax_unitnotes(e){
var unitidnotes = e.attr('id');
}
Your current code
var unitidnotes = $('.homelead').click(this).attr('id');
Actually does not know what it the this object you are trying to access.
Better yet you can use a jQuery event, remove the onclick from the img tag and have an event like this:
$('.homelead').click(function(){
id = $(this).attr('id');
});
You could pass the clicked object this to the function trigged by "onclick":
onclick="ajax_unitnotes(this);"
That will make the DOM object you clicked on available inside the JS function.
You need to change the function signature accordingly:
function ajax_unitnotes(clickedElement){
and then you can alter this
var unitidnotes = $('.homelead').click(this).attr('id');
to
var unitidnotes = clickedElement.id;
This will give you the value of $leadsfetch['unit_id'] = img id.
I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".
I have used same form for adding and edtting data. Adding and Editting is done successfully and I am refreshing after editing and adding. But I need some solution which is below
My jquery code is below
$(".update_vehicle_info").click(function(){
var hdn_id = $(this).attr('data-hdn_id');
$("#vehicle_form_div").find("#hdn_id").val(hdn_id);
var post_url = "<?php echo base_url();?>index.php/spc_con/get_vehicle_info_data/" + hdn_id;
$('#hdn_id').empty();
$.getJSON(post_url, function(response){
document.getElementById('financial_year_id').value = response.financial_year_id;
document.getElementById('vehicle_id').value = response.vehicle_id;
document.getElementById('brand_id').value = response.brand_id;
document.getElementById('country_id').value = response.country_id;
document.getElementById('reg_no').value = response.reg_no;
document.getElementById('capacity').value = response.capacity;
document.getElementById('running').value = response.running;
document.getElementById('serviceable').value = response.serviceable;
document.getElementById('condemned').value = response.condemned;
});
$("#vehicle_form_div").dialog("open");
});
I have screen shoot which is below
If i click edit button, if i don't edit now and if click Add Vehicle Info then edit field value has stayed but
I need when i click edit and click cross without editing. Then Page will be refresh/reload which if i click Add Vehicle Info then every field Data won't stay it.
How to solve it, Please help me.
UPD:
give to each of your tr some unique id, for example <tr id="tr_pk_23">...</tr> where 23 is a primary key of the row in you databse.
<button onClick="showModalForm(this,23);">EDIT</button>
function showModalForm(button,id){
var $tr = $(button).closest('tr');
/*
* Send ajax request to your php script /myScript.php?id=23
* Find data in database by id, and generate modal form with php, send it back to browser append to body and show it to user.
*/
}
Update button in modal form must be an ajaxButton. So onClick should be assigned as function
<button onClick="saveDataAndUpdateRow(this,23);">UPDATE</button>
JavaScript:
function saveDataAndUpdateRow(button,id){
var $form = $(button).closest('form');
var data = $form.serialize();
/*
* Send data to another script, save your data in DB and generate a new <tr> with updated values
*/
var $new_tr = #ajaxresponse;
var $old_tr = $('#tr_pk_'+id);
$old_tr.after($new_tr);
$old_tr.remove();
}
Feel free to ask me any questions about this concept.
I built a for each loop that pulls back several rows from the database. Each row it pulls has a link, and a hidden input box with a value of posting_id. This link will work similar to a like button on facebook in a way. The hidden input box just stores the posting_id. When you click the "like" link, it sends over the posting_id to a jQuery page and pings back a page called community to tell it the user has "liked" the post.
Here's the problem
I'm pulling several rows, and it seems that only the top row being pulled is actually sending the data to the jQuery page when you click the "like" button. If I click on any other "like" button other than the top one it will not work at all.
Jquery Page
$('.bump_link').click(function(){
var posting_id = $('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
Foreach Loop
foreach ($result as $value) {
$group_postings .= '
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
<div id="bump_icon" class="bump_link"></div>
<span id="counter"></span>
';
}
I hope I've made the issue clear, it was and is difficult to explain.
The problem is you are using a class to get the posting_id, since all the hidden fields have the same class only the first elements value is passed no matter what button you click.
i recommend using this html, without the hidden input, pass the value as a data attribute
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
and in this js, get the posting id from the data attribute
$('.bump_link').click(function(){
var posting_id = $(this).data('postid'); // get the posting id from data attribute
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
You are calling val() on selector you might return more then one elements, but val() will give you the value of one (first) element only. You can use map() to get all values of input having class posting_id
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');
Your problem is this line:
var posting_id = $('.posting_id').val();
This will return the first posting_id value every time, not the one associated with the bump_link you are clicking on.
There are lots of ways to solve this. One way is to use .prev() to select the previous element:
var posting_id = $(this).prev('.posting_id').val();
this selects the previous posting_id element from the current div. This relies on the fact that the posting_id element is before the associated bump_link div.
If you want to send just the posting_id of the clicked button, you could change your PHP/HTML code like this:
foreach ($result as $value) {
$group_postings .= '
<div id="bump_icon" class="bump_link">
<input type="text" class="posting_id" value="'.$value['posting_id'].'">
</div>
<span id="counter"></span>
';
}
And your JS code like this:
$('.bump_link').click(function(){
var posting_id = $(this).find('.posting_id').val();
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});
use on delegated event since you are adding the content dynamically and
$(this).prev('.posting_id') // to get the posting data value
$(document).on('click','.bump_link',function(){
var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this) reference
$.post("community.php", {
posting_id: posting_id
});
alert(posting_id);
$(this).toggleClass("bumped");
});