jquery ajax not working after str.replace - javascript

I have a jQuery ajax that doesn't work ONLY when there's another jQuery function using javascript's replace function. why is this happening?
note:
this only happens when running on Internet Explorer. It's working fine on Firefox
I'm very new to jQuery (have only been learning jQuery for 2 days). so please be gentle with me :)
this is the html file:
<?php
session_start();
include('koneksi.php');
include('function.php');
unset($_SESSION['cust']);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="jquery-1.12.1.js"></script>
<script src="script.js"></script>
<title>CSS MenuMaker</title>
</head>
<body>
<table class="width100 padding5 border_black" id="tabel_input_master" name="tabel_input_master">
<tr class="my_form">
<td colspan="2">
<div>
<div style="float:left; width:60px">Telepon</div>
<input
type="text"
id="cust_telp"
name="cust_telp"
style="width:200px;"
/>
</div>
<div id="cust_detail" name="cust_detail">
<div style="float:left; width:60px">Name</div>
<input
type="text"
id="cust_name"
name="cust_name"
style="width:200px;"
/>
</div>
</td>
</tr>
</table>
this is the content of script.js:
$(document).ready(function(){
$("#cust_telp").on("change",function(){
var myurl = "show_cust.php?q=" + $(this).val();
var request = $.ajax({
url: myurl,
type: "GET"
});
request.done(function(result){
var cust = JSON.parse(result);
if (cust[0].nama == '') {
$("#cust_name").val('');
$("#cust_name").prop('readonly',false);
}else{
$("#cust_name").val(cust[0].name);
$("#cust_name").prop('readonly', true);
}
});
});
// when I put this script here, the ajax call on [change] event stopped working
$("#cust_telp").on("keyup",function(){
var temp = $(this).val();
temp = temp.replace(/\D/g,'');
$("#cust_telp").val(temp);
});
});
but when I replace the keyup script with this one below, the ajax call works normally again
$("#cust_telp").on("keyup",function(){
var temp = $(this).val();
alert(temp);
});
here's the show_cust.php file
<?php
session_start();
include('koneksi.php');
include('function.php');
$q = (isset($_GET['q'])) ? $_GET['q'] : '';
$outp = '';
unset($cust);
$cust = array();
if ($q != '') {
$sql = "select * from customer where telp1 = '".$q."' or telp2 = '".$q."'";
$query = mysqli_query($link, $sql);
$cust = mysqli_fetch_array($query);
unset($_SESSION['cust']);
$_SESSION['cust'] = $cust;
$outp = "[";
$outp .= '{"name":"' . $cust["name"] . '",';
$outp .= '"address":"' . $cust["address"] . '"}';
$outp .= "]";
}
echo $outp;
?>

