ajax form not finding javascript function - javascript

I can't seem to figure out what I'm doing wrong with this no matter how many things I try. I've looked through Google for a related issue but found nothing specific. Hopefully someone can help me.
The script runs through a external .js file calling a list of music albums, then listing the song of the album chosen via ajax. The user can then edit of delete the songs. Everything works fine until I submit the edited information through a form. When I click the submit button I get a web developer error "updateSong is not a function"
Here's the form:
<?php
include("database.php");
$song = $_GET['song'];
$query = "SELECT * FROM song INNER JOIN genre ON song.gID = genre.gID INNER JOIN album ON song.alID = album.alID WHERE sID = '$song'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("
<form action='#' method='POST' name='updateSong' onSubmit='updateSong(\"$song\")'>
<input name='songName' type='text' value='$row[songName]' />
<input type='text' id='genreSearch' name='genre' alt='Genre Search' onkeyup='searchSuggest();' autocomplete='off' value='$row[genreName]'/>
<div id='genre_search_suggest'></div>
<input name='songURL' type='text' value='$row[songUrl]' />
<input name='sID' type='hidden' value='$row[sID]' />
<input name='Submit' type='Submit' value='Update Song' />
</form>
");
}
?>
Here's the javascript:
function updateSong(sID) {
if(ajax) {
var song = sID;
alert("2");
ajax.open('get', './song_update.php' + encodeURIComponent(sID));
alert("3");
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
//EDIT//
Here's the page it's loaded into. I removed the unnecessary stuff around what this question is dealing with.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="artistPageStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascripts/artistAjax.js"></script>
</head>
<body>
<div id="mediaPlayerBox">
<div id="artistAlbumList">
<?php
$query = "SELECT * FROM `album` INNER JOIN artist ON album.aID = artist.aID WHERE artist.LoginKey = '$token'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("<div id='artistAlbumBox'><div id='artistAlbum'><a href='#' onclick='loadAlbum($row[alID])'><img src='$row[albumCover]' width='75px' height='75px' border='0px' ></a></div><div id='artistAlbumLabel'>$row[albumName]</div></div>");
}
?>
</div>
</div>
</body>
</html>

Shouldn't it be: onSubmit='updateSong("$song")'?

try doing onSubmit='return updateSong($song)'

It's saying it is not a function because it isn't loaded, are you loading the external script in the display page at all?

Related

How to connect HTML page to MySQL Workbench Server using JavaScript,Ajax and PHP?

I have an HTML page where we enter the name of a movie and if that movie is present in the database,then the name is displayed. I am trying to connect to the database using JavaScript, Ajax and PHP. The database is in the MySQL Workbench Server.
This is what I have done:
pc.html
<html>
<head>
<script type="text/javascript">
function Search_Data()
{
var httpr = new XMLHttpRequest();
var movie_name=document.getElementById("moviename").value;
console.log(movie_name);
httpr.open("GET","get_data.php",true);
httpr.send();
httpr.onreadystatechange = function()
{
if(this.readyState==4 && this.status==200)
{
alert(this.responseText);
}
}
}
</script>
<body>
<input type="text" name="moviename" id="moviename" placeholder="Enter a movie...">
<br/>
<input type="button" name="search" value="Search" onclick="Search_Data()">
<br/>
<span id="response"></span>
</body>
</head>
</html>
get_data.php
(Below code is a trial code to see if its working)
<?php
echo "Hello World"
?>
In the browser,the result I am getting is:
The files are in the following location:
C:\Users\Admin\AppData\Roaming\MySQL\Workbench\scripts
The entire code is getting displayed instead of just "Hello World".I am new to web development and PHP and I am not sure what seems to be the problem.
what are you using is ajax with normal java-script i suggest to use jquery ajax and this is a full example how to connect it to php and how to get the value or list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
<td width="90%"><span id="employee_name"></span></td>
second
<input type="input" id="inputs" value="submit">
<p id="email"></p>
<p id="pass"></p>
<p id="permission"></p>
<script>
$(document).ready(function(){
$('#search').click(function(){
var val = document.getElementById("inputs").value;
var id= $('#employee_list').val();
setInterval(function(){
$.ajax({
url:"db.php",
method:"POST",
data: {val : val},
dataType:"JSON",
success:function(data)
{
$('#email').text(data[val].email);
$('#pass').text(data[val].pass);
$('#permission').text(data[val].perm);
}
})
}, 1000);
});
});
</script>
</body>
</html>
the php file
<?php
$items = array();
$url="localhost";
$user= "root";
$pass="";
$dbname="test";
$value= 0;
if(isset( $_POST['val'])){
$value= $_POST['val'];
}
$num=0;
$connect=mysqli_connect($url,$user,$pass,$dbname);
$result="SELECT email,pass,permission FROM test where id=$value";
$sql=mysqli_query($connect,$result);
while($row=mysqli_fetch_assoc($sql) ){
/* add a new item */
$num++;
$items[$value] = array(
'email' => $row['email'],
'pass' => $row['pass'],
'perm' => $row['permission']
);
}
$json_response = json_encode($items);
echo $json_response;
?>

Logic behind back button

I am workng on a project in which I have to put back button functionality. Unfortunatly I can't seem to work it out. I have created a back button and it works. But if the user wants to edit the previous form and then submit data again, so it edits the query. I have tried it in my project but it adds another record in the database and doesn't update the previous one. I know I am not using any update query here. Now I am stuck how would it works I can't think of a good logic. I have made a simple form for example. It is written below.
<?php
$con = mysqli_connect('localhost','root','','test1');
if (isset($_POST['sub'])) {
$first_name = $_POST['fname'];
$second_name = $_POST['lname'];
$sql = "INSERT INTO `tbl`(`first_name`, `last_name`) VALUES
('$first_name', '$second_name')";
$run = mysqli_query($con, $sql);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="POST" action="nextpage.php">
First_name: <input type="text" name="fname">
Second_name: <input type="text" name="lname">
<input type="submit" name="sub" value="submit">
</form>
</body>
</html>
nextpage.php
<?php
$con = mysqli_connect('localhost','root','','test1');
?>
<html>
<body>
<h1>Next Page</h1>
<p>The query is submitted press ok to forward and back if you want to go back</p>
<button>OK</button>
<button onclick="history.go(-1);">Back</button>
</body>
</html>
Thanks for your expert advice in advance.
If I understand correctly.. ..you have a lot of work to do to be able to to 'UPDATE' a record that you have just created.
Dont bother trying to go 'back' to the original form, go forwards to a new 'edit' form, passing the ID from the record that you have just created.
Use the ID to SELECT that record from the DB and pre-populate the 'edit' form. Add a hidden ID field to the form. Then on submission of the 'edit' form, UPDATE the existing record, using the ID.
I think you are taking the "back" button too literally. you are emulating the browser's back button. Instead, update your link text to "edit the submitted record", and either modify the submit page with the capability of editing it, (eg. a hidden input field with the index value of the last created item), or redirect to a page dedicated to editing the submitted record. the user will see it as going back, but the functionality will be different.
submitform:
<?php
$edit = false;
if(isset($_GET['editid']){
$edit = true;
//get the record, and display it in the fields below
}
$con = mysqli_connect('localhost','root','','test1');
if (isset($_POST['sub'])) {
$first_name = $_POST['fname'];
$second_name = $_POST['lname'];
$sql = "INSERT INTO `tbl`(`first_name`, `last_name`) VALUES
('$first_name', '$second_name')";
$run = mysqli_query($con, $sql);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="POST" action="nextpage.php">
First_name: <input type="text" name="fname" <?=($edit)?"value=\"".$req["fname"]."\":""?>>
Second_name: <input type="text" name="lname">
<input type="submit" name="sub" value="submit">
</form>
</body>
</html>
nextpage.php
<?php
$con = mysqli_connect('localhost','root','','test1');
?>
<html>
<body>
<h1>Next Page</h1>
<p>The query is submitted press ok to forward and back if you want to go back</p>
<button>OK</button>
<button onclick="submitform.php?editid=<?=mysqli_last_return_id()?>">Back</button>
</body>
</html>
Here's the answer to my own question..Hope it would help someone..
test.php
<?php
session_start();
$con=mysqli_connect('localhost','root','','test1');
if(isset($_POST['sub'])){
$first_name=$_POST['fname'];
$second_name=$_POST['lname'];
$sess_username=$_SESSION['user_name'];
$sql="INSERT INTO `tbl`(`first_name`, `last_name`,`sess_username`)
VALUES ('$first_name','$second_name','$sess_username')";
$run=mysqli_query($con, $sql);
header("location:nextpage.php");
}
if(isset($_POST['upd'])){
$first_name=$_POST['fname'];
$second_name=$_POST['lname'];
$id=#$_GET['id'];
$upd="UPDATE `tbl` SET
`first_name`='$first_name',`last_name`='$second_name' WHERE `id`='$id'";
$query=mysqli_query($con, $upd);
header("location:nextpage.php");
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
if(window.location.href.indexOf("id") > -1) {
$('.submit').hide();
$('.update').show();
}
});
</script>
<title>Untitled Document</title>
</head>
<body>
<form method="POST" action="">
First_name:<input type="text" name="fname">
Second_name:<input type="text" name="lname">
<input class="update" type="submit" value="Update" name="upd"
style="display:none;">
<input class="submit" type="submit" name="sub" value="submit">
</form>
</body>
</html>
nextpage.php
<?php
session_start();
$con=mysqli_connect('localhost','root','','test1');
$sql="SELECT * FROM `tbl` WHERE
`sess_username`='".$_SESSION['user_name']."'";
$run=mysqli_query($con, $sql);
while($res=mysqli_fetch_assoc($run)){
$id=$res['id'];
$firstname=$res['first_name'];
$lastname=$res['last_name'];
$sess=$res['sess_username'];
}
?>
<html>
<body>
<h1>Next Page</h1>
<p>The query is submitted press ok to forward and back if you want to go
back</p>
<button >OK</button>
<form method="POST" action="test.php">
<?php echo "<a href='test.php?id=$id;'>Back</a>"; ?>
</form>
</body>
</html>

Auto suggestion search result error in PHP

I am trying to implement search with auto suggestion in my script but unfortunately I am unable to understand why it is not giving values. I have created two files. One is HTML which has JavaScript functions and some HTML in to and the other one is PHP. Can you please help me to find out what problem is with the code which is not able to display records in the text box?
File: index.html
<!DOCTYPE html>
<script src="jquery-1.11.2.min.js"></script>
<script type="text/JavaScript">
function lookup(inputString){
if (inputString.length==0){
$('#suggestions').hide();
} else{
$.post("suggestions.php",{
queryString: "" + inputString + ""},
function(data){
$('#suggestions').html(data).show();
});
}
}
</script>
<html>
<form>
<input type="text" size="30" onkeyup="lookup(this.value);">
<div id="suggestions"></div>
</form>
<head lang="en">
<meta charset="UTF-8">
<title>Sandbox Page</title>
</head>
<body>
</body>
</html>
File: suggestions.php
<p id="searchresults"><?php
$db=new mysqli('localhost','root','','RateList');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM RateList.VoipRoutes" . $queryString);
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="'.$result->name.'">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>
Your SQL query is malformed. If I type "kittens" into the text box, the SQL query will be:
SELECT * FROM RateList.VoipRouteskittens

This auto submit form doesn't work (sometimes!)

This is strange. This code works well when I open it directly --but if I run the web page that precedes it it doesn't. This code is a confirmation page that I want to jump in a checkout process -I have all my fields, and I don't need to ask the user again for confirmation, so I send her to checkout directly, sending all the values of the fields.
Again, when I arrive to this page from another form post it doesn't work --despite no other field or object sent to this page is called like the form--. Any ideas?
<?php include 'security.php' ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Secure Acceptance - Payment Form</title>
<link rel="stylesheet" type="text/css" href="payment.css"/>
</head>
<body>
<?php
foreach($_REQUEST as $name => $value) {
$params[$name] = $value;
}
?>
<p>Redirecting to Secure Server...</p>
<form action="https://testsecureacceptance.cybersource.com/pay" method="post" id="formulario" name="formulario" />
<?php
foreach($params as $name => $value) {
echo "<input type=\"hidden\" id=\"" . $name . "\" name=\"" . $name . "\" value=\"" . $value . "\"/>\n";
}
echo "<input type=\"hidden\" id=\"signature\" name=\"signature\" value=\"" . sign($params) . "\"/>\n";
?>
<input type="submit" id="boton" name="boton" value="Ir a Checkout >>"/>
</form>
<script type = "text/javascript">
document.getElementById('formulario').submit();
</script>
</body>
</html>
You can use the JavaScript setTimeout method to delay the submit function while page loads or you can also use jQuery to wait until documents load and after that you can fire form submit function:
JS:
setTimeout(function(){
document.getElementById('formulario').submit();
},1000);
jQuery:
$(document).ready(function(){
$('#formulario').submit();
})

PHP - Hide Code hide div

Hey stackoverflow comunity i need to make this script hidden or show when if i clik on some Words like Upload or a button this script disiper or show i want to make this script hidden first when the user clik on Upload or a button this script will show.
This is the script
<?php require_once("maxUpload.class.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload File</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
$myUpload = new maxUpload();
//$myUpload->setUploadLocation(getcwd().DIRECTORY_SEPARATOR);
$myUpload->uploadFile();
?>
</body>
maxUpload.class.php:
<?php
/*************************************************
* Max's File Uploader
*
* Version: 1.0
* Date: 2007-11-26
*
****************************************************/
class maxUpload{
var $uploadLocation;
/**
* Constructor to initialize class varaibles
* The uploadLocation will be set to the actual
* working directory
*
* #return maxUpload
*/
function maxUpload(){
$this->uploadLocation = getcwd().DIRECTORY_SEPARATOR;
}
/**
* This function sets the directory where to upload the file
* In case of Windows server use the form: c:\\temp\\
* In case of Unix server use the form: /tmp/
*
* #param String Directory where to store the files
*/
function setUploadLocation($dir){
$this->uploadLocation = $dir;
}
function showUploadForm($msg='',$error=''){
?>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's File Uploader</div><div id="header_right"></div></div>
<div id="content">
<?php
if ($msg != ''){
echo '<p class="msg">'.$msg.'</p>';
} else if ($error != ''){
echo '<p class="emsg">'.$error.'</p>';
}
?>
<form action="" method="post" enctype="multipart/form-data" >
<center>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</center>
</form>
</div>
<div id="footer">Powered by PHP F1</div>
</div>
<?php
}
function uploadFile(){
if (!isset($_POST['submitBtn'])){
$this->showUploadForm();
} else {
$msg = '';
$error = '';
//Check destination directory
if (!file_exists($this->uploadLocation)){
$error = "The target directory doesn't exists!";
} else if (!is_writeable($this->uploadLocation)) {
$error = "The target directory is not writeable!";
} else {
$target_path = $this->uploadLocation . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$msg = basename( $_FILES['myfile']['name']).
" was uploaded successfully!";
} else{
$error = "The upload process failed!";
}
}
$this->showUploadForm($msg,$error);
}
}
}
?>
Hide your upload form by default, and show onclick of a button.
<body>
<div id="uploadForm" style="display:none">
<?php
$myUpload = new maxUpload();
//$myUpload->setUploadLocation(getcwd().DIRECTORY_SEPARATOR);
$myUpload->uploadFile();
?>
</div>
<input type="button" onclick="document.getElementById('uploadForm').style.display='block';">
</body>
If you want a link instead of button use
Upload

Categories

Resources