PHP-Javascript interaction - javascript

So I've been attempting to get this page to work correctly for the past few days. As far as the database manipulation and what not it works like a charm. The problem is that it apparently isn't hitting my javascript function to redirect back onto itself. It will instead show a mostly blank page with no $_GET variables in the url which leads me to believe the problem is actually in my php function rather than my javascript function.
function edit_player()
{
try{
if( isset( $_GET['player_id'] ) )
{
if( isset( $_GET['success'] ) && $_GET['success'] )
{
echo "<div class='success'> You have successfully edited this players info.</div>" ;
}
$playerid = $_GET['player_id'] ;
$db = honneyconnect( ) ; // db connection established
if( mysqli_connect_error() )
{
throw new Exception( "Could not connect to the database") ;
}
$query = 'select * from roster where player_number ="'.$playerid.'"' ;
$player = $db->query( $query ) ;
if( !$player )
{
throw new Exception ( "Query returned zero results" ) ;
}
else
{
$row = $player->fetch_row() ;
echo '
<div class="data_entry">
<form id="player_info" method="post" action="editplayer.php" enctype="multipart/form-data" />
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<input type="hidden" name="player_number" value="'.$row[0].'" />
<table>
<tr><td>Player Number:</td><td>'.$row[0].'</td></tr>
<tr><td>Player Name:</td><td><input type="text" size="50" name="name" value="'.$row[1].'"/></td></tr>
<tr><td>Player Position:</td><td><input type="text" size="20" name="position" value="'.$row[2].'" /></td></tr>
<tr><td>Years Skating:</td><td><input type="text" size="3" name="years" value="'.$row[3].'"/></td></tr>
<tr><td>How You Chose Your Derby Name:</td><td><input type="text" size="100" name="choice" value="'.$row[4].'" /></td></tr>
<tr><td>Life Outside of Derby:</td><td><input type="text" size="100" name="life" value="'.$row[5].'" /></td></tr>
<tr><td>Current Photo: </td><td><img class="thumbnail" src="rosterpics/'.$row[6].'"></td></tr>
<tr><td>Choose a different photo:</td><td><input type="file" name="photo" id="photo" /></td></tr>
<tr><td>Sponsor:</td><td><input type="text" size="50" name="sponsors" value="'.$row[7].'"/></td></tr>
</table>
<input type="submit" value="Submit Data" />
</form></div>' ;
}
}
else
{
if( isset($_POST['player_number']) && isset($_POST['name']) && isset($_POST['position'])
&& isset($_POST['years']) && isset($_POST['choice']) && isset($_POST['life']) )
{
if( !file_exists( $_FILES['photo']['tmp_name'] ) || !is_uploaded_file($_FILES['photo']['tmp_name'] ) )
{
$db = honneyconnect( ) ; // db connection established
if( mysqli_connect_error() )
{
throw new Exception( "Could not connect to the database") ;
}
$query = 'update roster set player_name = "'.$_POST['name'].'" ,
player_position = "'.$_POST['position'].'", player_years = "'.$_POST['years'].'" , player_choice = "'.$_POST['choice'].'",
player_life = "'.$_POST['life'].'" where player_number = "'.$_POST['player_number'].'"' ;
$player = $db->query( $query ) ;
if( !$player )
{
throw new Exception( "Query failed" ) ;
}
else
{
if( isset($_POST['sponsors']) )
{
$query = 'update roster set player_sponsor = "'.$_POST['sponsors'].'" where player_number = "'.$_POST['player_number'].'"';
$sponsor = $db->query( $query ) ;
if( !$sponsor )
{
throw new Exception( "Failed to update sponsor." ) ;
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." ) ;</script>" ;
}
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." ) ;</script>" ;
}
}
}
else
{
if( $_FILES['photo']['size'] > 50000000 )
{
throw new Exception( "File is to large for this server." );
}
if( !move_uploaded_file($_FILES["photo"]["tmp_name"], "C:/wamp/www/HoneysProject/rosterpics/" . $_FILES["photo"]["name"]) )
{
throw new Exception( "There was a problem uploading the file" ) ;
}
else
{
$db = honneyconnect( ) ; // db connection established
if( mysqli_connect_error() )
{
throw new Exception( "Could not connect to the database") ;
}
$query = 'update roster set player_name = "'.$_POST['name'].'" ,
player_position = "'.$_POST['position'].'", player_years = "'.$_POST['years'].'" , player_choice = "'.$_POST['choice'].'",
player_life = "'.$_POST['life'].'", player_photo = "'.$_FILES['photo']['name'].'" where player_number = "'.$_POST['player_number'].'"' ;
$player = $db->query( $query ) ;
if( !$player )
{
throw new Exception( "Query failed" ) ;
}
else
{
if( isset($_POST['sponsors']) )
{
$query = 'update roster set player_sponsor = "'.$_POST['sponsors'].'" where player_number = "'.$_POST['player_number'].'"';
$sponsor = $db->query( $query ) ;
if( !$sponsor )
{
throw new Exception( "Failed to update sponsor." ) ;
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." );</script>" ;
}
}
else
{
$url = "http://localhost/honeysproject/editplayer.php?player_id=".$_POST['player_number']."" ;
echo "<script type='text/javascript'>success_redirect( ".$url." ) ;</script>" ;
}
}
}
}
}
}
}
catch( Exception $error )
{
echo "<div class='error'>".$error."</div>" ;
echo $_FILES['photo']['name'] ;
}
}
<html>
<head>
<style>
#import "honeysstyle.css";
</style>
<script type="text/javascript">
function success_redirect( url )
{
window.location.replace( url ) ;
}
</script>
</head>
<body>
<?php
require( 'function.php' );
draw_masthead();
edit_player() ;
?>
</body>
</html>

