I want to add data to my database, and get back the response from php which accesses the database.
javascript code:
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
var responseText = "onbekend";
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
So when the a name isn't valid or is already in existence, I can add this message to a span element in my html.
This is my php code:
<?php
if($_POST)
{
// Create connection
$con=mysqli_connect("localhost","root","root","websitedb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = getdate();
$date_time = $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . " " . $date['hours'] . ":" . $date['minutes'] . ":" . $date['seconds'];
$uitdagerArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitdager'] . "'");
$uitgedaagdeArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitgedaagde'] . "'");
$uitdager = mysqli_fetch_array($uitdagerArray);
$uitgedaagde = mysqli_fetch_array($uitgedaagdeArray);
$uitdagerId = $uitdager['id'];
$uitgedaagdeId = $uitgedaagde['id'];
$sql="INSERT INTO duels (uitdager, uitgedaagde, aanmaakdatum, gespeeld) VALUES ('" . $uitdagerId . "','" . $uitgedaagdeId . "','" . $date_time . "','" . "0" . "')";
if(!mysqli_query($con,$sql)) {
echo mysql_errno() . ": " . mysql_error() . "\n";
}
else {
echo "Duel Toegevoegd";
}
mysqli_close($con);
}
?>
So is it possible that the text from echo in my php code will be passed to the 'response' from the succes function?
edit:
this is my html code
<div id="nieuwDuel">
<h2>Nieuw Duel</h2>
<form name="form" method="post">
Uitdager: <input type="text" id="naamUitdager" placeholder="naam uitdager">
Uitgedaagde: <input type="text" id="naamUitgedaagde" placeholder="naam uitgedaagde">
<input type="submit" class="nieuwDuelToevoegen">
</form>
<span id="duelToegevoegd" style="display:none"></span>
Home
</div>
I assume that your PHP code is right. then what you need to change is your jQuery code.
just change the following code :
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
into following :
responseText = response;
$('#duelToegevoegd').html(responseText);
I don't know what you are going to do with
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
So, I leave it out for now
hope it helps
Yes it should work. Try changing your JS to
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
console.log(response);//This will output the response you are getting to the console so you can check it
$("#duelToegevoegd").html(response);
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
Also I wouldn't echo out any errors you get back to the client
echo "Failed to connect to MySQL: " . mysqli_connect_error();
Although it depends who the user is, but you don't want anyone unauthorised to see these errors
Related
I am sending my form data through AJAX but for some reason my PHP script is not running. The test echo's Im using in my PHP script is not showing. The window.alert("success") does show but HIDE and SHOW form1 and form2 also does not work.
Here is the code:
$('#mainform').on('submit', function(event) {
//test for empty fields
//test for Bots
//insert data into DB
//pass t_code on to next form
//create a page number for tabs
event.preventDefault(); //stops form on submit
var a = document.forms["mainform"]["hidden"].value;
if (a === ""){
var formData = {};
$.each($("#mainform").serializeArray(), function (i, field) {
formData[field.name] = field.value;
});
$.ajax({
url: 'insert_tut_description.php',
data: formData,
method:'POST',
success: function(response) {
window.alert("success");
pnum = 1;
t_code = form.elements["t_code"].value;
$("#form1").hide();
$("#form2").show();
document.getElementById("pnum").innerHTML = pnum;
}
});
};
});
<?php
echo "php running";
require 'config/config.php';
$t_title = $conn->real_escape_string($_POST['t_title']);
$t_code = $conn->real_escape_string($_POST['t_code']);
$t_image = $conn->real_escape_string($_POST['t_image']);
$hidden = $conn->real_escape_string($_POST['hidden']);
$t_desc = $conn->real_escape_string($_POST['t_desc']);
$t_url = "something.php";
echo $t_title;
echo t_url;
if(empty($hidden)){
echo "hidden is empty";
$query = "INSERT into tutorial_list (title, description, t_code, t_url, image,) VALUES('" . $t_title . "','" . $t_desc . "','" . $t_code . "','" . $t_url . "','" . $t_image . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
} else {
$conn->close();
}
}
?>
I have an $.ajax function that posts to a php page and gets some results.
function GetLicenseCount(SoftwareNameFK, SoftwareTypeFK,LicenseMethodFK,MinistryFK )
{
$.ajax({
type: "GET",
url: "modules/SoftwareLicenseAllocations/GetLicenseCount.php",
data: {SoftwareName : SoftwareNameFK, SoftwareType: SoftwareTypeFK, LicenseMethod: LicenseMethodFK, Ministry: MinistryFK},
dataType: "json",
success: function(result) {
var LicenseCount = document.getElementById("txtLicenseCount");
var idHidden = document.getElementById("txtId");
//get id value from string, by using split and getting the first part before the delimeter
var id = result.split(",")[0];
//get second part of result using string
LicenseCount.value = result.split(",")[1];
idHidden.value = id;
},
error: function(reason) {
console.log(reason);
alert("Failed to get License Count");
}
});
}
GetLicenseCount.php
<?php
//Local include path format
set_include_path('C:\PROJECTS\BRIAN\AMS\Web Application;C:\PROJECTS\BRIAN\AMS\Web Application\inc\pear;C:\PROJECTS\BRIAN\AMS\Web Application\js;');
//Search Screen
require_once('vars.php');
require_once('funcs.php');
//read the parameter passed through URL
$SoftwareName = $_GET['SoftwareName'];
$SoftwareType = $_GET['SoftwareType'];
$LicenseMethod = $_GET['LicenseMethod'];
$Ministry = $_GET['Ministry'];
//formulate query - get all active departments
$queryString = "SELECT DISTINCT id, LicenseCount"
. " FROM SoftwareLicenseAllocations WHERE"
. " SoftwareTypeFK =" . $SoftwareType
. " AND SoftwareNameFK = " . $SoftwareName
. " AND LicenseMethodFK=" . $LicenseMethod
. " AND MinistryFK=" . $Ministry;
// $queryString = "SELECT DISTINCT LicenseCount"
// . " FROM SoftwareLicenseAllocations WHERE"
// . " SoftwareTypeFK =" . 2
// . " AND SoftwareNameFK = " . 2
// . " AND LicenseMethodFK=" . 2
// . " AND MinistryFK=" . 1 ;
$sla = GetOpenItDataSet($queryString);
//loop on result set to refresh the department options list
while ($row = mysql_fetch_array($sla))
{
$LicenseCount = $row["LicenseCount"];
$id = $row['id'];
}//endWhile
$_SESSION['id'] = 22;
//echo $departmentArray;
echo json_encode($id . "," . $LicenseCount);
//$_POST["lcID"] = $id;
I am trying to get one of the values passed on in the original page.
i tried using $_Session on GetLicenseCount.php but the variable remains null.
Is is possible to pass a variable from jQuery to PHP? If so, how?
EDIT:
The problem is that GetLicenseCount is supposed to pass id, which it is doing, but I cannot use it in the original page via PHP, only via jQuery. When I come to use the $_SESSION['id'] through the original/previous php page it remains null.. The jQuery block is contained in another php page.
My page lists out all of the rows from a MySQL table and puts them inside separate divs as links.
while($row = mysqli_fetch_array($result))
{
echo "<a href='projects/" . $row['dir'] . "'><div>";
echo "<h2>" . $row['name'] . "</h2>";
echo "<p>Created: " . $row['date_created'] . "</p>";
echo "<p>Last opened: " . $row['date_last_opened'] . "</p>";
echo "<p>" . $row['description'] . "</p>";
echo "</div></a>";
}
When I click on a box (div), it opens that specific project. What I need, is to update the 'date_last_opened' field for a project to the current date when I click into one. The column for it in the table is of type 'date'.
Thanks to anyone that can help.
Simple method would be use of Jquery and AJAX:
First add click function to your link in while loop like this:
echo "<a href='projects/" . $row['dir'] . "' onclick='update(".$row['name'].")';><div>";
and in your JS file use Jquery Ajax:
function update(name){
var now = new Date();
var dateToInsert = now.format("dd/M/yy h:mm tt");//or whatever format you need
var projectName = name;
$.ajax({
type: "POST",
url: "update.php",
data: { date: dateToInsert, name: projectName}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
and your update.php:
if(isset($_POST['date']) && $_POST['name']){
$sql = "update yourTable set date ='".$_POST['date']."' where name= '".$_POST['name']."'";
//Rest of the code to execute query
}
else{
echo "AJAX call failed to send post variables";
}
So I've got 2 boxes. On the left I have a list of items pulling from the database which I can drag and drop to the right. This works great. I can't for the life of me work out how to get it to post the data for the list on the right and I think I've tried every example Google has to offer this week.
When I do a print_r($_POST); on the page this submits to, I get Array ( ) with nothing in it. It doesn't seem to be grabbing the ID's and serializing them.
Does anyone have experience with this see anything I'm missing?
<script>
$(function() {
$( "ul.droptrue" ).sortable({
connectWith: "ul"
});
$( "ul.dropfalse" ).sortable({
connectWith: "ul",
dropOnEmpty: true
});
$( "#sortable1, #sortable2" ).disableSelection();
});
$( "#sortable2" ).sortable({
axis: 'y',
handle : '.handle',
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'setlists-edit-process.php'
});
}
});
</script>
<ul id="sortable1" class="droptrue">
<?php
$_GET['setlist_id'];
$sql = "SELECT material_id, material_name FROM material WHERE user_id=$session_id";
$result = mysqli_query($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
?>
</ul>
<ul id="sortable2" class="dropfalse">
</ul>
Replace this:
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
with:
while($row = mysqli_fetch_array($result))
{
echo '<li id="material_' . $row['material_id'] . '">' . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
Sortable expects the ID to be in the format setname_number.
Moreover, your code outputs in the format id=abc (no quotations), and rather it should be id="abc" with surrounding quotes.
I am trying to create a calender with a checkbox for each date. When a user clicks the submit button, I want to get those selected dates inserted into the database and those which are not selected would be deleted from the database if those already exist before. I have created a index.php page where I wrote the following code to generate dates:
index.php:
<form name="form1" method="post" action="show.php">
<?php
$year="2011";
$month="8";
$d=cal_days_in_month(CAL_GREGORIAN,1,2011);
$i=1;
while($i<=$d)
{
?>
<input type="checkbox" name="date[]" value="<? echo " $year-$month- " . $i . ""."<br>"; ?>">
<? echo " $year-$month- " . $i . ""."<br>"; ?>
<?
$i++;
}
?>
<input type="submit" name="Submit" value="Submit">
</form>
show.php:
<?
mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
$media_array = $_POST['date'];
foreach ($media_array as $one_media)
{
$source .= $one_media.", ";
}
$media = substr($source, 0, -2);
$query = "INSERT INTO table1 (id,media) VALUES('', '$media')";
$result = mysql_query($query); }
?>
And then I created page another page named show.php where I tried to write codes for inserting information, but I failed.
Would you please kindly help me to do this? I have tried my best but I couldn't make it happened. Thanks in advance.
The easiest way would be to make use of Ajax (going to use the JQuery library to make it a bit easier). So every time a checkbox changes values an Ajax request is triggered to updateDatabase.php and it either deletes or inserts a record.
So if you are showing your checkboxes on the page do:
<script>
$(document).ready(function() {
//Every time a checkbox changes (gets ticked or unticked) send n Ajax request
//to updateDatabase.php containing its value and a BOOLEAN checked/unchecked
$('input[type="checkbox"]').change(function() {
var checked = $(this).is(':checked');
$.ajax({
url: "updateDatabase.php",
type: "POST",
data: {value : $(this).val(),
checked : checked },
dataType: "html",
async:false,
success: function(msg) {
//Show the answer from the file in an alertbox.
//Use this to debug your code. Leave it out afterwards.
alert(msg);
}
});
});
});
</script>
So every time a checkbox is checked or unchecked it sends its value and the "checked" boolean value to updateDatabase.php.
In this file you can do something similar to:
updateDatabase.php
<?php
//Get POST variables
$value = mysql_real_escape_string($_POST['value']);
$checked = $_POST['checked'];
//If the checkbox was checked, INSERT its value into the database
//else you remove it.
if ($checked == true) {
$query = "INSERT INTO table (value) VALUES ('" . $value . "')";
}
else {
$query = "DELETE FROM table WHERE value = '" . $value . "'";
}
mysql_query($query);
?>
EDIT: Added the code to process the data after you click SUBMIT
If you do not want to do this on the flow
If you want to update your database when the user clicks SUBMIT, you simply submit the form to show.php.
show.php
<?php
$dates = $_POST["date"];
echo "Dates chosen: " . count($dates) . "<br /><br />";
if (count($dates)>0) {
echo "You picked the following dates:<br />";
}
for ($i=0; $i<count($dates); $i++) {
echo ($i+1) . ") " . $dates[$i] . "<br />";
mysql_query("INSERT INTO table (value) VALUES ('" . mysql_real_escape_string($dates[$i]) . "')");
}
?>
Hope this helps you!
(I did not test this code so I'm sorry if there are some minor errors in there still. But I'm sure you catch the drift!)