I have this ajax function which inserts data using modal but I'm currently having a problem in passing the array values in my insert query. How can i convert the it to pass multiple information to my query ?
My input textbox in html
<input type="text" class="form-control text-center" id="author_lname[]" name="author_lname[]" placeholder="Last Name" required>
<input type="text" class="form-control text-center" placeholder="First Name" id="author_fname[]" name="author_fname[]" required>
<input type="text" class="form-control text-center" id="author_mname[]" name="author_mname[]" placeholder="Middle Name / Initial" required>
Ajax function
var getauthor_lname = $("#author_lname").val();
var getauthor_fname = $("#author_fname").val();
var getauthor_mname = $("#author_mname").val();
var whatprocess = "ADDBOOK";
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: {getauthor_lname:getauthor_lname,
getauthor_fname:getauthor_fname,
getauthor_mname:getauthor_mname ,
whatprocess : whatprocess
},
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: '',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
$("#datatables").load(window.location + " #datatables");
});
}
else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).catch(swal.noop)
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
PHP FOR INSERTING AUTHORS
$getauthor_lname = $_POST["getauthor_lname"];
$getauthor_fname = $_POST["getauthor_fname"];
$getauthor_mname = $_POST["getauthor_mname"];
for ($i = 0; $i < count($getauthor_fname); $i++) {
if ($getauthor_fname[$i] != "" && $getauthor_mname[$i] != "" && $getauthor_lname[$i] != "") {
$query = "INSERT INTO tbl_author (book_isbn, author_firstname, author_middlename, author_lastname) VALUES (? , ? , ? , ?)";
$stmt = $mysqlconnection->prepare($query);
$getauthor_lname[$i] = htmlspecialchars(strip_tags($getauthor_lname[$i]));
$getauthor_fname[$i] = htmlspecialchars(strip_tags($getauthor_fname[$i]));
$getauthor_mname[$i] = htmlspecialchars(strip_tags($getauthor_mname[$i]));
$stmt->bind_param("ssss", $getbook_isbn, $getauthor_fname[$i], $getauthor_mname[$i], $getauthor_lname[$i]);
$stmt->execute();
}else{
echo "ERRORauthor";
}
}
I would package all of my variables into an array and ship it from the AJAX call using data and unwrap the array at the PHP layer where i can the directly pass the values into the INSERT statement and just execute the query. I would think you validated your data already at the javascript layer to avoid data corruption. Hope this helps or reply if you have some more questions.
Quick question though: why do you have your id and name set to be arrays. I wouldn't think those are necessary for a single input field
var author_lname = $('#author_lname').val()
var author_fname = $('#author_fname').val()
var author_mname = $('#author_mname').val()
var whatprocess = 'ADDBOOK'
var entries = {'author_lname': author_lname, 'author_mname': author_mname, 'author_fname': author_fname, 'whatprocess': whatprocess}
var json = JSON.stringify(entries)
$.ajax({
url: 'functioncall.php',
method: 'POST',
data: { entry: entries },
success: function (data) {
console.log(data)
// var getdata = data.trim();
},
error: function (jqXHR, exception) {
console.log(jqXHR)
}
})
$author_fname = $author_info['author_fname'];
$author_mname = $author_info['author_mname'];
$author_lname = $author_info['author_lname'];
if ( !(empty($author_fname)) && !(empty($author_mname)) && !(empty($author_lname)) ) {
$query = "INSERT INTO tbl_author (book_isbn, author_firstname, author_middlename, author_lastname) VALUES (? , ? , ? , ?)";
$stmt = $mysqlconnection->prepare($query);
$stmt->bind_param("ssss", $getbook_isbn, $getauthor_fname[$i], $getauthor_mname[$i], htmlspecialchars(strip_tags($author_lname)));
$stmt->execute();
}
else{
echo "ERRORauthor";
}
Related
i have a form that works by filling the next select fields with data based on the previous ones, it works perfect on Localhost / Xampp with PHP8 but now when i try to get it on my server it only works "once" per category.
My problem simplified.
I select category1 and get two results based on that to the next select
Only one of these results works with returning data to the 3rd Select and the other one doesn't return anything with json_encode and only throws an error
More info:
Request that works.
{
"request": "2",
"subcategoryid": "11",
"alakategoriaID": "15"
}
[
Response which is correct.
{
"ID": "23",
"name": "Puu 25"
},
{
"ID": "24",
"name": "Puu 50"
}
Request that doesn't return anything
{
"request": "2",
"subcategoryid": "10",
"alakategoriaID": "15"
}
Main function that contains the select fields etc..
´´´<script>
$(function () {
// Country
$('#sel_country').change(function () {
var categoryID = $(this).val();
// Empty state and city dropdown
$('#sel_state').find('option').not(':first').remove();
$('#sel_city').find('option').not(':first').remove();
$('#varichanger').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 1,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_state").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 3,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#varichanger").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
// State
$('#sel_state').change(function () {
var subcategoryid = $(this).val();
var alakategoriaID = $('#sel_country').val();
// Empty city dropdown
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 2,
subcategoryid: subcategoryid,
alakategoriaID: alakategoriaID
},
dataType: 'json',
success: function (response) {
console.log(response);
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['ID'];
var name = response[i]['name'];
$("#sel_city").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});
</script>´´´
Helper.php
include "pdoconfig.php";
error_reporting(0);
$request = 0;$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Fetch subcategory list by categoryID
if(trim($request) == 1){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT * FROM alakategoriat WHERE kategoriaID=:kategoriaID ORDER BY subcategoryname");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$subcategorysList = $stmt->fetchAll();
$response = array();
foreach($subcategorysList as $subcategory){
$response[] = array(
"id" => $subcategory['id'],
"name" => $subcategory['subcategoryname']
);
}
echo json_encode($response);
exit;
}
// Fetch city list by subcategoryid
if(trim($request) == 2){
$kategoriaID = $_POST['alakategoriaID'];
$alakategoriaID = $_POST['subcategoryid'];
$stmt = $conn->prepare("SELECT * FROM tuotteet
WHERE kategoriaID=$kategoriaID
AND alakategoriaID=$alakategoriaID
ORDER BY productname");
$stmt->execute();
$productslist = $stmt->fetchAll();
$response = array();
foreach($productslist as $product){
$response[] = array(
"ID" => $product['ID'],
"name" => $product['productname']
);
}
echo json_encode($response);
exit;
}
if(trim($request) == 3){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT *
FROM kategoriavarit
INNER JOIN varit ON kategoriavarit.variID = varit.variID
WHERE kategoriaID=:kategoriaID");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$varilist = $stmt->fetchAll();
$response = array();
foreach($varilist as $vari){
$response[] = array(
"id" => $vari['variID'],
"name" => $vari['varinimi']
);
}
echo json_encode($response);
exit;
}
you have to save your first category value to session and use it for second time ajax call. As per your code you always get
trim($request) == 1
because each time ajax call it consider as new request. So use session or cookie for store and use parent category.
Solved the problem by clearing and reinserting my database values and following #Foramkumar Patel's answer
EDIT: Cancel that, problem was with scandinavian letters in the response from JSON causing many different problems, solved the problem by utf_8 encoding the response.
I want autocomplete value from two columns of MySql database table, One column have multiple similar values, In autocomplete window in case of similarity it should only display one of the similar values. And after select it should not be suggested in autocomplete window in next row.
HTML
<tr>
<td><input type="text" data-type="aTeam" id="team_1" class="team"></td>
<td><input type="text" id="score_1" ></td>
</tr>
<button type="button" id="addRow">Add Row</button>
JS
$(document).on('focus','.team',function(){
var type = $(this).data('type');
if(type ==='aTeam' )autoTypeNo= 0;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'fetch.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.aTeam,
value: item.aTeam,
data : item
};
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#team_'+id[1]).val(ui.item.data.aTeam);
$('#score_'+id[1]).val(ui.item.data.score);
}
});
});
//add row
var i=$('table tr').length;
$("#addRow").on('click',function(){
html = '<tr>';
html += '<td><input type="text" data-type="aTeam" id="team_'+i+'" class="team"></td>';
html += '<td><input type="text" id="score_'+i+'"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
PHP
<?php
require_once("config.php");
if(!empty($_POST['type'])){
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$query = $db->prepare("SELECT aTeam, bTeam FROM teams where UPPER($type) LIKE '".strtoupper($name)."%' limit 10 ");
$query->execute();
$data= array();
$i = 0;
while ($row = $query->fetch(PDO:: FETCH_ASSOC)) {
$data[$i]['aTeam'] = $row['aTeam'];
$data[$i]['bTeam'] = $row['bTeam'];
$data[$i]['score'] = $row['score'];
++$i;
}
echo json_encode($data);
}
Try this: (read the // {comment here} and just compare the code with yours to see what changed)
$(document).on('focus','.team',function(){
let type = $(this).data('type');
// `autoTypeNo` isn't used anywhere, so I commented out this.
//if(type ==='aTeam' )autoTypeNo= 0;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'fetch.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
let selected = [],
uniques = [],
choices = [];
$('tr .team[id^="team_"]').each(function(){
let value = this.value.trim().toLowerCase();
if (value && selected.indexOf(value) < 0) {
selected.push(value);
}
});
data.forEach(item => {
let value = item.aTeam.trim().toLowerCase(),
value2 = item.bTeam.trim().toLowerCase();
if (uniques.indexOf(value) < 0 && selected.indexOf(value) < 0) {
choices.push({
label: item.aTeam,
value: item.aTeam,
data: item,
type: 'aTeam'
});
uniques.push(value);
}
if (uniques.indexOf(value2) < 0 && selected.indexOf(value2) < 0) {
choices.push({
label: item.bTeam,
value: item.bTeam,
data: item,
type: 'bTeam'
});
uniques.push(value2);
}
});
response(choices);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
// Strips the 'team_' part, leaving just the number.
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#score_' + id_num).val(ui.item.data.score);
$(this).attr('data-type', ui.item.type); // Change to the correct type?
// Cancels default action, so that the above `jQuery.val()` call works.
return false;
}
});
});
//add row
// 'i' is too generic, so I renamed it to 'row_num'.
var row_num=$('table tr').length;
$("#addRow").on('click',function(){
// Increment before used.
row_num++;
let html = '<tr>';
html += '<td><input type="text" data-type="aTeam" id="team_' + row_num + '" class="team"></td>';
html += '<td><input type="text" id="score_' + row_num + '"></td>';
html += '</tr>';
$('table').append(html);
// Optional, but I like to focus on the `input` in the row that was just added.
$('#team_' + row_num).select();
});
UPDATE
I updated the JS code (above).
And note that for the PHP part, I changed the $query from:
$query = $db->prepare("SELECT aTeam, bTeam FROM teams where UPPER($type) LIKE '".strtoupper($name)."%' limit 10 ");
to:
$query = $db->prepare("SELECT aTeam, bTeam, score FROM teams where ( aTeam LIKE '".$name."%' OR bTeam LIKE '".$name."%' ) limit 10 ");
because without the OR bTeam LIKE '".$name."%', for example if you typed "d" and there were no aTeam starting with "d", then you know what would happen..
I have a text box where I search database for a specific information.
The PHP code when I just type and click on search is the following:
try
{
$date_emp = $_POST['date_emp'];
$val = $_POST['data1'];
$gender = $_POST['gen'];
if($date_emp == "choose" && $gender == "specify")
{
$search = "SELECT * FROM employee
WHERE emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
And here the AJAX script for it:
$("#search").click(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
//console.log(txt);
if(txt == '' && drop == "choose" && gender == "specify")
{
$("#txtSearch").css('border-color', 'red');
}
else
{
if(drop == "choose" && gender == "specify")
{
$.ajax
({
url: 'search.php',
type: 'POST',
data: {data1: txt, date_emp: drop, gen: gender},
dataType: 'JSON',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Something Wrong");
}
});
}
$("#date_employed, #sex").change(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
$.ajax({
url: 'search.php',
type: 'post',
data: {data1: txt, date_emp: drop, gen: gender},
datatype: 'json',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Couldn't find any data!");
}
});
});
}
});
WHERE gender and drop are 2 drop lists that forming a search filters
When I change one of the drop lists, per example, when I choose the date equal to: this week I should see in table 2 rows.
But I can only see them in the network (in devTool), and at console tab I see the following error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
[{"id":"48","0":"48","emp_name":"Alexa","1":"Alexa","position":"Secretary","2":"Secretary","salary":"8000","3":"8000","date_employed":"2016-02-23","4":"2016-02-23","gender":"female","5":"female"}]
The PHP code when I change drop lists is:
if($date_emp == "week" && $gender == "specify")
{
$search = "SELECT * FROM employee WHERE (emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val) AND date_employed > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
When you make an ajax call and expect the response to be a json you need to send a json header from the PHP
header('Content-Type: application/json');
echo json_encode($data);
Sending the json header from the PHP will turn the "res" param in your ajax to a json object and not a json string.
If you don't send the the header you need to parse the json string into a json object
var json = JSON.parse(res);
Good day, ive been reading all the possible questions and answers here in this site all day, i know im almost getting the right answer but it seems some of the suggestions here doesnt work for me.
I have a dynamic form where the user can add and remove text fields and submit the request through ajax and php. The form consist of two required text field and buttons to add and remove another field(aside from the two required fields). The user can submit the form even not using another extra field.
My problem is if I press the add button and later on decide to remove it, I am getting a '0' value in corresponding table in database even after pressing the remove button.
Here is my HTML:
<form method="POST">
<span class="text-label">Subject:</span>
<input type="text" name="subject" id="subject-field" placeholder="Subject name here" maxlength="10" class="record-input-forms" /> <span class="text-label">Section:</span>
<input type="text" name="section" id="section-field" placeholder="Subject section here" maxlength="3" class="record-input-forms" /> + <a class="remove-field" href="#" title="Remove student field">×</a> →
<div id="student-box-wrap"></div> <span id="status-message"></span> </form>
Here is my AJAX
$(document).ready(function() {
$("#save-button").click(function() {
var subject = $("input#subject-field").val();
if (subject == "") {
$('#status-message').css({
"color": "#ec3f8c"
});
$('#status-message').html('Please fill the subject fields');
return false;
}
var section = $("input#section-field").val();
if (section == "") {
$('#status-message').css({
"color": "#ec3f8c"
});
$('#status-message').html('Please fill the section fields');
return false;
}
var studid = [];
$('input[name="studid[]"]').map(function() {
studid.push($(this).val());
});
var dataString = 'subject=' + subject + '§ion=' + section + '&studid=' + studid;
$.ajax({
type: "POST",
url: 'save.php',
data: dataString,
dataType: "html",
success: function(data) {
$("input#subject-field").val('');
$("input#section-field").val('');
$("input#field-wrap").remove();
$("#status-message").css({
"color": "#39b1c6"
});
$("#status-message").html('Save successfully');
$("#status-message").fadeOut(2000);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
return false;
});
});
my Jquery counter
$(document).ready(function() {
var counter = 0;
$(".add-field").click(function() {
counter += 1;
$("#student-box-wrap").append('<div class="field-wrap-' + counter + '"><span id="number-' + counter + '">' + counter + '.</span> Student ID: <input type="text" name="studid[]" class="record-input-forms" /></div>');
});
$(".remove-field").click(function() {
if (counter == 0) {
alert("Nothing to remove!");
} else {
$(".field-wrap-" + counter + "").remove();
counter--;
}
});
});
And my PHP
<?php
require 'connection.php';
session_start();
$studid = (explode(",", $_POST['studid']));
$subject = mysql_real_escape_string(strtoupper($_POST['subject']));
$section = mysql_real_escape_string(strtoupper($_POST['section']));
$adminid = $_SESSION['AdminID'];
mysqli_query($con, "INSERT INTO tbl_subjects(SubjectName, SubjectSection, AdminID) VALUES ('$subject', '$section', '$adminid')");
if (!empty($studid) && !empty($name)) {
foreach ($studid as $new) {
$sql_1 = "INSERT INTO tbl_student(StudentID, SubjectID) VALUES ('$new', LAST_INSERT_ID())";
mysqli_query($con, $sql_1);
}
}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
?>
i used !empty in my php and im getting same result. If i dont press the add button at all, im not getting any issue. Its just about when pressing it and even after removing it the variable in ajax seems to carry an empty data to database.
I think your issue issue is that, in your PHP, you call $studid = (explode(",", $_POST['studid'])); before you check if the value is set.
From the docs for explode()
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
Effectively, you are calling explode() on an empty string and getting back your empty string.
In your PHP, try moving explode() inside the if statement, after you check if it is set like:
<?php
require 'connection.php';
session_start();
$subject = mysql_real_escape_string(strtoupper($_POST['subject']));
$section = mysql_real_escape_string(strtoupper($_POST['section']));
$adminid = $_SESSION['AdminID'];
mysqli_query($con, "INSERT INTO tbl_subjects(SubjectName, SubjectSection, AdminID) VALUES ('$subject', '$section', '$adminid')");
if ( isset( $_POST['studid'] )) {
$studid = (explode(",", $_POST['studid']));
foreach ($studid as $new) {
$sql_1 = "INSERT INTO tbl_student(StudentID, SubjectID) VALUES ('$new', LAST_INSERT_ID())";
mysqli_query($con, $sql_1);
}
}
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
?>
Also, in your jquery, change:
var dataString = 'subject=' + subject + '§ion=' + section + '§ion=' + section;
To:
// only add `studid` if there is one or more present
var studidStr = studid != '' ? '&studid=' + studid : '';
var dataString = 'subject=' + subject + '§ion=' + section + studidStr;
I'm trying to create a simple chat application that posts people's messages, and that gives the user an option to "reset" the chat which will delete all messages from the database so the user can start over. The messages post okay, but the reset button just sends an empty post (instead of deleting all current posts). I'm wondering what I'm doing wrong:
if ( isset($_POST['reset']) ) {
$sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':CHA' => $_POST['message']));
header( 'Location: '.sessionize('index.php') ) ;
return;
}
Per a comment below, I've updated my client side code to be:
<html>
<script type="text/javascript" src="<?php echo($CFG->staticroot); ?>/static/js/jquery-1.10.2.min.js"></script>
<body>
<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
<a style="color:grey" href="chatlist.php" target="_blank">Launch chatlist.php</a>
</form>
<p id="messages" >
<script type="text/javascript">
function htmlentities(str) {
return $('<div/>').text(str).html();
}
function updateMsg() {
window.console && console.log("Requesting JSON");
$.ajax({
url: '<?php echo(sessionize('chatlist.php')); ?>',
cache: false,
success: function(data){
window.console && console.log("JSON Received");
window.console && console.log(data);
$("#chatcontent").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#chatcontent").append("<p>"+entry[0] +
"<br/> "+entry[1]+"</p>\n");
window.console && console.log("entry " + entry[0]);
}
setTimeout('updateMsg()', 4000);
}
});
}
window.console && console.log("Startup complete");
updateMsg();
</script>
</p>
</body>
The code in its entirety, in case I've missed something/context is helpful:
<?php
require_once "../../config.php";
require_once $CFG->dirroot."/pdo.php";
require_once $CFG->dirroot."/lib/lms_lib.php";
// This is a very minimal index.php - just enough to launch
// chatlist.php with the PHPSESSIONID parameter
session_start();
// Retrieve the launch data if present
$LTI = requireData(array('user_id', 'result_id', 'role','link_id'));
$instructor = isset($LTI['role']) && $LTI['role'] == 1 ;
$p = $CFG->dbprefix;
if ( isset($_POST['message']) ) {
$sql = "INSERT INTO {$p}sample_chat
(link_id, user_id, chat, created_at)
VALUES (:LI, :UID, :CHA, NOW() )
ON DUPLICATE KEY
UPDATE chat = :CHA, created_at = NOW()";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':LI' => $LTI['link_id'],
':UID' => $LTI['user_id'],
':CHA' => $_POST['message']));
$messages = array();
header( 'Location: '.sessionize('index.php') ) ;
return;
}
if ( isset($_POST['reset']) ) {
$sql = "DELETE FROM {$p}sample_chat WHERE chat = :CHA";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(':CHA' => $_POST['message']));
header( 'Location: '.sessionize('index.php') ) ;
return;
}
?>
<html>
<script type="text/javascript" src="<?php echo($CFG->staticroot); ?>/static/js/jquery-1.10.2.min.js"></script>
<body>
<form id="chats" method="post">
<input type="text" size="60" name="message" />
<input type="submit" value="Chat"/>
<input type="submit" name="reset" value="Reset"/>
<a style="color:grey" href="chatlist.php" target="_blank">Launch chatlist.php</a>
</form>
<p id="messages" >
<script type="text/javascript">
function htmlentities(str) {
return $('<div/>').text(str).html();
}
function updateMsg() {
window.console && console.log("Requesting JSON");
$.ajax({
url: '<?php echo(sessionize('chatlist.php')); ?>',
cache: false,
success: function(data){
window.console && console.log("JSON Received");
window.console && console.log(data);
$("#chatcontent").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#chatcontent").append("<p>"+entry[0] +
"<br/> "+entry[1]+"</p>\n");
window.console && console.log("entry " + entry[0]);
}
setTimeout('updateMsg()', 4000);
}
});
}
window.console && console.log("Startup complete");
updateMsg();
</script>
</p>
</body>
Major issue:
$.getJSON('<?php echo(sessionize('chatlist.php')); ?>', function(data){
^^^--- using http GET
if ( isset($_POST['reset']) ) {
^^^^---expecting HTTP POST
.getJSON() is for GET requests only. If you want to use a POST, you'll have to use $.ajax() instead.
You are doing a GET request using ajax. Make a POST request. Add Type. For Example
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
I suggests best thing you can do is: Use PHP REQUEST variable. Using it use can accept either post or get requests. i.e. For example:
if ( isset($_REQUEST['reset']) ) {
/***Code to delete chat **/
}