I have a table which displays user-data fetched from a mysql table.i want to make it editable right within the cells of this table. I have used php to show data inside \"text\"
Using ajax the basic:
Some basic notions of Server side and client side;
Ned some basic javascript(jquery) notions;
And some html and javascript basics.
For the first part:
Server-side programming is writing code that runs on the server, using languages supported by the server (such as Java, PHP, C#; it is possible to write code that executes on the server-side in JavaScript). Client-side programming is writing code that will run on the client, and is done in languages that can be executed by the browser, such as JavaScript, html and css.
For the second:
The ajax it's inportant to declare the jQuery Core.
Example:
<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
Use the last version jQuery Core.
Have the notion of who the AJAX works.
Ajax works doing this steps:
For more Use this link: https://www.w3schools.com/xml/ajax_intro.asp
Configure the Request:
url:
Type: String
Description: A string containing the URL to which the request is sent.
data:
Type: PlainObject or String or Array
Description: Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
dataType (default: Intelligent Guess (xml, json, script, or html)):
Type: String
Description: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
xml: Returns a XML document that can be processed via jQuery.
html: Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
script: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
json: Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.) jsonp: Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. text: A plain text string. multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
type (default: 'GET'):
Type: String
Description: The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). (version added: 1.9.0)
success:
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
Description: A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
For more information about configuration use the link: http://api.jquery.com/jquery.ajax/
Example:
AJAX:
$.ajax({
url: 'test.php',
type: 'POST',
datatype: 'Json',
data: {'var1': val_1, 'var2': val_2},
success: function (response) {
$('.search-results').html(response);
}
});
PHP:
$val = $_POST['var1'];//recive the values from ajax
$val = $_POST['var2'];
...// The code to recive and create html code.
echo json_encode($html);//send values back to the main page.
For the third and last part:
A full working exemple:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var var_1 =
$.ajax({
url: 'test.php',
type: 'POST',
datatype: 'Json',
data: {'q': str},
success: function (response) {
if(response.error_state = ""){
document.getElementById("txtHint").innerHTML = response.html;
}
else{
document.getElementById("txtHint").innerHTML = response.response.error_state;
}
}
});
}
}
</script>
</body>
</html>
Server side PHP (teste.php):
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_POST['q']);
$error_state = "";
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
//die('Could not connect: ' . mysqli_error($con));
$error_state = "<p>"."Could not connect:". mysqli_error($con)."</p>";
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
$html = "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
$html = $html. "<tr>";
$html = $html. "<td>" . $row['FirstName'] . "</td>";
$html = $html. "<td>" . $row['LastName'] . "</td>";
$html = $html. "<td>" . $row['Age'] . "</td>";
$html = $html. "<td>" . $row['Hometown'] . "</td>";
$html = $html. "<td>" . $row['Job'] . "</td>";
$html = $html. "</tr>";
}
$html = $html. "</table>";
mysqli_close($con);
echo json_encode (array(
'html'=>$html,
'error_state'=>$error_state
));
?>
</body>
</html>
Any doubt, just ask for my help.
Good work! And don't forget to accept the answer if it helps.
I managed the job by handling the form submission.However, I appreciate all for at least looking into this question.The errors were: 1. i didnt put the submit in any form tag premises and nor did i handle it using .submit() on click.
2. i was using type of button twice.. a. as "button" b. as "submit"