I already have implemented an ajax that send a tr and td to a html table every time that a element from the table of the DB is updated, i'll like to send the ajax html data to a append and send it from there to the body and not directly from ajax to the body, any one knows hoy?
this is my php:
<?php if($total>0 && $search!='')
{
do {
echo "<tr><form method='post' action='modifystatusdown.php'>
<td style='width:20%; '><input type='text'><input type='hidden'>";
echo $fila['nombre'];
echo "</td><td style='width:20%;'>";
echo $fila['telefono'];
echo "</td><td style='width:20%;'>";
echo "<input type='Submit' name='delete' value='Atendido'></td></form></tr>";
}
while ($fila=mysqli_fetch_assoc($resultado));
} ?>
this is send it to this ajax:
$(document).ready(function()
{
function actualizar()
{
value = $('#value').html();
$.ajax(
{
type: "POST",
url: "../solicitudes/buscador.php",
success: function(data)
{
$('#value').html(data);
}
})
}
setInterval(actualizar, 3000);
})
finaly from ajax its send it to a table inside a div:
<div class="container">
<table id="value">
</table>
</div>
how could i send it to the append and then to the table? instead directly from ajax?
the idea is something like this, in a table of the database I have a status column which is initialized to 0 and every time someone requests a service from an application android status is changed to 1, that I mentioned above is working, I want to achieve is that every time status is equal to 1, then appears in a html page , just as already appears in the html page, the problem is that assigned an input field where you can type in the text field the service to be assigned to the user requesting and as the table where they are inserted into the html refreshes every 5 seconds and you can not write in the text because it cleared everytime refreshes the table automatically ,
You can combine both $.post and $.get
ie $.post('url', {datatoappend: 'append'}, function(data){
$.get('urlwithsentdata', function(data){
});
});
this works nicely
Related
New to web dev so bear with me. In wordpress I have a functions.php file with a function that generates a chart and would take 2 dates as an input.
In my page-template.php I would take 2 date inputs and click generate to make a chart re-generate without reloading the page. I have a function with no arguments that runs on page load, and the button would load the alternate function that takes the two dates on button click.
Ajax seems to be the answer but most tutorials confuse me as their example require connecting to the DB or is focused on it exclusively. Wouldn't calling my function that does it already via wordpress functions handle that on their own? Is there a simple way to get my function called as it is while passing the two form values date1,date2? Truncated code to be hopefully readable.
Appreciate the help.
page-template.php: The first function is the one on load with default range (from functions.php file), then the date picker and button.
<?php
lineChartAll_Generate();
echo "<form>
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
</form>";
?>
functions.php: Using WP database function to run a select into a variable, then run the javascript code that generates the visuals of my chart.
<?php
add_action('wp_enqueue_scripts','enqueue_parent_styles');
function enqueue_parent_styles(){
wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
}
function lineChartCustom_Generate($date1,$date2){
//Database queries
global $wpdb;
$overallenergyResults = $wpdb->get_results
(
"SELECT QUERY GOES HERE"
);
// Line chart code
echo "
<div class='lineChartAll'>
<canvas id='myChart' width='400' height='200'></canvas>
<script>
//Chart javascript code goes here using $overallenergyResults variable
</script></div>";
}
?>
Here is a simple and working ajax program, check it to understand the process then customize it in the way you want.
The program gets two dates (date1, date2) from a form with id="my-form" and displays them into a div with id="display".
page-template.php:
<?php
echo "<script> const ajaxurl = '". admin_url('admin-ajax.php') ."' </script>"; // stores the ajaxurl into a js constant to be accissable in front-end page
?>
<form id='my-form'>
Select Dates: <br>
Date1: <input type='date' name='date1'><br>
Date2: <input type='date' name='date2'><br>
<button id='submit'> submit </button>
</form>
<div id='display' style="border: 1px solid; width: 200px; height: 100px;">
<em>submit the form to see dates here: </em>
</div>
<script type="text/javascript">
jQuery('#submit').on('click', function(event) {
event.preventDefault();
let date1 = jQuery('input[name="date1"]').val();
let date2 = jQuery('input[name="date2"]').val();
let formData = [date1, date2]; // prepare the form data as an array
jQuery.ajax({
url: ajaxurl, // ajaxurl defined at the top of the codes
type: 'POST',
data: {
action: 'your_custom_action', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP function by the name of dataForPHP
},
success: function(response) {
// show the response into dispaly div
jQuery('#display').html(response);
},
error: function(error) {
// show an oops! message
alert('oops! request failed.');
}
});
});
</script>
functions.php:
// ajax actions in wordpress must be handled by two actions: one with the prefex 'wp_ajax_' and another with the prefix 'wp_ajax_nopriv_'
add_action('wp_ajax_your_custom_action', 'your_custom_function');
add_action('wp_ajax_nopriv_your_custom_action', 'your_custom_function');
function your_custom_function() {
if ( isset( $_POST['dataForPHP'] ) ) {
// do anything you want with the submitted data, ex: running database query
$date1 = $_POST['dataForPHP'][0];
$date2 = $_POST['dataForPHP'][1];
}
echo "date 1: $date1 <br> date 2: $date2"; // send the response back to the client.
die();
}
Note: This function must have a response for the Ajax. the response can be JSON object or any string, if you would like to return HTML typography, just echo them as a string.
More about WP AJAX here: https://codex.wordpress.org/AJAX_in_Plugins
Yeah, Ajax is the solution for this issue, Here is the Ajax-using version of your code:
Form:
<?php
lineChartAll_Generate();
echo "<form id="my-form">
Select Date Range:
<input type='date' name='date1'>
<input type='date' name='date2'>
<button id='submit'> submit </button>
</form>";
?>
JavaScript/jQuery:
By clicking the submit button the jQuery collects the form data into an array and stores them in the formData variable, then submits it to the PHP with the name of dataForPHP and fires an ajax action hook by the name of your_custom_action
jQuery('#submit').on('click', function() {
let formData = jQuery('#my-form').serializeArray(); // retrieves the form's data as an array
jQuery.ajax({
url: ajaxurl, // default ajax url of wordpress
type: 'POST',
data: {
action: 'your_custom_action', // use this action to handle the event
dataForPHP: formData // this is your form's data that is going to be submitted to PHP by the name of dataForPHP
},
success: function( response ) {
// do what you want with the response echoed from PHP
},
error: function( error ) {
// show an oops! message
}
});
});
});
PHP:
PHP uses the fired ajax action by jQuery to run a function, so, add_action('wp_ajax_your_custom_action', 'your_custom_function'); means when the your_custom_action fired, run the your_custom_function.
add_action('wp_ajax_your_custom_action', 'your_custom_function'); // ajax actions in wordpress must have the prefex 'wp_ajax_'
function your_custom_function() {
if ( isset( $_POST['dataForPHP'] ) ) {
// do staffs with submitted data from the html form...
}
echo 'what you want to receive as a response in jQuery.ajax() success function'; // ignore this line if you don't want to receive any response.
}
This is a tough one to explain...
I'm developing a restaurant system where the user add the dishes available to sell, but the user has to have an option to edit/delete AFTER the dish was registered.
So what i thought was: k, gonna make a table fetching the data from the DB and in the last column put some options like edit/delete... Here is the code for better understanding:
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img src="img/icons/16/delete.png" alt="delete" height="16" width="16">'.'</td>';
echo '</tr>';
}
Like you've saw the delete option has already there (with no function/action yet) Here is the thing... I could put a link to a file in href="delete.php? but when a user clicks on this link will lead them to the delete.php page, leaving the administration page... I would like that when the user clicks the delete img, worked as/similar AJAX. I don't want the user exit the page....
Sorry for bad english (not my mothertongue), if you guys want more details just ask.
Ps: New PHP Programmer
Thanks in advance.
use javascript or jQuery to do an ajax request to delete.php with the id of the row you want to delete. I often put the id in the <tr> like echo "<tr data-id='{$row['id']}'>" and my jQuery would look something like this
$(".delete").on('click', function() {
var id= $(this).parents('tr').data('id');
$.ajax({
url:"delete.php",
type:"POST",
data:{id:id},
success:function(data, textStatus, jqXHR) {
// do something with the data returned. I usually output "success" from my
// delete.php and then check for data.indexOf('success') != -1
$("tr[data-id="+id+"]").remove();
},
error:function(jqXHR, textStatus, errorThrown) {
alert("Error: "+jqXHR+" "+textStatus+" "+errorThrown);
}
});
});
on my delete.php page i check that $_POST['id'] is not empty before continuing. If you use $_REQUEST['id'] it will also work with a direct link to delete.php?id=999
You can call Delete.php using AJAX, so the request is executed without leaving the page.
The advantage of making an actual link to the delete page, is that it also works without Ajax/Javascript. So you can start by building a plain delete page, and add the Ajax later.
First, you should also print a record_id because just deleting based on the name is a very bad idea where encoding will hunt you down.
Having said that, here is what I would do using jQuery:
//PHP
foreach ($result as $row){
echo '<tr>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '<td>'.$row['description'].'</td>';
echo '<td>'.'<img class="delete-btn" src="img/icons/16/delete.png" alt="delete" height="16" width="16" data-order-id="$row['id']">'.'</td>';
echo '</tr>';
}
//JQUERY
$(document).ready(function(){
$(".delete-btn").click(function(){
$.post("/delete.php", {order_id: $(this).attr("data-order-id")}, function(){
$(this).closest("tr").remove();
});
});
});
I'm trying to call a file from my server and return an HTML form. I asked a question here to get started but now I have another problem.
The textbox and submit button display, but since the data is JSON encoded and returned via AJAX to a DIV I'm not quite sure how to approach it.
Right now here's the result. Where I have "textbox and submit button" those elements are actually there. The other text appears around it.
testing
{"formHTML":"
"textbox here" " submit button here"<\/form>"}
Here's the code that would be on another server which calls to mine. This is the page that does the displaying
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<?php
echo "testing";
?>
<script>
$.ajax({
type: 'GET',
url: 'form_deliverer.php',
data: "true",
success: function(response) { // on success..
$('#yourdiv').html(response); // update the DIV
}
})
</script>
<div id = "yourdiv">
//form is displayed here
</div>
Here is the page that gets called, form_deliverer.php
<?
$o = new stdClass();
$o->formHTML = "<form method='post'><input type='textbox' name='text'/><input type='submit' name='submit_text'/></form>";
echo json_encode($o);
?>
Because AJAX automatically updates the div, how can I decode the data? Should I even do that?
For reference, this displays the form properly without the extra text. However, since I'll be calling from another server and have to deal with same domain issues, I'll have to use JSONP
<?
if(isset($_GET['true'])){
echo "
<form method='post'>
<input type='textbox' name='text'/>
<input type='submit' name='submit_text'/>
</form>
";
}
?>
You won't need to decode the data, though you will have to treat the response as an object. Because you json_encode()ed an stdClass, your ajax call will basically get something like this in return:
{"formHTML": "<form method='post'><input type='textbox' name='text'/><input type='submit' name='submit_text'/></form>"}
To access the string, you could simply write
$("#yourdiv").html(response.formHTML);
However, if you are only passing in the string, you could simply json_encode() the string instead of creating an object and then encoding that. That way, you can use response directly in your javascript.
form_deliverer.php
<?
echo json_encode("<form method='post'><input type='textbox' name='text'/><input type='submit' name='submit_text'/></form>");
?>
javascript
$.ajax({
type: 'GET',
url: 'form_deliverer.php',
data: "true",
success: function(response) { // on success..
$('#yourdiv').html(response); // update the DIV
}
})
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
NOTE: This question is a split from the post: 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');
}
});
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 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.
ok, previously i thought the mistake with the content type header of php file, still its there (you need to specify the header type to parse with jQuery JSON). But found one more mistake which i suppose the cause of the problem.
<form id='delete-group-form' action='php/delete_groups.php' method='post'>
and the form you wish to serialize is
$('#delete-groups-form').serialize()
You can see the difference in IDs. This will return an empty object, where in php file it expects the index called groups which never exists. Therefore it'll return an undefined index error as an html content type which starts with <html>, with that JSON parser return an error with unexpected token <
Hope this helps
When you call $_POST['groups']; (in your delete_groups.php) it looks for the content sent from the form element with an attribute name="groups", but your delete-group-form doesn't have any such element.
The "error unexpected token <" message may be from a separate issue. Validating your HTML might reveal the issue.
Also, I'm not entirely clear on why you're using two separate functions (the $.post in your JS and the $.ajax). Unless there's something else going on that I can't see from the code you've posted, you could simplify it considerably by just using one call to ajax. Put that one call inside the $('#delete-group-form').submit(function(e) in place of the $.post, and pass your groups variable using the ajax call's data parameter. Modify delete_groups.php to return the necessary information (currently returned from update_group_list.php) to update the display on your page.