Passing Javascript (HTML Table Contents) array to php file - php

Im very confused, I have been looking for a solution to pass HTML table contents via a javascript array (if this is indeed the best way of capturing HTML Table data) to a php file so I can then do whatever I like with the data.
I have simplified the table shown in my example code in order to make it easier, the table i will be using live will have a lot of rows with more complicated data etc.
The current code in get_table_data_php is:-
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div id ="results_table">
<table id="stats_table">
<tr>
<td>Car</td><td>Engine</td><td>Color</td><td>Price</td>
</tr>
<tr>
<td>Ford</td><td>2 Litre</td><td>Blue</td><td>22,000</td>
</tr>
<tr>
<td>Audi</td><td>2.5 Litre</td><td>White</td><td>25,000</td>
</tr>
</table>
</div>
<script>
var myTableArray = [];
$("table#stats_table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray); // alerts the entire array
alert(myTableArray[0][0]); // Alerts the first tabledata of the first tablerow
$.ajax({
type: "POST",
data: {myTableArray:myTableArray},
url: "stats.php",
success: function(msg){
$('.answer').html(msg);
}
});
</script>
The code in the stats.php file being called is as follows:-
<?php
var_dump($_POST);
?>
The code in the calling php file runs as expected and shows (via the alert(s) which are there for my sanity) the table data as expected.
The file called (stats.php) however does not do anything and as such I do not know if its working and what the issue is as to why it isn't.
I am pretty new to the Javascript and Ajax side of things so any help would be appreciated.
Regards
Alan

Related

Reload php include on button click

I am a beginner on using php mysql and basically what I am trying to do is in index.php on form submit it inserts the data in mysql and then I query and store 2-3 column values of same data in another php file lets say data.php. Now I have included data.php in index.php and on every submit want to reload data.php and display latest values from the same in a data table in index.php.
Long story short, reload a include php file containing variables on button click to display latest values everytime after form submit. Below is the code
<?php
include("data.php");
?>
<html>
<form id="signupform"></form>
<button onclick="postdata()"></button>
<table>
<tr>
<td>var1 in data.php:</td> <td>value of var1</td>
</tr>
<tr>
<td>var2 in data.php:</td> <td>value of var2</td>
</tr>
</table>
<script>
function postdata() {
var data = $("#signupform").serialize();
$.post('submit.php', data, function(data,status){
console.log("");
});
document.getElementById("var1").innerHTML = '<?php echo $var1; ?>' ;
document.getElementById("var2").innerHTML = '<?php echo $var2; ?>' ;
</script>
</html>
If its a form make the action="time.php" and on the time.php page after you insert the data use header("location: index.php");
PHP code is server-side code that finishes executing before the page is actually sent to the browser. What this effectively means is that you can't execute php code when the user does something like clicking a button.
There are effectively two solutions for 'reloading' the data from an included php file:
Reload the entire page after you've posted the form data:
$.post('submit.php', data, function(data,status){
console.log("");
window.location.reload();
});
Or fetch the output of the other PHP file (assuming data.php) with Jquery after your post to submit.php is done, and then insert the result into the DOM:
$.post('submit.php', data, function(data,status){
console.log("");
$.ajax({
url: "url/to/data.php",
method: "get",
success: function(output){
$("#html-element-id-here").html(output);
}
})
});

Ajax not sending PHP POST data

I'm using the following ajax script to POST data back after re-sorting the rows (which works fine). I'm not getting anything in the alert(data) that is being shown once I drag-and-drop the row. It should show me what it's trying to pass to the 'refresh_order.php' file.
I am NOT a jQuery or ajax expert -- I found this bit of code online and the first part works for me (the dragging and dropping) but I don't know what's wrong with the ajax that posts the data back to MySQL.
What do I need to do to fix this?
$('tbody').sortable({
cancel: ":input,button,[contenteditable]",
axis: "y",
update: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data); // Sent to server
$.ajax({
data: data,
type: 'POST',
url: 'refresh_order.php',
success: function(response) {
// alert(response); // Server response
}
});
}
});
[I have looked through most of the posts here on Stack Overflow and seen nothing that helps my situation. I even tried to reach out to the person who I got the code from but haven't received a response.]
From the documentation:
Note: If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number" For example, a 3 element list with id attributes "foo_1", "foo_5", "foo_2" will serialize to "foo[]=1&foo[]=5&foo[]=2". You can use an underscore, equal sign or hyphen to separate the set and number. For example "foo=1", "foo-1", and "foo_1" all serialize to "foo[]=1".
I assume your tr elements are missing the id attributes in the appropriate format. Here's a working example:
<table>
<tbody>
<tr id="tr_1">
<td>r1c1</td>
<td>r1c2</td>
</tr>
<tr id="tr_2">
<td>r2c1</td>
<td>r2c2</td>
</tr>
</tbody>
</table>
$('tbody').sortable({
cancel: ":input,button,[contenteditable]",
axis: "y",
update: function(event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
}
});
https://jsfiddle.net/bwxmfzs5/

Using a value from an Input, do a Select using that value, then return a json to an autocomplete

I'm new to Json, Ajax and Jquery, so this is turning out very frustrating.
I'm doing a code to autocomplete on a form using Jquery. My form consists in 4 elements:
1) Client
2) Requestor
3) Address
4) Email
So far, I can autocomplete the Client with this code:
<script type="text/javascript">
$(document).ready(function(){
$("#Client").autocomplete({
source:'getClient.php',
minLength:1
});
});
</script>
However, I need to get the next data (Requestors, Address...) using the Client's values instead of showing all the requestors and all the addresses from the database.
I've been trying for 3 hours and I just don't seem to get any data.
As an example, I've just set my Requestor input with an onclick.
<input type="text" name="Req" size="60" id="Reqt" onclick="getreq()"><br>
This was the last code attempt I've done so far:
<script type="text/javascript">
$(document).ready(function()
{
function getreq(){
//get the username
var Client = $('#Client').val();
//use ajax to run the check
$.ajax({
data: Client,
url: 'getReq.php',
type: 'post',
success: function (response) {
$("#Reqt").autocomplete({
source:'getReq.php',
minLength:1
});
}
});
}
});
</script>
And my PHP looks like this
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("test");
$client = mysql_real_escape_string($_POST['Client']);
$query=mysql_query('SELECT * FROM client WHERE Clients ="'.$client.'"');
$json=array();
while($Reqt=mysql_fetch_array($query)){
$json[]=array(
'value'=> $Reqt["Requestor"],
'label'=>$Reqt["Requestor"]
);
}
echo json_encode($json);
?>
Like I said, I've been trying this for hours and I'm pretty new to Json, Ajax and Jquery, but I need to use those technologies, I would really appreciate any and all insight. Thanks in advance!