A better solution will be to prevent the default nature of keys to prevent the unwanted keys like
$(document).ready(function() {
$("#cust_telp").on("change", function() {
snippet.log('changed: ' + this.value)
});
// when I put this script here, the ajax call on [change] event stopped working
$("#cust_telp").on("keypress", function(e) {
return e.which >= 48 && e.which <= 57;
});
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="width100 padding5 border_black" id="tabel_input_master" name="tabel_input_master">
<tr class="my_form">
<td colspan="2">
<div>
<div style="float:left; width:60px">Telepon</div>
<input type="text" id="cust_telp" name="cust_telp" style="width:200px;" />
</div>
<div id="cust_detail" name="cust_detail">
<div style="float:left; width:60px">Name</div>
<input type="text" id="cust_name" name="cust_name" style="width:200px;" />
</div>
</td>
</tr>
</table>

Related

Cannot show error message "No result Found" in php-ajax-live-search-with-multiple-value

I followed this tutorial on https://www.webslesson.info/2019/03/php-ajax-live-search-with-multiple-value.html
Everything works well, after hosting on my local computer. Except when I search data not available on my database , I want to get error message " No result found on this table" .
Please check the code.
You can check demo here as well, http://demo.webslesson.info/bootstrap-tags-input-with-php/. "No result found error does not pop up when we search invalid value.
Index.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Data Search using Multiple Tag in PHP with Ajax</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput-typeahead.css" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js" crossorigin="anonymous"></script>
<style>
.bootstrap-tagsinput {
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">Live Data Search using Multiple Tag in PHP with Ajax</h2><br />
<div class="form-group">
<div class="row">
<div class="col-md-10">
<input type="text" id="tags" class="form-control" data-role="tagsinput" />
</div>
<div class="col-md-2">
<button type="button" name="search" class="btn btn-primary" id="search">Search</button>
</div>
</div>
</div>
<br />
<div class="table-responsive">
<div align="right">
<p><b>Total Records - <span id="total_records"></span></b></p>
</div>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Customer Name</th>
<th>Gender</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td>'+data[count].CustomerName+'</td>';
html += '<td>'+data[count].Gender+'</td>';
html += '<td>'+data[count].Address+'</td>';
html += '<td>'+data[count].City+'</td>';
html += '<td>'+data[count].PostalCode+'</td>';
html += '<td>'+data[count].Country+'</td></tr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#tags').val();
load_data(query);
});
});
</script>
Fetch.php
<?php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$output = '';
$query = '';
if(isset($_POST["query"]))
{
$search = str_replace(",", "|", $_POST["query"]);
$query = "
SELECT * FROM tbl_customer
WHERE CustomerName REGEXP '".$search."'
OR Address REGEXP '".$search."'
OR City REGEXP '".$search."'
OR PostalCode REGEXP '".$search."'
OR Country REGEXP '".$search."'
";
}
else
{
$query = "
SELECT * FROM tbl_customer ORDER BY CustomerID
";
}
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
?>
as future reference my answer in more than 1 comment line:
In Fetch.php the variable $data will only exist in the case one or more answers are found.
otherwise, the var $data is still not present at the last line: json_encode($data);
Would you have your error_reporting on, it would give you a message about "undefined var data on line X".
PHP will forgive you, and suppose $data has value NULL; So you get a json_encoded form or NULL.
So if you put in the top of your Fetch.php it will always exist and be an empty or a filled array.
This will avoid your error in Javascript where you cannot read the length of NULL.
An empty array however has length = 0.

validating answer submitted to database

<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate">
<div id="display"><script type="text/javascript">document.write(count);</script></div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
</script>
</html>
So basically this is the code I've done so far, I'd like to do a validation to check the count after the user clicks on submit, and check the count with the database answer. Is there anyone out there who can help me out?
in the form use the method in tag form onsubmit ="validation". after you need to implement the validation method in javascript and make a ajax request (in validation) to another php form, in that php form u make the query to db and returning the number of click you need to do. o you need to implement jquery library.
function validation(){
$.ajax({
url: "your_php_requesting_to_db.php",
success: function(data){
if(data == numberofclicks){
return true;
}else{
return false;
}
}
});
}
Here is the new code, im new in this foro so i don't know how to put in a comment the code, im assumng you got the total clicks you need to do, answering your question of timmer here is a little bit of doc
http://www.w3schools.com/js/js_timing.asp
<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate" onsubmit="validate()">
<div id="display">
<script type="text/javascript">document.write(count);</script>
</div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="hidden" id="totalClicks" value="<?php /*IF U GOT THE NUMBER OF CLIC FROM BD PUT IN THERE LIKE ECHO $NUMCLICKS */ ?>"/>
<input type="hidden" id="countClic" value="0" />
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
document.getElementById('countClic').value=count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
function validate(){
var totalClics = document.getElementById('totalClicks').value=count;
var clicksCount = document.getElementById('countClic').value=count;
if(totalClics == clicksCount){
return true;
}else{
return false;
}
}
</script>
</html>

Display tweets retrieved from database after onclick function