success_redirect( ".$url." )
should be
success_redirect( '".$url." ')
and why don't you use the header function
header("Location: $url");

Related

Uploading multipile files using HTML file input

i'm trying to upload a bunch of files using file type input with php i tried so far to make upload only one file and it worked the problem is that when i added [] to the name attribute it started to print Uploaded data error.
HTML
<form id="theform" action="upload.php" onsubmit="event.preventDefault(); return myFunction2();" method="post" enctype="multipart/form-data">
<input id="file" name="uploadedFile[]" onchange="uptoserver();" style="display:none;"type="file" multiple>
<div class="row justify-content-center">
<div id="buttons" style="display:none !important;">
<button type="submit" class="btn wbtn" style="font-family:Hana; font-size:18px; border:1px solid black !important;">
<img src="style\image\add.png" width="32" /> تكوين كشف
</button>
<button type="button" class="btn wbtn" style="font-family:Hana; font-size:18px; border:1px solid black !important;">
<img src="style\image\camera.png" width="32" /> إضافة نموذج
</button>
</div>
</div>
</form>
Javacript :
function myFunction2(){
document.getElementById('file').click();
console.log('reading form');
}
function uptoserver(){
// var formscounter = parseInt(document.getElementById("counter").value);
if(!document.getElementById("file").files.length == 0) {
const form = document.getElementById('theform');
form.submit();
console.log('fucking working');
}
}
upload.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo "Empty data, please select file";
die;
}
if (!isset($_FILES["uploadedFile"])) {
echo "Wrong data struct";
die;
}
if ($_FILES["uploadedFile"]['error'] != 0) {
echo "Uploaded data error";
die;
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]);
$allowUpload = true;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$maxfilesize = 80000000;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["uploadedFile"]["tmp_name"]);
if($check !== false) {
//
} else {
echo "This's not image file.";
$allowUpload = false;
}
}
if (file_exists($target_file)) {
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"] > $maxfilesize) {
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes )) {
require "other\\fileExtenstion.php";
$allowUpload = false;
}
if ($allowUpload) {
if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) {
// echo "File ". basename( $_FILES["uploadedFile"]["name"]). " uploaded success.";
// echo $target_file;
require "prepare.php";
echo count($_FILES["uploadedFile"]);
} else {
echo "Error when upload file.";
}
// $total = count($_FILES['uploadedFile']['name']);
// // Loop through each file
// for( $i=0 ; $i < $total ; $i++ ) {
// //Get the temp file path
// $tmpFilePath = $_FILES['uploadedFile']['tmp_name'][$i];
// //Make sure we have a file path
// if ($tmpFilePath != ""){
// //Setup our new file path
// $newFilePath = "uploads/" . $_FILES['uploadedFile']['name'][$i];
// //Upload the file into the temp dir
// if(move_uploaded_file($tmpFilePath, $newFilePath)) {
// //Handle other code here
// }
// }
// }
} else {
echo "";
}
?>
Your original structure works perfectly fine because, when you're uploading a single file, line 18 is if ($_FILES["uploadedFile"]['error'] != 0), and this returns 0.
When you send through an array of files, even if a single file is sent, the uploadFile array is now an array of arrays, as below.
[_FILES] => Array
(
[uploadedFile] => Array
(
[name] => Array
(
[0] => funnyMusclePose.jpg
)
[type] => Array
(
[0] => image/jpeg
)
[tmp_name] => Array
(
[0] => C:\Development\wamp64\tmp\phpE949.tmp
)
[error] => Array
(
[0] => 0
)
[size] => Array
(
[0] => 735092
)
)
)
This means $_FILES["uploadedFile"]['error'] will always evaluate to true because it doesn't equal 0.
From here on out, you can wrap this entire function in a for() loop and iterate over each of the internal array items to get the data you're after, ie.
for($i = 0; $i < count($_FILES["uploadedFile"]["name"]); $i++) {
if ($_FILES["uploadedFile"]['error'][$i] != 0)
{
echo "Uploaded data error";
die;
}
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["uploadedFile"]["name"][$i]);
$allowUpload = true;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$maxfilesize = 80000000;
$allowtypes = array('jpg', 'png', 'jpeg', 'gif');
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["uploadedFile"]["tmp_name"][$i]);
if($check !== false)
{
//
}
else
{
echo "This's not image file.";
$allowUpload = false;
}
}
if (file_exists($target_file))
{
require "other\\fileExsist.php";
$allowUpload = false;
}
if ($_FILES["uploadedFile"]["size"][$i] > $maxfilesize)
{
require "other\\fileSize.php";
$allowUpload = false;
}
if (!in_array($imageFileType,$allowtypes ))
{
require "other\\fileExtenstion.php";
$allowUpload = false;
}
// Add the rest of the code here
}