How to use php and mysql functions inside javascripts

Here is my javascript code which is added in the tag of my php/html page:
<script type="text/javascript">
$(document).ready(function() {
$('#status').change(function(){
var status = $('#status').val();
var html = ''; //string variable for html code for fields
if( status=="closed"){
html += '<th>Close By :</th><td align="left"><select name="close_by">'+<?php $user=mysql_query("SELECT * FROM user");
while($data=mysql_fetch_array($user)){?>+'<option value="'+<?php echo $data['username'] ?>+'">'+<?php echo $data['username']; ?>+'</option>'+<?php } ?>+'</select></td>';
}
$('#close_by').html(html);
});
});
</script>
The code is for that, if Status=="closed" then a select tag will be appeared and the option values will be fetched from the database using mysql functions.But its not working. Please help to sort out this problem.
Thanks in advance.
You can't. PHP/MySQL reside on your server, while JS is executed in the browser.
Of course you may let the browser interact with your server by proper HTTP requests, after setting proper routes on your server.
You can mix PHP into Javascript. The PHP will execute on the server, and then the JS on the client. It's horrible though, extremely bad practice, and a nightmare to debug. Much better to seperate them out and use jQuery ajax to load the data.
Or use PHP to put the data into a JSON object at the start of the javascript, and process that with Javascript, rather than using PHP code to concatenate strings inside Javascript.
But in your example, what exactly is the problem? What is the end result of the PHP (in the HTML source) of the html variable? I suspect there's a bracket or quote wrong somewhere.
You can do it with ajax
$(document).ready(function() {
$('#status').change(function(){
var status = $('#status').val();
if( status=="closed"){
$.ajax({
url: 'ajax.php?',//if you have parameters
success:function (response) {
$('#close_by').html(response);
}
});
}
});
});
And you create a new php file for the ajax request
ajax.php
<th>Close By :</th>
<td align="left">
<select name="close_by">
<?php $user=mysql_query("SELECT * FROM user");
while($data=mysql_fetch_array($user)){?>
<option value="<?php echo $data['username'] ?>"><?php echo $data['username']; ?>
</option>
<?php } ?>
</select>
</td>

