SQL +AJAX + PHP POST REQUEST - php

Im trying to use PHP to delete a row in a SQL database.
The row is decided by the name of the product the user types in.
I created a simple form to delete products that have already been entered:
<article>
<section>
<fieldset><legend><span>Would you like to add a Product?</span> </legend>
<form method="POST" id = "myForm" name="myForm" onsubmit="return false;">
<br>
<p>Enter a name of product <input type='text' id='name' name = 'name'/></p>
<br>
<input name="submit" id ="submit" type="button" value="Find Product"/>
</form>
</fieldset>
<div id="fetchProduct">
</div>
</section>
</article>
Say I have already entered the data on another form and it goes into the database, but when I try to delete it I am getting the Undefined index: name in error when i try to delete.
Here is the script im using to delete the product:
<?php
include("database/connect_database.php");
$name = $_POST['name'];
$query = "DELETE FROM products WHERE product_name = '$name' ";
$result = $database->query($query) OR die ("Failed query $query");
echo $database->error."<p>";
if($result){
echo "Record deleted";
}
else {
echo "Product not found!";
}
?>
Im also using AJAX to pass through the name:
fetch = function () {
// declare the two variables that will be used
var xhr, target, changeListener;
// find the element that should be updated
target = document.getElementById("fetchProduct");
var name = document.getElementById("name").value;
var variable = "name="+name;
// create a request object
xhr = new XMLHttpRequest();
changeListener = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "deleteProductSQL.php", true);
xhr.onreadystatechange = changeListener;
xhr.send(variable);
};
pageLoaded = function () {
var fetchButton = document.getElementById("submit");
if (fetchButton) {
fetchButton.addEventListener("click", fetch);
}
};
window.onload = pageLoaded;
Could anyone point out where im going horribly wrong here because I just cant identify why it isn't allowing me to delete the row and why im receiving the undefined error.
Thankyou for your time

