Load php file with ajax - javascript

Im using ajax to load the testNew.php file into the Cart.html file. It loads the testNew.php file but when i click on the button add which is in the testNew.php, 0 is being entered in the database and as soon as i click on the add button the page refresh by itself. My problem is that i dont want the page to refresh and want the add button to do the same action as in the testNew.php file(which works correctly).
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function() {
$("#product").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "testNew.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
</head>
<body>
<table border="1">
<tr>
<td>
<input type="button" id="product" name="product"value="View all products"/>
</td>
</tr>
</table>
<div id="responsecontainer"></div>
Here is the testNew.php which works correctly.
<?php
include'connect.php';
$image = isset($_REQUEST['image']) ? $_REQUEST['image'] : "";
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : "";
$name = isset($_REQUEST['name']) ? $_REQUEST['name'] : "";
$price= isset($_REQUEST['price']) ? $_REQUEST['price'] : "";
$sql="SELECT * FROM product";
$result = mysql_query($sql);
if($result>0){
?>
<table border='1'>
<tr>
<th>Id</th>
<th>Image</th>
<th>Name</th>
<th>Price MUR</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo ($row['id']); ?></td>
<td><img src=<?php echo $row['image'] ?> width='120'
height='100'/></td>
<td><?php echo htmlspecialchars($row['name']); ?></td>
<td><?php echo htmlspecialchars($row['price']); ?></td>
<td>
<form method="POST" action="" >
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="hidden" name="image" value="<?php echo $row['image']; ?>" />
<input type="hidden" name="price" value="<?php echo $row['price']; ?>" />
<input id="submit" type="submit" name="submit" value='Add to cart'
onclick="add()"/>
</form>
</td>
</tr>
<?php
}
?>
</table>
<?php
}
$insert = "INSERT INTO product_add(id, name, price) VALUES ('$id', '$name','$price')";
$insertQuery=mysql_query($insert);
?>

Your error in thought is actually that you are including a form through AJAX of which the HTML is then loaded into your page after which the action attribute on the form refers to the page itself (loading HTML into your page with AJAX does not work the same as an iframe) which does not have the relevant code to actually parse and insert the database.
You need to make a separate page that only accepts a few parameters and inserts those into the database. However, before you do that you need to read this:
I'm going to go off on the safety of your code for a tad.
$_REQUEST refers to both $_GET and $_POST, you really want only $_POST as you just want to deal with what gets submitted through a form.
You never sanitize your input, this way a person could craft an URL with say phpNew.php?id='; DROP TABLE wooptiedoo. This is a simplified example but nevertheless you should take a closer look at the mysql_real_escape_string documentation and possibly some guides on "sql injection".
After that those same variables can be used for XSS which means someone can use your page to serve random HTML to people visiting that site and trusting your domain. I suggest you look up the htmlentities function and/or read up on "cross-site scripting" attacks.
And to end it all, the mysql_* functions are deprecated and you should probably be using mysqli_* functions.

Related

Error in Image resizing JavaScript

I am resizing image before upload with JavaScript library the link is here https://gist.github.com/dcollien/312bce1270a5f511bf4a It has successfully created the blob.My html form is here:
<form action="/" class="data-form" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td><?php echo $form['title']->renderLabel(); ?> </td>
<td><?php echo $form['title']->render(); ?>
<?php echo $form['title']->renderError(); ?>
</td>
</tr>
<tr>
<td><?php echo $form['patient_name']->renderLabel(); ?> </td>
<td><?php
echo $form['patient_name']->render();
echo $form['patient_name']->renderError(); ?>
</td>
</tr>
<tr>
<td><?php echo $form['thumbnail']->renderLabel(); ?> </td>
<td><?php
echo $form['thumbnail']->render();
echo $form['thumbnail']->renderError(); ?>
</td>
<td><img id="preview">
</td>
</tr>
<input class="button" type="Submit" value="Save" />
</form>
My JavaScript code is here:
<script>
document.getElementById('clinic_stories_thumbnail').onchange = function(evt) {
ImageTools.resize(this.files[0], {
width: 300, // maximum width
height: 250 // maximum height
}, function(blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
document.getElementById('preview').src = window.URL.createObjectURL(blob);
$("#clinic_stories_thumbnail").attr('value',blob);
});
};
I am stuck how to upload the resized blob to server. I have appended the blob with input field through its value attribute. But the field does not get this and the form is submitted with the original image.So please advice how should I send the blob with same POST request. I don't want to submit a separate request for the blob. I want to submit the blob to server with the existing post request.