ajax to retrieve data from another page after post

I know this is very easy, but i only know the DOM equivalent of this code. the very long one. i've already searched trough some of the questions here in stack but i cant seem to find the solution.
so basically i have this script:
function searchNow(str)
{
$.ajax({
url: "search.php",
type: "POST",
async: false,
data: {"search": str},
success: function(data){
alert("test");
$("#result").html(data);
}
});
}
<table>
<tr>
<td>Search: </td>
<td><input type = "text" name = "search" onBlur="searchNow(this.value)"> </td>
</tr>
this will submit search to search.php to do a query search and retrieve the result and display it at id result.
i can do this easily using the old DOM ajax but then i wanna try using this jquery version instead since it is cleaner and maybe faster.
at my search.php
i have this:
$search = $_POST['search'];
return $search;
sadly i cant seem to return anything at all.
some input would be greatly appreciated, im already starting to be familiar with jquery ajax but only on the same page, not on inter page manipulation.
thank you,
-magician
Your PHP file should output the value. The ajax is going read that page and get it's content.
$search = $_POST['search'];
echo $search;
You want to be doing echo $search rather than return.
You can also add print_r($_POST); to take a look at what is going on in the PHP side of things.
Once you see what that is doing you can develop your php script a little further.
// Sets the correct response type
header('Content-type: application/json');
// get your search string/query
$search = $_POST['search'];
/*
* Do whatever you need in order to get a result
*/
echo json_encode($result);
exit;
If you are passing the search query to a database be sure to read Nettuts great intro to PDO. There are a lot of common pitfalls that can lead to security issues/exploits - avoiding one of the main ones (SQL injection) is covered in that post.
As per your comment, make sure your page with the search field is properly including jquery in the right place (sorry I don't mean to patronise if this is obvious!)
<html>
<head>
<title>Jquery Ajax</title>
<!-- google nicely host jquery for free... -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function searchNow(str)
{
$.ajax({
url: "search.php",
type: "POST",
data: { "search": str },
success: function(data) {
alert("test");
$("#result").html(data);
}
});
}
</script>
<table>
<tr>
<td>Search: </td>
<td><input type="text" name="search" onBlur="searchNow(this.value)" /></td>
</tr>
</table>
<div id="results"></div>
</body>
</html>
Dont forget to create an HTML element with ID="result" used by the selector to contain the result printed by your search.php.
$("#result").html(data);
Your PHP file should output the value. The ajax is going read that page and get it's content.
$search = $_POST['search'];
echo $search;
Also, the success option is set to be deprecated in the future releases of jQuery. You should instead use .done(callbackFunction) like so:
$.ajax({
url: 'beh.php',
type: 'POST',
data: {search: "beeeeeeeh"}
}).done(function () {
// do stuff
})
Also, is there any reason in particular why you are setting async to false?
I tried using
type: 'GET'
and in php file, got the value as
$search = $_GET['search'];
echo $search;
It worked. Hope it works for you also.

Categories