mixing php with jquery - php

I build a table up of cameras using php. So upon entry I have a query that pulls all the data I need (this is Joomla, hence the weird functions):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type, camera_sensitivity, camera_user, camera_pass, camera_ip, camera_port FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
I then look through to create a table with the data I need (this is abbreviated):
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
...
<tbody>
<tr data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>">
<td>
<?php echo $result_cameras[$i]["camera_type"]; ?>
</td>
<td>
<?php echo $result_cameras[$i]["camera_name"]; ?>
</td>
...
<td>
<button id="axis-details" onclick="apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>');">API Key</button>
</td>
...
<?php
}
?>
I'd like to create a jquery ui dialog with a textarea and a url filled in. The dialog is easy:
$(document).ready(function() {
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ')
.append('<p><textarea id=\"textbox\">'+ENTER URL HERE+'</textarea></p>')
.append('<p>For more information see: setup</p>');
$dialog.dialog({
autoOpen: false,
title: 'API Key'
});
$('#axis-details').click(function(e) {
e.preventDefault();
$dialog.dialog('open');
});
});
The url is this:
"http://myhost.com/notify.php/" +'<?php echo $result_cameras[$i]["camera_hash"]; ?>';
The problem is how can I put that url in the jquery code (where it says "ENTER URL HERE")? I obviously can't use:
<?php echo $result_cameras[$i]["camera_hash"]; ?>
because that is only resolved in the PHP code where I loop to build an html table. Any suggestions are appreciated.

Foolowing will create dialog "on the fly"
First you have to use class instead of ID for your "axis_details" button. ID's must be unique in a page.
You aready have url in your data-has attribute in TR
$('.axis-details').click(function(e) {
e.preventDefault();
var url = $(this).closest('tr').data('hash');
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ').append('<p><textarea id=\"textbox\">' + url + '</textarea></p>').append('<p>For more information see: setup</p>');
$dialog.dialog({
title: 'API Key',
close: function() {
$(this).remove();
}
});
})

....
<button class="axis-details" data-url="<?php echo $result_cameras[$i]["camera_hash"] ?>">API Key</button>
....
....
var $dialog = $('<div id="dialog-container"></div>');
$dialog.append('Please copy this key for camera setup: ')
.append('<p><textarea class="url-container"></textarea></p>')
.append('<p>For more information see: setup</p>');
....
....
$(".axis-details").on("click", function()
{
var url = $(this).data("url");
$("#dialog-container").find(".url-container").val(url);
$dialog.dialog('open');
});
if you didn't, you have to append the dialog div to the document (i'm not sure)