I am using JavaScript, PHP and HTML for my application. I have a SQL database that contains tweets. I need to query from database and display tweets after the keyword (connecting to a hyper tree) is clicked. I have researched and tried to include an external php file (generatetweets.php) inside myFunction() at index.php. However it's not working. Anyone can enlighten me or any reference for me to guide?
Thank you in advance.
Extracted example2.js, where child.name refers to the keyword from hyper tree
onComplete: function(){
//Log.write("done");
//Make the relations list shown in the right column.
//ONCLICK FUNCTION FOR KEYWORDS TO LOAD RELATED TWEETS
var node = ht.graph.getClosestNodeToOrigin("current");
var html = "<div><b>Keyword: " + node.name + "</b></div>";
html += "<ul>";
node.eachAdjacency(function(adj){
var child = adj.nodeTo;
var childName=child.name;
html += '<a onClick="myFunction('+'''+child.name+'''+')"><li>'+child.name + '</li></a>';
});
html += "</ul><br />";
$jit.id('inner-details').innerHTML = html;
}
generatetweets.php
<?php
// connect to the database
include "mysqli.connect.php";
// create your SQL statment to retrieve everything from
// the users table
$sql = "SELECT * FROM post WHERE content LIKE '%school%' ORDER BY date DESC";
// run the query
$result = $mysqli->query($sql);
// check for error
if ($mysqli->errno)
{
error_log($mysqli->error);
echo "<br />Something's wrong";
exit();
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
</head>
<body>
<?php
// Check if there are records in the first place
if ($result->num_rows < 1)
{
echo "<h3>No records found</h3>";
}
// Iterate through the records
$counter = 0;
// Use fetch_array to get rows returned one at a time
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<table>
<tr id="tweetlist">
<td style="width:50px">
<!-- name goes here -->
<!--<img id="img<?=$counter?>" style="padding-right:5px" src="<?=$row["displaypicture"]?>"></img>-->
</td>
<td>
<!-- email textfield goes here -->
<span id="date<?=$counter?>" style="color:#CCFF33">[<?=$row["date"]?>] </span>
<span id="name<?=$counter?>">#<?=$row["username"]?>: </span>
<span id="emailTxt<?=$counter?>"><?=$row["content"]?> <span/>
</td>
</tr>
</table>
<br/>
<?php
$counter++;
}
$result->free();
$mysqli->close();
?>
</body>
Extracted index.php, to display tweets in div "demo"
<body onload="init();">
<!-- Header -->
<div id="header" class="container">
<!-- Logo -->
<h1 id="logo">Mood</h1> <!-- logo from style-n1.css -->
<div id="center-container">
<div id="infovis"></div>
</div>
<div id="right-container">
<div id="inner-details"></div>
<div id="log"></div>
<div id="node_name"></div>
<div id="demo" style="padding-left: 50px">
<script type="text/javascript">
function myFunction() {
$("#demo").load("generatetweets.php");
}
</script>
</div>
</div>
</div>
</body>
Hypertree is referenced from http://philogb.github.io/jit/static/v20/Jit/Examples/Hypertree/example2.html
I obtained tweets using nodejs and append it to div. Here is my code.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
#<input type="text" id="tag" class="hash"/>
<button>submit</button>
</form>
<div id="tweets"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect("link to nodejs");
var link;
var tag;
var a;
function debounce(func, wait, immediate){
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply();
}, wait);
if (immediate && !timeout) func.apply();
};
};
var func = debounce(function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
},1000);
$('.hash').keypress(func);
$('.hash').on('change',function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
});
socket.on('message', function(msg){
console.log(msg.length);
$('#tag').val('');
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig ;
var hashregex= /(#[a-z0-9][a-z0-9\-_]*)/ig;
console.log(link);
for(var i = 0; i < msg.length; i++){
msg[i].tweettext=msg[i].tweettext.replace(hashregex,a);
msg[i].tweettext=msg[i].tweettext.replace(regex, "<a href='$1' target='_blank'>$1</a>");
$('#tweets').after('<div>UserName: ' + msg[i].username+ '</div>');
$('#tweets').after('<div>Text: ' + msg[i].tweettext+ '</div>');
$('#tweets').after('<div>Time: ' + msg[i].timedate+ '</div>');
$('#tweets').after('<br></br>');
}
});
</script>
</body>
<html>

AJAX Load and PHP Error

I have created a simple form which submits data to the database.
I want to use Ajax so that when submit is pressed, a loading bar shows and then takes you to the success! page after a few seconds. How do i go about this?
Also the following code gives me the following error, what do i need to fix - SOLVED:
Notice: Undefined index: command in F:\xamppnew\htdocs\web\billing.php on line 5
Code:
<?php
include "storescripts/connect_to_mysql.php";
session_start();
if ($_REQUEST['command']=='update'){
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$address=$_REQUEST['address'];
$phone=$_REQUEST['phone'];
$item_id = $_SESSION['item_id'];
$quantityorder = $each_item['quantity'] = $_SESSION['quantity1'];
$cartTotal = $_SESSION['cartTotal'];
// Add this product into the database now
$sql = mysqli_query($link,"insert into transactions values('','$item_id','$quantityorder','$cartTotal','$name','$address','$email','$phone')");
die('Thank You! your order has been placed!');
}
?>
<!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" />
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
<title>Billing Info</title>
<script language="javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script language="javascript">
function validate(){
var f=document.form1;
if(f.name.value=='' || f.email.value=='' || f.address.value=='' || f.phone.value=='' ){
alert('You have not filled in all fields');
f.name.focus();
return false;
}
f.command.value='update';
f.submit();
}
</script>
</head>
<body>
<div align="center" id="mainWrapper">
<?php include_once("template_header.php");?>
<div id="pageContent">
<div style="margin:24px; text-align:left;">
<br />
<form name="form1" onsubmit="return validate()">
<input type="hidden" name="command" />
<div align="center">
<h1 align="center">Billing Info</h1>
<table border="0" cellpadding="2px">
<tr><td>Product ID:</td><td><?php echo $item_id = $_SESSION['item_id'];?></td></tr>
<tr><td>Total Quantity:</td><td><?php echo $each_item['quantity'] = $_SESSION['quantity1']; ?></td></tr>
<tr><td>Order Total:</td><td>£<?php echo $cartTotal = $_SESSION['cartTotal'];?></td></tr>
<tr><td>Your Name:</td><td><input type="text" name="name" /></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" onkeypress='return isNumberKey(event)' /></td></tr>
<tr><td> </td><td><input type="submit" value="Place Order" /></td></tr>
</table>
</div>
</div>
<?php include_once("template_footer.php");?>
</form>
</body>
</html>
<!--================================== code for "stack_ajax.php" start here ==================================-->
<!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" />
<link rel="stylesheet" type="text/css" href="css/external_css.css">
<script type="text/javascript" src="jquery_src/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function validate(){
var f=document.form1;
if(f.name.value=='' || f.email.value=='' || f.address.value=='' || f.phone.value=='' ){
alert('You have not filled in all fields');
f.name.focus();
return false;
}
f.command.value='update';
postData = $("#form1").serializeArray( );
$.ajax({
type : "POST",
data : postData,
dataType : "html",
url : "ajax_response.php",
async : true,
beforeSend : function( ) {
$("#ajax_image_div").show();
},
success : function(data, textStatus, xhr) {
ajax_response_status = parseInt(data, 10);
if(ajax_response_status)
window.location.href='success_message.php';
else
window.location.href='failed_message.php';
},
error : function(xhr, textStatus, errorThrown) {
alert(textStatus);
},
complete : function(jqXHR, textStatus) {
$("#ajax_image_div").hide();
}
});
return true;
}
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<link rel="stylesheet" href="style/style.css" type="text/css" media="screen" />
</head>
<title>Billing Info</title>
<body>
<div id='ajax_image_div' style="display:none;">
<img id="ajax_loader_image" style="vertical-align:middle" src='image/ajax_loader.gif'>
</div>
<div align="center" id="mainWrapper">
<div id="pageContent">
<div style="margin:24px; text-align:left;">
<br/>
<div align="center">
<form id="form1" name="form1" method="POST" action="" autocomplete="off" enctype="multipart/form-data">
<input type="hidden" name="command" />
<h1 align="center">Billing Info</h1>
<table border="0" cellpadding="2px">
<tr><td>Your Name:</td><td><input type="text" name="name" id="user_name" /></td></tr>
<tr><td>Address:</td><td><input type="text" name="address" /></td></tr>
<tr><td>Email:</td><td><input type="text" name="email" /></td></tr>
<tr><td>Phone:</td><td><input type="text" name="phone" onkeypress='return isNumberKey(event)' /></td></tr>
<tr><td> </td><td><input type="button" name="submit" value="Place Order" onClick="return validate()"/></td></tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<!--================================== code for "stack_ajax.php" end here ==================================-->
<!--============================== code for "ajax_response.php" start here ==============================-->
<?php
/*
Note : I made changes in your HTML form ( You can add session variable by yourself ) and delete following lines
1. <?php include_once("template_header.php");?>
2. <?php include_once("template_footer.php");?>
*/
sleep(3); /* Wait for 3 seconds before executing below code, by doing so
you will be able to see "AJAX LOADER" on the page.
*/
/* print_r($_POST); // You will get all the FORM input data in this array. */
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$address = $_REQUEST['address'];
$phone = $_REQUEST['phone'];
$item_id = $_SESSION['item_id'];
$quantityorder = $each_item['quantity'] = $_SESSION['quantity1'];
$cartTotal = $_SESSION['cartTotal'];
// Add this product into the database now
$sql = mysqli_query(
$link,
"insert
into
transactions
values
('','$item_id','$quantityorder','$cartTotal','$name','$address','$email','$phone')"
);
if( $sql )
echo 1; /* When SQL query will execute successfully. */
else
echo 0; /* When SQL query will not execute successfully. */
exit;
?>
<!--============================== code for "ajax_response.php" end here ==============================-->
/* ================================== code for "external_css.css" start here ==================================*/
#ajax_image_div {
top:30%;
left:30%;
width:50%;
height:50%;
position:absolute;
z-index:999;
}
#mainWrapper {
width:100%;
height:100%;
position:absolute;
}
#ajax_loader_image {
position:relative;
top:35%;
left:35%;
}
/* ================================== code for "external_css.css" end here ==================================*/
<!-- ============================= code for "success_message.php" start here ============================= -->
<?php
echo 'Thank You! your order has been placed!';
?>
<!-- ============================= code for "success_message.php" end here ============================= -->
<!-- ============================= code for "failed_message.php" start here ============================= -->
<?php
echo 'An error occurred, please try after some time ';
?>
<!-- ============================= code for "failed_message.php" end here ============================= -->
<!--
Note : make sure your directory structure must be same as below
php_ajax ( create a folder with "php_ajax" and put all the code inside it )
1. css [ create a folder with "css" name ]
A. external_css.css
2. image [create a folder with "image" name]
A. ajax_loader.gif [ You may download it using internet :-) ]
3. jquery_src [ [create a folder with "jquery_src" name]]
A. jquery-1.11.0.min.js [ jQuery framework, you may download it using internet ]
4. ajax_response.php
5. failed_message.php
6. stack_ajax.php
7. success_message.php
Let me know if you have any problem after implementing this. I put all the codes in separate files to
make DEBUG task very easy.
-->

ajax form not finding javascript function

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?

Categories

Resources