displaying records from a php file via jquery; - php

Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.

First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.

Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});

you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()

Related

Handling PHP POST variable from other php file and managing $_SERVER["PHP_SELF"]

I stucked at a problem I can't figure out why isn't is working.
I am handling POST variable from another php file:
$temp_variable = $_POST['activity'];
After my code process $temp_variable, I try to make a button (still in the same php file where I handled $_POST['activity'])
echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">';
echo '<input type="submit" value="OK" name="process_more"/>';
echo '</form>';
Then I try to catch OK button press, to start another activity:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$query = "DELETE FROM table1 WHERE id = 5";
mysqli_query($conn,$query)
}
My problem is that the "Delete FROM" part of the code executes immediately, before the user press the "OK" button.
What can be the problem ?
Check something more specific to your form.
if(isset($_POST['process_more'])){
if ($_POST['process_more'] == 'OK') {
// execute the delete
}
}
$_SERVER["REQUEST_METHOD"] could equal 'POST' from a different form submission..

How to submit form without moving to next page in PHP

The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!
Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)
action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that
You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.
Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.

PHP page not sending data to .csv

I have created a PHP page (see code below) that is supposed to validate the information entered into the webform prior to submitting it, to ensure that all fields have been completed. If any fields have been left blank, it is supposed to display an error message; if all fields have been filled in, it is supposed to send the data to a .csv file. The problem is that it is not validating the fields, nor is it sending the data to the .csv. I have tried deleting the .csv and then submitting the webform; it creates a .csv with commas separating the entries, but there are no entries (i.e. no text, only commas).
Does anybody know why this might be?
Any assistance would be appreciated.
Thanks in advance!
Here is the code:
<form action="form_mailer.php" method="post">
<table>
<tr><td>Which is your name?</td>
<td><input type="text" name="formName" maxlength="50" value="<?=$varName;?>"></td></tr>
<tr><td>What is your occupation?</td>
<td><input type="text" name="formOccupation" maxlength="50" value="<?=$varOccupation;?>"></td></tr>
</table>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formName']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
if(empty($_POST['formOccupation']))
{
$errorMessage .= "<li>You forgot to enter your occupation!</li>";
}
$varName = $_POST['formName'];
$varOccupation = $_POST['formOccupation'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
<?php
if($errorMessage != "")
{
echo("<p>There was an error:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
else
{
$fs = fopen("data.csv","a");
fwrite($fs,$varName . ", " . $varOccupation . "\n");
fclose($fs);
}
?>
UPDATE:
Hi,
Many thanks for the responses.
I've realised where I have gone wrong now........I had the form action as 'form_mailer.php', which is not the form page itself but another page that performs further actions with the data provided on the webform.
I have now brought the 'form_mailer' coding into the webform .php and have changed the 'action' of the webform page so that it effectively submits to itself, but now I need to redirect to the form_mailer page following successful submission of the webform or display a thank you message........don't suppose anybody knows how I can do this? If you could provide instructions for how to do both that would be great as I can then choose the one I prefer that would be best for my needs.
Thanks again!
I have checked your code and it's working fine and also store data in csv file.
Probably you should make these vars global:
<?php
global $varName, $varOccupation
...
... probably in both <?php blocks.

AJAX fade on submit

I have a quick question about this fade out div. I use facebox, and after the submit, and it shows an error it'll show this:
http://puu.sh/1uPnF
however I want that to fade away, after they've caught that message. On my AJAX handler for the submit form, this is the PHP code:
<?php
require_once('....');
$form_name = $_GET['form_name'];
$form_comment = $_GET['form_comment'];
$date = date('Y-n-j');
$ip = $_SERVER['REMOTE_ADDR'];
if($form_name == '') {
echo("<div class='alert alert-error-x'>Don't forget to enter a name, as we need to identify who's commenting on this article!</div>");
} else if($form_comment == '') {
echo("<div class='alert alert-error-x'>Please do not leave the comment field blank, we want to know what you're saying!</div>");
} else {
mysql_query("INSERT INTO comment (id, articleid, name, comment, date, ip) VALUES (NULL,'{$_GET['id']}','{$form_name}','{$form_comment}','{$date}','{$ip}')");
// output comment
echo "<div class='alert alert-success-x'>Posted by <strong>$form_name</strong> on <strong>{$date}</strong>$form_comment</div>";
}
?>
This is where the output of what would be submitted, on the article.php:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); $comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
<div id="new_comment"></div>
<div class="article-comment">
Posted by <b><?php echo $row['name'] ?></b> on <b><?php echo $row['date'] ?></b>
<br />
<?php echo $row['comment'] ?>
</div>
<?php } ?>
</div>
</body>
</html>
Now I tried adding the below code in the core.js file, which is located on my site at krissales.com
$(window).bind("load", function() {
$('#new_comment').fadeOut(4000);
});
However it did not work. If you want to test the demo, then check it out at: http://www.krissales.com/#/media/30.This-is-a-new-article-for-Testing!
What is it that I'm doing wrong, please?
Thanks!
If you're using AJAX, I suggest you use jquery's ajax method (http://api.jquery.com/jQuery.ajax/) to make the call to your PHP file.
Then, use the success callback function of that method to show the correct response.
Hiding the response can then simply be done by fading out the div (with a delay if you want that).
if ($('#new_comment').length > 0)
{
$('#new_comment').delay(4000).fadeOut();
}
You are now trying to fade out the message on window load, but since you're using AJAX, there is no page reload happening.
Hope this helps you!

Converting PHP/MySQL Request into jQuery AJAX Request

I am kicking myself in the arse here because i can't for the life of me figure it out...this is supposed to be a quick and dirty project, but, I decided i want to try something new, and I have little to no experience with the AJAX methods in jQuery...I spent quite literally 5 days trying to learn and understand how to appropriately implement the AJAX calls, but to know avail...I learned some basic stuff, but not what i need to execute the code below.
Again, I am wondering how to go about converting this standard request to AJAX using jQuery...
here is my form & php
HTML:
<form action="categories.php?action=newCategory" method="post">
<input name="category" type="text" />
<input name="submit" type="submit" value="Add Categories"/>
</form>
PHP:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['category'])) {
if ($_GET['action'] == 'newCategory') {
$categories = $_POST['category'];
$query = "SELECT * FROM categories WHERE category ='$categories' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)) {
echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>';
} else {
// Simply cleans any spaces
$clean = str_replace(' ', '', $categories);
// Makes it possible to add multiple categories delimited by a comma
$array = explode(",", $clean);
foreach ($array as &$newCategory) {
mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')");
}
echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>";
}
}
} else {
echo "<script>alert('Please Enter at Least One Category.')</script>";
}
}
?>
here's the proper syntax for making the call in the background and not submitting the form, but still sending/retrieving results.
$(function(){
$('form').submit(function(e){
e.preventDefault(); // stop default form submission
$.ajax({
url: 'categories.php',
data: 'action=newCategory',
success: function(data){
//here we have the results returned from the PHP file as 'data'
//you can update your form, append the object, do whatever you want with it
//example:
alert(data);
}
});
});
});
Also:
I would not do this ->
echo "<script>alert('Please Enter at Least One Category.')</script>";
Just do echo 'Please Enter at Least One Category.';
If you need to create an error system, you can do things like,
echo "Error 1001: <!> Please enter at least One Category!';
Then in your Ajax callback for 'success', we can split the returned object in <!>. Example to follow:
success: function(data){
if($(data+':contains("<!>")'){
var errMsg = $(data).split('<!>');
alert(errMsg[0]+' : '+errMsg[1]);
//above would output - Error 1001 : Please enter at least One Category!;
}
}

Categories