contact form unable to reset

I am looking to create a contact Us form in my website, where after the form is submitted, the text fields should be cleared, and a Thank You should appear.
Here is the html code :
<div class="form">
<div id="sendmessage">Your message has been sent. Thank you!</div>
<form action="contactform.php" method="post" role="form" class="contactForm">
<div class="form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Name (eg: James)" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email (eg: james#example.com)" data-rule="email" data-msg="Please enter a valid email" />
<div class="validation"></div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Phone Number (eg: 0406 624 456)" data-rule="minlen:9" data-msg="Please enter a valid contact number" />
<div class="validation"></div>
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required" data-msg="Please write something for us" placeholder="Message"></textarea>
<div class="validation"></div>
</div>
<br/>
<div class="text-center">
<button type="submit" name="submit" value="Submit"></button>
<!--b>Send Message</b-->
</div>
</form>
The relevant java script code:
jQuery(document).ready(function($) {
"use strict";
//Contact
$('form.contactForm').submit(function(){
var f = $(this).find('.form-group'),
ferror = false,
emailExp = /^[^\s()<>#,;:\/]+#\w[\w\.-]+\.[a-z]{2,}$/i;
f.children('input').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
case 'email':
if( !emailExp.test(i.val()) ){ ferror=ierror=true; }
break;
case 'checked':
if( !i.attr('checked') ){ ferror=ierror=true; }
break;
case 'regexp':
exp = new RegExp(exp);
if( !exp.test(i.val()) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') !== undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
f.children('textarea').each(function(){ // run all inputs
var i = $(this); // current input
var rule = i.attr('data-rule');
if( rule !== undefined ){
var ierror=false; // error flag for current input
var pos = rule.indexOf( ':', 0 );
if( pos >= 0 ){
var exp = rule.substr( pos+1, rule.length );
rule = rule.substr(0, pos);
}else{
rule = rule.substr( pos+1, rule.length );
}
switch( rule ){
case 'required':
if( i.val()==='' ){ ferror=ierror=true; }
break;
case 'minlen':
if( i.val().length<parseInt(exp) ){ ferror=ierror=true; }
break;
}
i.next('.validation').html( ( ierror ? (i.attr('data-msg') != undefined ? i.attr('data-msg') : 'wrong Input') : '' ) ).show('blind');
}
});
if( ferror ) return false;
else var str = $(this).serialize();
$.ajax({
// alert("enterd the loop")
type: "POST",
url: "contactform/contactform.php",
data: str,
success: function(msg){
//alert(msg);
if(msg == "New record created successfully") {
$("#sendmessage").addClass("show");
$("#errormessage").removeClass("show");
$('.contactForm').find("input, textarea").val("");
document.getElementsByClassName("contactForm").reset();
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
return false;
});
});
Relevant php script to obtain db credentials and properties:
<?php include "../../inc/dbinfo.inc"; ?>
<?php
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$Phone = test_input($_POST["Phone"]);
$message = test_input($_POST["message"]);
$submit = test_input($_POST["Submit"])
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$sql = "INSERT INTO contact_details (name, email, Phone, message)
VALUES ('$name', '$email', '$Phone', '$message')";
// <script>alert("your message is sent successfully");
// window.location="index.html";
// </script>
if ($connection->query($sql) === TRUE) {
echo "New record created successfully";
mysqli_free_result($result);
mysqli_close($connection);
} else {
echo "Error: " . $sql . "<br>" . $connection->error;
mysqli_free_result($result);
mysqli_close($connection);
}
?>
after submitting the form, the form doesn't reset and displays any message but its getting updated in the database.
Redirect to new page or same page like below:
if ($connection->query($sql) === TRUE) {
mysqli_free_result($result);
mysqli_close($connection);
header('Location: filename?msg=success');
}

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

$.post JQuery not working

I have a problem with form. After i click Dodaj button nothing happens.
I've putted alert dialog to see when it stops and it stops after
$.post('dodaj_ztoner.php', post_data, function(response){
I have made similar forms with similar code (names and number of items was different) and it worked
alert('post'); is not displaying. so looks like problem is here $.post('dodaj_ztoner.php', post_data, function(response){
html code:
<body>
<div id="dialog" title="Błąd Wprowadzania!">
<p>Proszę uzupełnić podświetlone pola.</p>
</div>
<div class="container">
<fieldset id="contact_form">
<h2>Zużycie Tonera</h2>
<div id="zresult"></div>
<label for="id"><span>ID</span></label>
<input type="text" name="zid" id="zid" value="<?php
$zapytanie = "select max(id) as id from zuzycie_toner";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo $wynik['id']+1;
}
mysql_free_result($widok);
?>" disabled />
<label for="zdata"><span>Data wydania</span></label>
<input type="text" name="zdata" id="zdata" />
<label for="ilwyd"><span>Ilość wydrukowanych</span> </label>
<input type="text" name="ilwyd" id="ilwyd" />
<label for="drukarka"><span>Drukarka</span></label>
<select type="text" name="zdrukarka" id="zdrukarka" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from drukarki order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="toner"><span>Toner</span></label>
<select type="text" name="ztonery" id="ztonery" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from tonery order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="user"><span>Użytkownik</span> </label>
<select type="text" name="zuser" id="zuser" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwisko_imie as id from uzytkownicy order by nazwisko_imie";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[id]</option>";
}
mysql_free_result($widok);
?>
</select>
<label><span> </span>
<button type="submit" class=submit_btn" id="zsubmit_btn">Dodaj</button>
</label>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var divObj = $('#dialog');
divObj.dialog({
autoOpen: false
}
);
$( "#zdrukarka" ).selectmenu();
$( "#zuser" ).selectmenu();
$( "#ztonery" ).selectmenu();
$("#zdata").datepicker();
$( "button[type=submit]" )
.button()
$("#zsubmit_btn").click(function() {
//Pobieramy dane
var ztoner_id = $('input[name=zid]').val();
var ztoner_data = $('input[name=zdata]').val();
var ztoner_wydr = $('input[name=ilwyd]').val();
var ztoner_toner = $('select[name=ztonery]').val();
var ztoner_user = $('select[name=zuser]').val();
var ztoner_drukarka = $('select[name=zdrukarka]').val();
//Prosta walidacja (kolorujemy na czerwono pole jeśli jest puste
var proceed = true;
alert( '1');
//wszystko w porządku idziemy dalej
if(proceed)
{
//Dane do wysłania
post_data = {'ztonerID':ztoner_id, 'ztonerWydr':ztoner_wydr, 'ztonerData' :ztoner_data, 'ztonerToner' :ztoner_toner,
'ztonerUser':ztoner_user, 'ztonerDrukarka':ztoner_drukarka};
//Przesłanie danych poprzez AJAX
$.post('dodaj_ztoner.php', post_data, function(response){
alert( 'post');
//wczytanie danych zwrotnych JSON
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#zresult").hide().html(output).slideDown();
}, 'json');
} else divObj.dialog("open");
});
//resetujemy kolorowanie po zaczęciu pisania
});
</script>
PHP file:
<?php
include './includes/html_elements.php';
//pokaz_zmienna($_SERVER);
$db_link = connect_db();
if(!$db_link)
{
$out='<p>Brak połączenia z bazą danych</p>';
print_page($out, 'Baza książek');
exit;
}
if($_POST)
{
//Sprawdzamy czy jest to rządanie Ajax, jeśli nie..
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//Kończymy skrypt wysyłając dane JSON
$output = json_encode(
array(
'type'=>'error',
'text' => 'Rządanie musi przejść przez AJAX'
));
die($output);
}
//Sprawdzamy czy wszystkie pola zostały wysłane. kończymy skrypt jeśli nie (tutaj dodawaj więcej pól, które są wymagane)
if(!isset($_POST["ztonerID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'POLA SĄ PUSTE!'));
die($output);
}
//Pobieramy dane z formularza
$ztoner_id = filter_var($_POST["ztonerID"], FILTER_SANITIZE_STRING);
$ztoner_data = filter_var($_POST["ztonerData"], FILTER_SANITIZE_STRING);
$ztoner_wydr = filter_var($_POST["ztonerWydr"], FILTER_SANITIZE_STRING);
$ztoner_drukarka = filter_var($_POST["ztonerDrukarka"], FILTER_SANITIZE_STRING);
$ztoner_toner = filter_var($_POST["ztonerToner"], FILTER_SANITIZE_STRING);
$ztoner_user = filter_var($_POST["ztonerUser"], FILTER_SANITIZE_STRING);
//Dodatkowa validacja PHP (tylko dla pól wymaganych)
if(!is_numeric($ztoner_id)) //sprawdzamy czy telefon jest numeryczny
{
$output = json_encode(array('type'=>'error', 'text' => 'Tylko liczby są dozwolone'));
die($output);
}
die($output);
}
$zapytanie = "select idd from drukarki where nazwa = '$ztoner_drukarka'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_drukarka = $wynik['idd'];
}
mysql_free_result($widok);
$zapytanie = "select idu from uzytkownicy where nazwisko_imie = '$ztoner_user'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_user = $wynik['idu'];
}
mysql_free_result($widok);
$zapytanie = "select idt from tonery where nazwa = '$ztoner_toner'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_toner = $wynik['idt'];
}
mysql_free_result($widok);
$insert = "Insert INTO zuzycie_toner Values ($ztoner_id, '$ztoner_data', $ztoner_wydr, $ztoner_drukarka, $ztoner_toner, '$ztoner_user')";
$wykonaj = mysql_query($insert);
if ($wykonaj)
{
$output = json_encode(array('type'=>'message', 'text' => 'Dodano '.$drukarki_nazwa.' do tabeli'));
die($output);
}else{
$output = json_encode(array('type'=>'error', 'text' => 'Dodawanie nie powiodło się '.$insert));
die($output);
}
}
?>
Your page doesn't conatains any form tag, so simple use
<button class=submit_btn" id="zsubmit_btn">Dodaj</button> instead of input type = submit
This will Work!!!!

AJAX more button in PHP to fetch more records

How can I make the load more button working to make the LIMIT 0,5 to convert to LIMIT 0,10 and on third click it converts to LIMIT 0,15 and maximum up to LIMIT 0,30
I am using the following PHP, MySQL to fetch records from the database
$select_resdetails = mysql_query("SELECT *, ((ACOS( SIN( -27.486204 * PI( ) /180 ) * SIN( `store-latitude` * PI( ) /180 ) + COS( -27.486204 * PI( ) /180 ) * COS( `store-latitude` * PI( ) /180 ) * COS( (152.994962 - `store-longitude`) * PI( ) /180 ) ) *180 / PI( )) *60 * 1.1515) AS `distance` FROM ( SELECT max(if(`field_name`='store-name', `field_value`, null )) AS `store-name`,
max(if(`field_name`='store-description', `field_value`, null )) AS `store-description`, max(if(`field_name`='store-longitude', `field_value`, null )) AS `store-longitude`, max(if(`field_name`='store-latitude', `field_value`, null )) AS `store-latitude` FROM `wp_cf7dbplugin_submits` WHERE `form_name` = 'Add Store' GROUP BY `submit_time`) A ORDER BY `distance` LIMIT 0,5");
?>
<form class="ui-filterable">
<input id="myFilter" data-type="search">
</form>
<ul data-inset="true" data-role="listview" data-filter="true" data-input="#myFilter" style="padding:0px;">
<?php
while($fetch_resdetails = mysql_fetch_array($select_resdetails)) {
echo '<li>
<h2>' . $fetch_resdetails['store-name'] . '</h2>
<p>' . number_format(($fetch_resdetails['distance']), 2, '.', '') . ' KM <em>' . $fetch_resdetails['store-description'] . '</em></p>
</a>
</li>
';
}
?>
<input type="button" value="Load More" />
</ul>
save the click amount in local storage
if(limit <= 30){
limit = limit + 5;
localStorage.setItem("limit", limit);
}
dont forget initial variable and make default value 5
And send this variable by ajax
USE THE GET METHOD
and send the parameter
$.get( "example.php?limit="+localStorage.getItem("limit"),
function() {
alert( "success" );
})
IN your php file use $_GET['limit'] to read limit variable
I am using Yii framework for solving this problem.
in views file:
<div id="own_video_list">
View more
</div>
here $videos_limit is first limit(say 5).
in js:
$('#own_video_list .load').live('click', function() {
var lastaction = $(this).attr("id");
var type = 'own_video_list';
loadMoreVideos(type, lastaction);
return false;
});
function loadMoreVideos(type, lastaction)
{
if(lastaction)
{
$("#"+type+" a#"+lastaction).html('<img src = "/images/loading.gif" alt = "loading"> Loading...');
$.ajax({
type: "POST",
url: "/videos/home/loadmorevideoshome",
data: "type="+ type + "&lastId=" +lastaction,
success: function(html){
$("#"+type+" a.load").parent().parent().remove();
$("#"+type).append(html);
$('body').animate({scrolltop: $('body')[0].scrollHeight});
}
});
}
else
{
$("#"+type+" .load").html("no more video");
}
}
in controller:
public function actionLoadmorevideoshome()
{
$type = $_REQUEST['type'];
$lastId = $_REQUEST['lastId'];
$userId = Yii::App()->user->getId();
$videoHtml = '';
$videos = VideoList::getMostRecentVideos(self::RECORD_PER_PAGE, $userId , $lastId, 1);
if( is_array($videos) && (count($videos) > 0) )
{
$videoHtml .= $this->renderPartial('_view', array(
'videoList' => $videos, 'type' => $type, )
, true, false);
$lastId = $lastId + count($videos);
$videoHtml .= '<div class="video_col_01">
<div style="margin-left: 20px;" class="search_btn">
View more
</div>
</div>';
}
else
{
$videoHtml .= '<div class="video_col_01"><font color="red">No More Video</font></div>';
}
echo $videoHtml;
Yii::app()->end();
}

Categories