Put your PHP code in isset()
if (isset($_POST['name']){
//code here
}
Also
<p>Enter a name of product <input type='text' id='name' name = 'name'/></p>
In this line, <p> is not a self-closing tag so
<p>Enter a name of product <input type='text' id='name' name = 'name'></p>

Related

How to handle multiple forms?, stop reloading page on submit?

First form is where client can get all products by Make Model and Price as radio button with value of there id in database
Client click submit.
PHP ask isset name of submit button
If isset it echos second form where client can add specifications for product that he or she choose. Form is input type text and textarea's
Then php ask isset name of submit button for second form
but the problem is when client press submit for second form
If first form is unset then the rest of code should check that second form don't exist because both forms most exit for code to work and I can get that, if I don't find away to stop page reload on submit
I try using AJAX but the MySQL query throws an error that inputs are empty.
JavaScript code:
<script>
$( document ).ready(function() {
$('.link').click(function(){
$.post('ajax1.php?strana='+$(this).attr('strana'), function(odgovor) {
$('#odgovor').html(odgovor);
});
});
});
</script>
PHP code:
echo "<div class='container' id='cars'>
<div class='row'>
<div class='col-md-4 col-md-offset-4 text-center'>
<form action='' method='post' class='loginForm' id='cmsC' name='cmsC' enctype='multipart/form-data'>
<div class='input-group'>";
$sql="select * from produkt ";
$rez=mysqli_query($db,$sql);
while($red = mysqli_fetch_object($rez))
{
echo "<input type='radio' name='proizvod' value='$red->id'> ". $red->marka." ". $red->naziv." ". $red->cena."<br>";
}
echo "<input type='submit' id='btnsubmit1' name='btnsubmit1' class='form-control' value='Chouse Product' >
</div>
</form>
</div>
</div>
</div>";
if (isset($_POST['btnsubmit1'])) {
$id = $_POST['proizvod'];
echo "<div class='container'>
<div class='row'>
<div class='col-md-4 col-md-offset-4 text-center'>
<form action='' method='post' class='loginForm' id='cms' name='cms' enctype='multipart/form-data'>
<div class='input-group clear'>
<input type='text' id='dotm' name='dotm' class='form-control'
placeholder='Description Of The Motherboard ( ASUS H81M-R/C/SI )'>
<input type='text' id='top' name='top' class='form-control'
placeholder='Type Of Processor ( Intel® Core™ i3 Processor )'>"; // there is bunch more of this type for input type
if (isset($_POST['submit'])) {
// Variable with data from form
$description_of_the_motherboard = $_POST['dotm'];
$type_of_processor = $_POST['top'];
$processor_description = $_POST['pd'];
$type_of_graphics_card = $_POST['togc'];
if(strlen($description_of_the_motherboard)!="") {
if(!preg_match("/[^\w\s,.\\\'\"\-\/]/", $description_of_the_motherboard) {
$sql = "insert query";
mysqli_query($db, $sql);
} else echo "<script>
alert('Your input can not have special characters ');
</script>";
}
}
}
Just add a flag to avoid duplicate requests.
Example:
$( document ).ready(function() {
var iAmProcessing = false;
$('.link').click(function(){
if (iAmProcessing === true) {
return;
}
iAmProcessing = true;
$.post('ajax1.php?strana='+$(this).attr('strana'), function(odgovor) {
iAmProcessing = false;
$('#odgovor').html(odgovor);
});
});
});
data post most be into the array in second parameter.
<script>
$( document ).ready(function() {
$('.link').click(function(){
$.post('ajax1.php',{strana:$(this).attr('strana'),function(odgovor){
$('#odgovor').html(odgovor);
});
});
});
</script>

Difficulty processing data from jQuery post to pg_query();

Having the following difficulty.
I'm currently creating a form. This form is made in HTML and controlled by jQuery.
The form code is as following;
<div id="form">
<form>
<label>ID :</label>
<input type="text" id="clientid" /><br /><br />
<label>Name :</label>
<input type="text" id="name" /><br /><br />
<label>IP Address :</label>
<input type="text" id="ipaddress"/><br /><br />
<label>Status :</label>
<input type ="text" id ="status" />
<input type="button" id="button" value="Insert" /><br /><br /><br />
<label id="response"></label>
</form>
Now, this form picks up user data, and gets processed by the following jQuery script;
// Start jQuery script
// jQuery for dynamic adding without complete page reloads
//Wait for document readiness
$('document').ready(function() {
// Define submit button and action
$('#button').click(function() {
// Assign variable
if ($('#clientid').val() == "") {
alert("Enter Client ID");
return false;
} else {
var clientid = $('#name').val();
}
// Assign variable
if ($('#name').val() == ""){
alert("Enter Client full name");
return false;
} else {
var name =$('#name').val();
}
// Assign variable
if ($('#ipaddress').val() == "") {
alert("Enter Client owned IP address");
return false;
} else {
var ipaddress = $('#ipaddress').val();
}
// Assign variable
if ($('#status').val() == "") {
alert("Enter client status");
return false;
} else {
var status = $('#status').val();
}
// When variables are known, continue processing and POST'ing
// Posting to seperate PHP file to complete
jQuery.post("processing/addC.php", {
clientid: clientid,
name: name,
ipaddress: ipaddress,
status: status
},
function(data, textStatus) {
if (data == 1) {
$('#response').html("Insert successful!");
$('#response').css('color', 'green');
} else {
$('#response').html("Insertion failure. Please try again or restart.");
$('#response').css('color', 'red');
}
});
});
});
This code obviously passes the variables through a POST to addC.php.
addC.php contains the following code:
<?php
// Get current connection
include 'dbconnect.php';
$clientid = $_POST['clientid'];
$name = $_POST['name'];
$ipaddress = $_POST['ipaddress'];
$status = $_POST['status'];
$query = pg_query_params(
$dbconnection,
'INSERT INTO clients(clientid, name, ipaddress,status) VALUES ($1, $2, $3, $4);',
array($clientid, $name, $ipaddress, $status)
);
if(pg_affected_rows($query)>0){
echo "1";
}else{
echo "2";
}
?>
The desired result of this code is the if-statement returning a 1, so the jQuery can create a nice green message saying the database insertion went correct.
Now, as I validated the pg_query(); syntax to be correct, there must be something wrong in this code itself. What seems to be the problem here?
EDIT:
Following error;
Warning: pg_query_params(): Query failed: ERROR: invalid input syntax for integer: "michael" in /Applications/XAMPP/xamppfiles/htdocs/LoginHQ/processing/addC.php on line 18
invalid input syntax for integer: "michael"
It means that column has type integer, but you try insert string

how to run php code on submit button without refreshing/ reloading the page

I want to execute some php code on submit button click without refreshing/reloading my page. Is it possible? also i have javascript function on page load that's why i don't want to refresh my page.
thanks in advance.
<?php
if(isset($_POST["search"]))
{
$show = "SELECT * FROM data";
$rs = mysql_query($show) or die(mysql_error());
$add_to_textbox = "<input type='button' name='btn' value='add' />";
#****results in Grid****
echo "<table width='360px' border='1' cellpadding='2'>";
$rowID=1;
while($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td width='130px' id='name.$rowID.'>$row[Name]</td>";
echo "<td width='230px' id='link.$rowID.'><a href = '$row[Link]'>$row[Link]</a></td>";
echo "<td width='130px' onclick='Display($rowID);'>$add_to_textbox</td>";
echo "</tr>";
$rowID++;
}
echo "</table>";
#**********************
mysql_free_result($rs);
}
?>
<script type="text/javascript">
function Display(rowID){
var linkVal = document.getElementById('link'+rowID+'').innerHTML.replace(/<\/?[^>]+(>|$)/g, "\n");
document.getElementById("name").value = document.getElementById('name'+rowID+'').innerHTML;
document.getElementById("link").value = linkVal;
}
</script>
here is my code
Well, you need to use the javascript / ajax.
Example: on your submit link (a href for exaple), add call-in-to js function submitMe and pass on whatever variables you need
function submitMe() {
jQuery(function($) {
$.ajax( {
url : "some_php_page.php?action=getsession",
type : "GET",
success : function(data) {
alert ("works!"); //or use data string to show something else
}
});
});
}
IF you want to change some content dynamically, it is easy- you just need to create tags, and assign ID to them : <div id="Dynamic"> </div>
Then you load ANYTHING between those two tags using
document.getElementById("Dynamic").innerHTML = "<b>BOOM!</b>";
Meaning that you calling area between two tags and loading something into them. The same way you GET data from that place:
alert(document.getElementById("Dynamic").innerHTML);
Please read this:
http://www.tizag.com/javascriptT/javascript-getelementbyid.php
In addition, play and experiment with DOM elements and learn how they interact. It is not hard, just takes some time to grasp all concepts.
Whenever you send request ajax (with plain js anyway) from a html form, make sure you add the return false statement to prevent redirection:
something like:
<form method="post" ... onsubmit="ajax_post(); return false;">
You have to use ajax, but you can do it in plain javascript (without jquery). Jquery makes it easier.
plain javascript example: This function will trigger an ajax, via get, without parameter: you can tweak it so it run in POST and be able to send some parameter: file represent the php file to request and html represent the container whre the data will be displayed:
function plain_ajax(file,html){
if (window.XMLHttpRequest){
r=new XMLHttpRequest(); //For Most BRowser
} else{
r=new ActiveXObject("Microsoft.XMLHTTP"); //for Explorer
}
//When the state change
r.onreadystatechange=function(){
//ReadyState 4 = Loaded see: http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
//status 200 = ok see: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
if(r.readyState==4 && r.status==200){
//Replace the content with the response, Using creatDocumentFragment is more efficient
//at the cost of a few more lines But it would alos allow you to append the data
//instead of replacing it using innerHTML;
document.getElementById(html).innerHTML = r.responseText;
}
}
//Opening the connection and sending the request.
r.open("GET",file,true);
r.send();
}
Your HTML or PHP form
<form action="submit.php" method="post">
Name: <input name="name" id="name" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Phone Number: <input name="phone" id="phone" type="text" /><br />
<input type="button" id="searchForm" onclick="SubmitForm();" value="Send" />
</form>
Your JavaScript
<script>
function SubmitForm() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.post("submit.php", { name: name, email: email, phone: phone },
function(data) {
alert("Data Loaded: " + data);
});
}
</script>
Your PHP page to do some activity
<?php
echo $_POST['name']."<br />";
echo $_POST['email']."<br />";
echo $_POST['phone']."<br />";
echo "All Data Submitted Sucessfully!"
?>

Commenting System - Ajax, Php & MySql

I've succeeded to write a simple commenting system with a form of 2 fields: name and comment. When the user inters values and presses submit it simply adds the comment to the current page using Ajax (without loading the whole page).
Now, I need also to add the ability of "Deleting Comment", but I have no idea how can I implement that.
If you take a look at my code bellow you would notice that when loading the page I printed all the existing comments, and when adding new ones I simply added them to the HTML code by this sub-code:
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
I thought of declaring an array that holds the values of all the comments with an additional value for each one "active".
When this value is trua I print the current comment, else I dont.
I've not succeeded to implement that, besides, Is it a good solution at all?
cause this solution prints all the comments all over again each time the user presses submit.
Any suggestions?
I would appreciate your help.
This is My Code:
main.php
<html>
<head>
<title> </title>
<script language="Javascript" src="ajax.js"> </script>
</head>
<body>
<h1 align="center"><font color="#000080">Welcome, </font></h1>
<p align="center"><font color="#000080">Enter your name & comment then press
"Submit Button"</font></p>
<form name="f1" method="post">
<p align="center"><font color="#000080">
Enter your name: <input type="text" name="username" id="username">
<font color="#000080">
Enter your comment: <input type="text" name="comment" id="comment">
<input value="Submit" type="button"
onclick='JavaScript:postRequest()' name="showdate"></font></p>
</form>
</br></br>
<?php
include_once("config.php");
$query = "SELECT * FROM `comments` ORDER BY 'id'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center">';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
?>
<div id="result" align="center"> </div>
</body>
</html>
showcomments.php
name: ' .$name;
echo 'comment: ' .$content;
echo ''
?>
ajax.js
function postRequest() {
var xmlHttp;
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var usr=window.document.f1.username.value;
var cmnt=window.document.f1.comment.value;
var url = "showcomments.php?username=" + usr +"&comment=" + cmnt;
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange =function(){
if(xmlHttp.readyState == 4){
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(url);
}
function updatepage(str){
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
}
(P.S: I created a table using MySql named "comments" with the following columns: Id, Added_by, comment.)
I would not only print the name and comment in you PHP file, but also a form with a hidden field containing the ID. Or, even better, a button with a onClick="deleteComment(ID)". More importantly: place every comment in a p-tag with an ID, with id=comment-id. Your main.php PHP file would be expanded with this:
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center" id="'.$row['id'].'>';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
This (ajax)-function deleteComment(ID) then sends the ID of the comment to be deleted to another PHP-script. This deletes it from the database.
Now you have two options: you either delete the p-tag on the page by it's ID (this is very easy with jQuery with the function $('IDofP').empty(); ) or you reload all the comments.

Ajax Id Auto Incrementing

I will probably sound or look dumb by this but I need to learn. Check out the following part of a code:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
var yes = $("input#yes").val();
if (yes == "") {
return false;
}
var id = $("input#id").val();
if (id == "") {
return false;
}
var dataString = 'yes='+ yes + '&id=' + id;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: dataString,
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function(data) {
$("#div").hide(data).fadeOut();
$("#div").html(data);
$("#div").show(data).fadeIn();
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
My button ID that is being submitted in my html page is sending random numbers. For example
It can be:
$("#383").click(function() {
or it can be:
$("#521").click(function() {
My question is, how do I do it to auto increment the ID of the button clicked so that no matter what ID number is clicked it will still run the run the code smoothly... Right now I have this:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
Hopefully someone can help me... let me know if you need more info... Thank you in advanced...
Here is part of my HTML code... Hopefully it will be a little more understandable...
<?php
$data3 = mysql_query("SELECT * FROM `EdinburgCISDGorenamessage`
ORDER BY `ID` DESC LIMIT 0, 100")
or die(mysql_error());
echo "<div id=\"div\"> <table align=\"center\" width=\"570\">";
while($info3 = mysql_fetch_array( $data3 ))
{
$id = $info3['ID'];
}
?>
<form name="contact" id="post" method="post" action="">
<input id="id" value="<?php echo $id?>"/>
<input type="submit" class="buttonclass" id="<?php echo $id?>" name="<?php echo $id?>" value="Yes" />
<input type="submit" id="no<?php echo $id ?>" name="no<?php echo $id ?>" value=" No " /> </form>
I don' want to provide the whole code because its too messy and it doesn't go with the question... Let me know if you need anything else.
Use a class instead. Add a class to the button, and an incremental id you give it while printing it out in your html (I suppose you echo buttons in a loop?), and then just use one snippet:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
// your function here
alert(button_id); // just to see if ID is retrieved
)};
});
So, if you have
<button id="325" class="buttonclass" type="button">BUTTON 325</button>
<button id="150" class="buttonclass" type="button">BUTTON 150</button>
The ID of the button you click is retrieved only when you press it

Categories