First in your PHP file:
echo '<input type="hidden" value="'.$result_cameras[$i]["camera_hash"].'" class="cameraHash" />';
Then you need to modify your jQuery code so the appends happen the way you intend.
$(document).ready(function() {
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ');
//new code to count each instance found
var eachLink = $(".cameraHash").val();
$.each(eachLink, function(index,value){
$dialog.append('<p><textarea id=\"textbox-'+index+'\">http://myhost.com/notify.php/'+value+'</textarea></p>')
});
//end new code, but change the next .append to $dialog.append
$dialog.append('<p>For more information see: setup</p>');
$dialog.dialog({
autoOpen: false,
title: 'API Key'
});
The above function grabs each value of .cameraHash. It appends the same textarea (which I modified because the ID isn't unique in your post, so I used the 'index' of the links to represent the textbox. so that it's cohesive with the values) and inside of it uses the value of the cameraHash found at that specific index.

Related

Can I call jquery.ajax() with some other function?

I am using the jQuery DataTables plugin, it has one event, that on click of button we can add new row in table.
The jQuery code is as below:
$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
$('#addRow').on( 'click', function () {
t.row.add( [
counter,
'<select id="k'+counter+'" name="itemname'+counter+'" ><option>-------</option></select>' ,
'<input id="itemrate" name="itemqty'+counter+'" placeholder="Quantity" type="text">',
'<input id="itemrate" name="itemrate'+counter+'" placeholder="Rate" type="text">',
'<input id="totalamt" name="totalamt'+counter+'" placeholder="Total Amount" type="text">'
] ).draw();
counter++;
});
});
I want to fill data fetched from a MySQL database using jQuery .ajax(), and my code is as follows:
jQuery(document).ready(function(){
jQuery('#k'+counter).click(function(){
jQuery.ajax({
url: 'getData.php',
type:'POST',
data:'form_data='+val,
success:function(results){
jQuery('#k'+counter).html(results);
}
});
});
});
The code for getdata.php is as follows:
<?php
mysql_connect('localhost','root','');
mysql_select_db('eroyalsum');
$sql = "SELECT ITEMCODE,ITEMNAME FROM itemmaster1";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{
echo '<option value="'.$row[0].'" >'.$row[1].'</option>';
}
?>
Finally, my problem is when I write it as separate function, it just works only once. When I add other row it does not work, and when i write jQuery's .ajax() in one function it does not work...
try changing you selector from:
jQuery('#k'+counter).click(function(){
…
to
jQuery(document).on("change", "select[id^='k']", function(){
...
The issue is the event binding.
When you bind the event to the #k elements, the new item doesn't automatically get the event bound to it.
You can use stuff like :
$('body').on('click','.new_elements',function(){ //dostuff});
you can read more about it here
Event binding on dynamically created elements?

jQuery not working on elements created by jQuery

I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.
Below is the code for the ajax call.
$.ajax({
url: 'php/update_group_list.php',
data: '',
dataType: 'json',
success: function(data) {
var id = data.instructor_id;
group_cnt = data.group_cnt,
group_name = data.group_name,
group_code = data.group_code;
for (i = current_row; i < group_cnt; i++)
{
//setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);
$('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
$('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
"<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
"<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
"</fieldset>");
}
current_row = i;
$('#group-list').listview('refresh');
$('#delete-group-list').trigger('create');
}
});
Now I am having two problems
FIRST PROBLEM:
When I try to run the code below (it should show an alert box if any of the list items created in this line $('#group-list').blah...blah in the code above), nothing happens.
$(".view-group-btns").click(function()
{
alert("check");
});
SECOND PROBLEM:
Also when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <
What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.
Here is extra code relating to the SECOND problem
HTML:
<form id='delete-group-form' action='php/delete_groups.php' method='post'>
<h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
<div style='margin-top: 20px;'></div>
<div id='delete-group-list'>
</div>
<div style='margin-top: 20px;'></div>
<input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>
</form>
JS Code
$('#delete-group-form').submit(function(e)
{
e.preventDefault();
alert($('#delete-group-form').serialize());
if ($('#delete-group-form').serialize() == "")
{
alert('No groups selected to be deleted.')
return false;
}
else
if ($('#delete-groups-form').serialize() == null)
{
alert('No groups selected to be deleted.')
return false;
}
else
{
$.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data)
{
obj = jQuery.parseJSON(data);
var group_codes = obj.group_list;
alert(group_codes);
alert("The selected groups have been deleted");
window.setTimeout(2000);
return false;
});
}
return false;
});
delete_groups.php
<?php
$group_codes = $_POST['groups'];
$items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
echo json_encode($items); //sending data back through json encoding
?>
I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.
You need to use event delegation to make your newly-created elements function properly:
$("#group-list").on("click", ".view-group-btns", function() {
alert("check");
});
I noticed you have 3 single quotes on this line... missed one after controlgroup
$('#delete-group-list')."<fieldset data-role='controlgroup data-iconpos='right'>"
That would explain the unexpected token <
You have to use the jquery on event.
$(".view-group-btns").on("click", function(event)
{
alert("check");
});
Why?
Because you can only use the regular "click" on elements that are created BEFORE the DOM is updated.
When you are dynamically creating new elements into the dom tree, then you can't use .click anymore.
on (and in the past, .live(), which is deprecated now) can listen to modifications in the DOM tree and can use the later-on created elements.
You have to bind the click function after you get the element from ajax call. Binding on pageLoad event will only bind with those elements that are already in the dom. So do something like this.
$.ajax({
success : function(res){
//bind your click function after you update your html dom.
}
})

Codeigniter AJAX Example

I've been looking for a week now for a decent full working example of how to use AJAX with Codeigniter (I'm an AJAX novice). The posts / tuts I've seen are old - all the programming languages have moved on.
I want to have an input form on a page which returns something to the page (e.g. a variable, database query result or html formatted string) without needing to refresh the page. In this simple example is a page with an input field, which inserts the user input into a database. I'd like to load a different view once the input is submitted. If I could understand how to do this I'd be able to adapt it to do whatever I needed (and hopefully it would help others too!)
I have this in my 'test' controller:
function add(){
$name = $this->input->post('name');
if( $name ) {
$this->test_model->put( $name );
}
}
function ajax() {
$this->view_data["page_title"] = "Ajax Test";
$this->view_data["page_heading"] = "Ajax Test";
$data['names'] = $this->test_model->get(); //gets a list of names
if ( $this->input->is_ajax_request() ) {
$this->load->view('test/names_list', $data);
} else {
$this->load->view('test/default', $data);
}
}
Here is my view, named 'ajax' (so I access this through the URL www.mysite.com/test/ajax)
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery('#submit').click( function( e ) {
e.preventDefault();
var msg = jQuery('#name').val();
jQuery.post("
<?php echo base_url(); ?>
test/add", {name: msg}, function( r ) {
console.log(r);
});
});
});
</script>
<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
All that happens currently is that I type in an input, updates the database and displays the view "test/default" (it doesn't refresh the page, but doesn't display "test/names_list" as desired. Many thanks in advance for any help, and for putting me out of my misery!
Set unique id to the form:
echo form_open('test/add', array('id'=>'testajax'));
I assume that you want replace a form with a view:
jQuery(document).ready(function(){
var $=jQuery;
$('#testajax').submit(function(e){
var $this=$(this);
var msg = $this.find('#name').val();
$.post($this.attr('action'), {name: msg}, function(data) {
$this.replace($(data));
});
return false;
});
better way if you return url of view in json response:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$this.load(data.url);
},"json");
from your last comment - I strongly not suggest to replace body, it will be very hard to support such code.
but here is anser:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$('body').replace(data);
});