How to hide the result table on search bar?

I am not really good in coding, I need a help with my code. I have a code to search in a database. Now it's showing all the data on the database, when somebody search, it will filter out and show me result on the same table.I only want to show the result, when somebody search on the search bar, it should show me the filtered data. otherwise, my table should be hidden.
Can anybody please tell me how to do that. Thank you so much for your time.
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `ADDRESS` WHERE CONCAT(`ID`, `STATE`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `ADDRESS`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost:3306", "root", "dbadmin", "simplymac");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>SimplyMac PO Tracking Tool</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<style>
</style>
</head>
<body>
<div class="images-wrapper">
<img class="Large" src="/dbadmin/Images/simplymac_logo.png" width="320" height="140" />
</div>
<form action="index.php" method="post">
<div class="wrap">
<center><h3>PO TRACKING TOOL</h3></center>
<center><table>
<tr>
<td><input type="text" name="valueToSearch" placeholder="Enter Purchase Order (PO#) Number" size="100" class="searchbar"></td>
<td><input type="submit" name="search" value="SEARCH" class="Button"></td>
</tr>
</table></center>
</div>
<table class="resultdata">
<tr>
<th>ID</th>
<th>ADDRESS_LINE_1</th>
<th>ADDRESS_LINE_2</th>
<th>CITY</th>
<th>STATE</th>
<th>ZIP</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['ID'];?></td>
<td><?php echo $row['ADDRESS_LINE_1'];?></td>
<td><?php echo $row['ADDRESS_LINE_2'];?></td>
<td><?php echo $row['CITY'];?></td>
<td><?php echo $row['STATE'];?></td>
<td><?php echo $row['ZIP'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
You can use ajax for your problem.
When customer type in text box at that time call one java script function, in this function get text box value and call ajax for result table.
function getResult(search)
{
var file_path = '';//your php file path
$.ajax({
type: "POST",
url: file_path,
data: search,
cache: false,
success: function(result){
//print result in one div
}
});
}
<input type="submit" name="search" value="SEARCH" class="Button" onClick="getResult(this.value);">

Dropdown select , update user account activate/deactivate

I'm new in php how can I make this work
delete.php
<?php
include_once 'dbconfig.php';
if($_POST['del_id'])
{
$id = $_POST['del_id'];
$stmt=$db_con->prepare("UPDATE tbluser set status=1 WHERE id=:id");
$stmt->execute(array(':id'=>$id));
}
?>
I want to add an active/inactive dropdown choice in my edit form page but I dont know how to make it work I dont know how to call the delete.php so that when i choose inactive and submit the form it will not show on my datatable
edit_form.php
<?php
include_once 'dbconfig.php';
if($_GET['edit_id'])
{
$id = $_GET['edit_id'];
$stmt=$db_con->prepare("SELECT * FROM tbluser WHERE id=:id");
$stmt->execute(array(':id'=>$id));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<div id="dis">
</div>
<form method='post' id='emp-UpdateForm' action='#'>
<table class='table table-bordered'>
<input type='hidden' name='id' value='<?php echo $row['id']; ?>' />
<tr>
<td>Status</td>
<td><select name=stats>
<option value="1">Active</option>
<option value="0">Inactive</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-primary" name="btn-update" id="btn-update">
<span class="glyphicon glyphicon-plus"></span> Save Updates
</button>
</td>
</tr>
</table>
everything is working it's just an additional functionality in the edit form page
Get the stats like $status= $_POST['stats']; in delete.php
change you $_GET['edit_id'] to $_GET['id']
modify you updated to set the status
$id = $_POST['id'];
$status = $_POST['stats']
$stmt=$db_con->prepare("UPDATE tbluser set status=:status WHERE id=:id");
$stmt->execute(array(':status'=>$status,':id'=>$id));
If you want to call the delete.php, you can use ajax.
<script>
$.ajax({
url:'delete.php',
type:'post',
data: $('form').serialize()
});
</script>
You can get values on the delete.php, with the help of $_POST or $_REQUEST.
And if the delete.php code is right, then on submit of the edit_page.php your datatable can get affected.

Updating SQL data without refreshing page

I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!
<?php
SESSION_START();
$output = NULL;
if(isset($_POST['btn_checkTelefon'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$fornavnoutput_Database = $rows['Fornavn'];
$etternavnoutput_Database = $rows['Etternavn'];
}
echo '<script type = "text/javascript">';
echo 'function sayHi() {';
echo 'val1 = document.getElementById("telefon_Input").value;';
echo 'if(val1 == "") {';
echo ' alert("Vennligst skriv inn ditt telefon nummer!");';
echo '}';
echo 'if(val1 !== "") { ';
echo ' document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
echo ' document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
echo '}';
echo '}';
echo '</script>';
} else {
$output = "No results";
}
}
$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
</script>
<script type = "text/javascript"></script>
<title></title>
</head>
<body>
<?php
include 'connectdb.php';
?>
<form name="form1" action="">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
if(isset($_POST["radios"])){
echo $_POST["radios"];
} else {
//header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
</form>
<?php echo $output; ?>
</body>
You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.
Please never mix JavaScript with php.
Use it in separate file.
Edit: So have you fixed it yet?
The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.
I will give a proper example how to code.
Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.
$(function() {
$('a').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).attr('href');
$('body').load(URL, 'form');
})
})
php example
prefered showsomethingfunction in separate file like showfunctions.php
function myLinks() {
echo "<a href='index.php?action=showsomething'>showsomething</a>"
}
index.php + included showfunctions.php
<?php
myLinks();
if(isset($_GET["action"]){
// do your ordinary thing like open connection with database.
switch($_GET["action"]))
{
case "showsomething":
//show showsomething() function with html
break;
//further you can add more action instead of showsomething if you have several links
}
//close database.
}
?>
You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.
Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.
You have to use jQuery $.post() for that.
first You have to create php file which will process Your data.
For example lets create file query.php with the following content:
<?php
if(isset($_POST['telefon_Search'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
$row = $resultSet->fetch_assoc();
echo json_encode($row);
}
}
next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
var user = $.parseJSON(data);
$('#check_Fornavn').val(user.Fornavn);
$('#check_Etternavn').val(user.Etternavn);
});
});
and complete html will looks like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title></title>
</head>
<body>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
$('#check_Fornavn').val(data.Fornavn);
$('#check_Etternavn').val(data.Etternavn);
});
});
</script>
</body>
</html>

Radio Button Value: "on"

i have this form, when user clicks on the submit button, a script open a popup where i need to print the radio button value. My problem is the printed value on the popup window: "on" but the result should be a number (selected person's id)
My PHP Code:
<form method="post" action="edit.php" onsubmit="target_popup(this,'edit.php')"><input type="submit" value="Modifica Giocatore" /><br /><br /><br />
<?php
//my queries (work)
?>
<table cellspacing="2" cellpadding="2">
<tr>
<th></th>
<th>Name</th>
<th>Surname</th>
</tr>
<?php
$i=0;
while ($i < $num) {
$id=mysql_result($results,$i,"ID");
$name=mysql_result($results,$i,"Name");
$surname=mysql_result($results,$i,"Surname");
?>
<tr>
<td><input type="radio" name="radioEdit" value"<?= $id; ?>" /><?= $id; ?></td>
<td><?=$name?></td>
<td><?=$surname?></td>
</tr>
<?php
$i++;
}
?>
<?php
echo "</table></form>"
?>
And this is my script:
function target_popup(form,page)
{
window.open(page, 'formpopup', 'left=100,top=100,width=600,height=400,menubar,toolbar,resizable');
form.target = 'formpopup';
}
edit.php file:
<?php
$prova = $_POST['radioEdit'];
echo $prova;
?>
Thanks.
The only way I could get this to work was to use sessions.
Here is what I could test without setting up an entire DB.
PHP
<?php
session_start();
$id="12345"; // test ID number
// works with sessions
$prova = $_POST['radioEdit'] = $_SESSION['id'] = $id;
echo $prova;
?>
<form method="post" action="edit.php" onsubmit="target_popup(this,'edit.php')">
<td><input type="radio" name="radioEdit" value"<?php echo $id; ?>" /><?= $id; ?></td>
<input type="submit" value="Modifica Giocatore" />
</form>
<script>
function target_popup(form,page)
{
window.open(page, 'formpopup', 'left=100,top=100,width=600,height=400,menubar,toolbar,resizable');
form.target = 'formpopup';
}
</script>
edit.php
<?php
session_start();
echo $_SESSION['id'];
echo $id;
echo "<br>";
var_dump($_SESSION['id']);
?>
What happens when you echo $id? Are you sure that it returns a value? Also isn't <?= ;?> considered really old and deprecated PHP? You should be using <?php echo ;?>

Categories