Deleting database records using jQuery AJAX is not working

I am trying to delete records from database without reloading the page. In the view file I have the following code. But when I click on the delete link nothing happens. Would you please kindly help me find out where I have done wrong?
Thanks in advance.
My view file:
<script type="text/javascript">
$(function(){ // added
$('a.delete').click(function(){
$.ajax({
var a_href = $('selector').attr('href');
type: "POST",
url: "<?php echo base_url(); ?>student_fee_status/payment_info_delete",
data: "id="+a_href,
success: function(html){
$("#show").html(html);
}
});
return false
});
}); // added
</script>
<?php if(count($records) > 0) { $i = 0; foreach ($records as $row){ $i++; ?>
<span> <?php echo $row['fee_type']; ?> : <?php echo $row['fee_amount']; ?> [<a id='<?php echo "$paymentid" ;?>'
class='delete' href='#'>Delete</a>]</span> <br>
<?php }} ?>
This is my Controller:
function payment_info_delete(){
$id = mysql_real_escape_string($_POST['id']);//Some clean up :)
$query= $this->db->delete('studentpayment2', array('pid' => $id));
echo "$id";
}
You need to put the 'var a_href...' line outside of the ajax function
You need to replace the word selector with this which refers to the currently clicked element.
var a_href = $(this).attr('href');
$.ajax({...
var a_href = $('selector').attr('href');
$.ajax({...
As mgraph pointed out in his answer, the var a_href = $('selector').attr('href'); line is incorrect. You want to replace 'selector' with this so that you're getting the href attribute from the anchor that was clicked on.
That said, I think that's still probably wrong - surely you want to be passing back the id of the entry to delete, which seems to be stored in the id attribute of the anchor tag, rather than always passing back a # symbol?
To pass the id back instead, rather than the href, replace this:
var a_href = $('selector').attr('href');
with this:
var a_href = this.id;

jquery/ ajax callback doesn't fire twice without a page reload. Part 1

I'm learning how to apply ajax to my jquery/php/mysql script for the purpose of callback firing. This question is probably from my ignorance when it come to the name of this term.
The Question: Is there a way to reset ajax callback without reloading the page script.
The Goal: I have a mysql query displaying on jQuery Accordian 1, 2, and 3. The goal is to click a query result href from Accordian and display the results in jQuery UI Tab 3 without a page reload...So far the script fires on my first callback but it doesn't fire a second time. Is there a term or jquery command that will reset jquery/ajax?
index.php
<?php
...script... include'right.content.php';
?>
<script type="text/javascript" >
$(function() {
$("#submit").click(function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
</script>
index.php - html section
<div id="stage">
<?php include'test.arena/test.php';?>
</div>
right.content.php
while ($row = mysql_fetch_array($result)){
if($row['stats'] == "1"){
$data .= "<tr><td colspan='2'>".$row['order_number']."</td>
<td colspan='2'>
<input type='hidden' id='string3' value='".$row['details']."'>
<input type='hidden' id='string2' value='".$row['order_number']."'>
<input type='button' id='submit' value='View'></td>
<td>info</td></tr>";
test.arena/test.php
if(!isset($_POST['string2'])){
$_POST['string2'] = "";
}else{
$string3 = "PO Number:" .$_POST['string3'];
$string2 = "Order:" .$_POST['string2'];
echo $string3 ."</br>";
echo $string2 ."</br>";
}
Is the element with ID 'submit' inside the one with ID 'stage'? If so, try changing $("#submit").click(function(){ to $("#submit").live('click', function(){.
The problem is probably because your submit button is inside of the 'stage' div. This means that when you load the new 'stage' content, it will delete the old button and add a new one and the new one won't have any click thing attached.
The quick fix for this is to use a 'live' handler.
$(function() {
$("#submit").live('click', function(){ // when submitted
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load('test.arena/test.php', {'string2':name, 'string3':lname,} );
});
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});
But the other solution, which might make the problem clearer, is to re-add the click handler after the load finishes.
$(function() {
function submitClicked() {
var name = $('#string2').val();
var lname = $('#string3').val(); // // POST name to php
$('#stage').load(
'test.arena/test.php',
{ 'string2':name, 'string3':lname },
function() {
addClickHandler();
}
); // display results from test.php into #stage
}
function addClickHandler() {
$('#submit').click(submitClicked);
}
addClickHandler();
$( "#tabs" ).tabs().find( ".ui-tabs-nav" );
$( "#accordion" ).accordion();
});

Categories