ReferenceError: ajaxfunction is not defined - php

I've been unable to get an ajax script to run for some time.
Basically, I need the user to select an option from one drop down box, then, based on what's selected, the second drop down box with populate accordingly based on a MySQL query.
My Script looks like
<script type="text/javascript">
$(function(){
$('select [name="front-size"]').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html",
success: function(data) {
$("#sub").html(data);
}
});
});
});
</script>
My initial drop down box is populated by a MySQL query like so
<select name="front-size" onchange="ajaxfunction(this.value)">
<?php
$door_size = $db->prepare("SELECT DISTINCT door_size FROM doors WHERE door_model = '".$_SESSION['front_door']."'");
$door_size->execute();
while($row = $door_size->fetch(PDO::FETCH_ASSOC))
{
$size = $row['door_size'];
echo '<option value="'.$size.'">'.$size.'</option>';
}
?>
</select>
The second drop down box is empty
<select name="front-finish" id="sub" onchange="ajaxfunction(this.value)">
</select>
And process.php should do the next query based on what was previously selected (this works on its own)
<?php
session_start();
include ('config.php');
$parent = $_GET['parent'];
$update_option = $db->prepare("SELECT door_finish FROM doors WHERE door_model = '".$_SESSION['front_door']."' AND door_size = '".$parent."'");
$update_option->execute();
while($row = $update_option->fetch(PDO::FETCH_ASSOC))
{
$door_finishes = $row['door_finish'];
echo '<option value="'.$door_finishes.'">'.$door_finishes.'</option>';
}
?>
In Firebug, when I select my first drop down menu, this error is shown and I've been unable to solve it.
ReferenceError: ajaxfunction is not defined
ajaxfunction(this.value)
How can I fix this?

you are calling ajaxfunction but you haven't defined it anywhere in the code.
<script type="text/javascript">
$(function(){
$('select [name="front-size"]').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html",
success: function(data) {
$("#sub").html(data);
}
});
});
});
function ajaxFunction(stuff){
//do ajax stuff here will fix the error
}
</script>
On a broader note, why are you calling that inline in your html (onchange=ajaxfunction(this.value)) when the same thing can be accomplished in your ready function?
<script type="text/javascript">
(function(){
$('select[name="first"]').change(function(){
//do stuff
});
$('select[name="second"]').change(function(){
//do other stuff
});
})
</script>
would be better
EDIT: check this jsfiddle for a working example http://jsfiddle.net/WF8CV/

Related

How can refresh MySQL query in every second using ajax or php?

I'm new in ajax. I have try to find solution but failed. I want to refresh MySQL query in every second but how? I have no idea how to do it so please help me.
CODE
$sql="SELECT * FROM `user`";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
echo $row['email'];
}
Try below
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
You can use jQuery with $.ajax() to get data, setInterval() to call a function every x seconds and $.html() to insert your data into an element.
Here is an example :
setInterval(function(){ getUsers(); }, 1000);
function getUsers()
{
$.ajax({
url: 'myphppage.php',
type: 'post',
success: function(data) {
$('.htmlelement').html(data);
}
});
}
<div class="htmlelement">data will appear here</div>
.htmlelement is an HTML element (ex: a div with a class "htmlelement"), where your results will be inserted.
Brutal solution: set the meta refresh tag in HTML:
<meta http-equiv="refresh" content="1">

getting variable from javascript to php

I have a simple combo box whose value I can get in JavaScript.
I am doing that so I don't need to refresh the page.
Also I want to use the selected value to do some conditional branching after combo box so how do I get the value of combo box from JavaScript to my variable $change.
echo '<select id="combo_1">';
echo '<option value="2">Submative</option>';
echo '<option value="1">formative</option>';
echo '</select>';
Below is my JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
});
});
</script>
Here I want to do $change = $(this).val(), but obviously I cant do it like this.
Any suggestions?
i want to do it on the same page without refreshing or without submitting
my url kinda look like this
http://localhost/lms/grade/report/userdef/index.php
and i want it to be on click action
cuz depending on the choice of combobox 2 very different procedures will be called
You're gonna want to use AJAX and submit the form, then you can access the returned data without ever refreshing the page.
Basically:
HTML
<select name="combo" id="combo_1">
<option value="2">Submative</option>
<option value="1">formative</option>
</select>
JavaScript
$('#combo_1').change(function() {
$.post('calcScript.php', $(this).serialize(), function(data) {
alert(data);
});
});
in PHP, you can access your combo data via $_POST['combo'].
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
var combo_1 = $(this).val();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {'combo_1':combo_1},
success: function(data){
alert(data)
}
});
});
});
</script>
ajax.php
if( isset($_GET['combo_1]) ) {
echo $change = $_GET['combo_1'];
}
JS:
$.ajax({
type: "POST",
url: './filename.php',
beforeSend: function(){
//If you want to do something
},
data: 'data='$('#combo_1').val(), //Optional '&data2='+value+'&datan='+value,
success: function(msg){
alert(msg);
}
});
PHP:
$val = $_POST['data'];
return 'received successfully';
This will alert 'received successfully'

TypeError: $(...) not a function

I've used jQuery to create a page where users can click on a cell in a table that says, "delete," and it will send an ajax request to delete that entry from a database based on the id of the cell and then it will alter the CSS to hide the cell.
I created a test page while I was creating/tweaking the jQuery code. This page works perfectly. Here is the code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
(function( $ ){
$.fn.deleterow = function(event) {
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = event.target.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
}
})( jQuery );
});
</script>
</head>
<table border="1">
<tr>
<td>Cell 2, Row 2</td><td onclick="$(this).deleterow(event);" id="13376">delete</td>
</tr>
</table>
<html>
Now I'm working on getting the code to work in the actual page that it's going to be used in. This page has a short form where users can select their name and a date. This form sends an ajax request that returns the results in a div. The data that is returned is a table , and this is where I'm trying to get my function to work. This table has a tablesorter script attached to it and also my function attached to it.
The tablesorter still works fine, but nothing happens when I click the cell with "delete" in it. I used FireBug to look at the issue and it gives me the error, "TypeError: $(...).deleterow is not a function"
Here is the code for the main page where the user submits a form and where the result is loaded in a div:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src='jquery.tablesorter.js'></script>
<script type='text/javascript'>
$(document).ready(function()
{
$('#myTable').tablesorter();
}
);
</script>";
</head>
<body id="my-students">
<?php include 'header.php'; ?>
<?php include 'nav-tutoring.php'; ?>
<div id="content">
This is where you can view students whom you have assigned to tutoring.
<p>
You may change the way each column is sorted by clicking on the column header.
<p>
<b>Select your name and the date to view students you have assigned for that day.</b>
<form> My form is here; removed to make post shorter </form>
<script>
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: "mystudents.php",
data: $('#name').serialize(),
success: function(data) {
$("#list").empty();
$('#list').append(data);
}
});
return false;
});
</script>
<div id="list"></div>
Here is the code for the page that is inserted into the div underneath the form. This is the page where the tablesorter works, but I cannot get my function to work. I've also made sure that I include these script libraries in the head of the main page where this div is.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type='text/javascript' src='jquery.tablesorter.js'></script>
<script type='text/javascript'>
$(document).ready(function()
{
$('#myTable').tablesorter();
(function($) {
$.fn.deleterow = function(event) {
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = event.target.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
}
})(jQuery);
});
</script>
<table id='myTable' class='tablesorter' border="1">
<thead><tr><th>ID Number</th><th>Last</th><th>First</th><th>Tutoring<br>Assignment</th><th>Assigning Teacher</th><th>Delete?</th></tr></thead><tbody>
<?php
while($row = mysql_fetch_array($data)){
echo "<tr><td>".$row['id']. "</td><td>". $row['last']. "</td><td>". $row['first']."</td><td>". $row['assignment']."</td><td>". $row['assignteacher']."</td><td onclick='$(this).deleterow(event);' id='".$row['pk']."'>Delete</td></tr>";
}
?>
</tbody></table>
I've done many searches based on the error I'm getting, but I just can't seem to fix the problem. Any help would be greatly appreciated.
First it makes no sense to include the $.fn.deleterow = function(event) { inside the document.ready. You should move it outside of that method.
Personally I would change the code to not rely on the inline event handlers in the table. You are using jQuery, so utilize it. Use event bubling to your advantage.
Add it to the table level and listen for click events on the td's that have ids.
$("table tbody").on("click", "td[id]", function(e){
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = this.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
});
jsFiddle
Test if jQuery loaded in console (check for jQuery variable)...
You should wrap your code this way:
(function( $ ){
$(document).ready(function(){
$.fn.deleterow = function(event) {
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = event.target.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
}
});
})( jQuery );
But the most important is check if jQuery are loading correctly and solve it...
Hope it help
try rewriting to a usual javascript function
function deleterow(id) {...}
and in php
echo "<tr><td>".$row['id']. "</td><td>". $row['last']. "</td><td>". $row['first']."</td><td>". $row['assignment']."</td><td>". $row['assignteacher']."</td><td onclick='deleterow(".$row['id']. ")' id='".$row['pk']."'>Delete</td></tr>";
It's due to this:
<td onclick='$(this).deleterow(event);'
JavaScript can't see this as a function due to the enclosing ' '.
What I advise doing is this:
<td class='deleterow'>
then
$(body).on('click', '.deleteRow', function(event) {
$(this).deleterow(event);
});
You'd be better off binding those events using jQuery's handers instead of onclick, which is poor practice. Eg:
$('#myTable').on('click', 'td', function(e) {
$(this).deleterow(e);
});

Trigger a second ajax function when the first has completed

Ok so im trying to start an ajax call after the first call has completed. I have a form with 3 drop down menus. The first menu onload runs the script to bring back values. I then want to feed the vale into the second script and run the script to populate the second 3rd menu.
the second dropdown is populated onChange of the first. This works great. I then want the result of that feed into to third drop down. I know my external queries are right I just think the ajax is wrong. Here is my Ajax calls....
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function() {
jQuery('#networks').trigger('change');
});
function get_cities(networks)
{
$.ajax({
type: "POST",
url: "select.php",
beforeSend: function () {
$("#folder").html("<option>Loading ...</option>");
},
data: "idnetworks="+networks +"&par="+ <?php echo $row_rs_doc['parentid']; ?>,
success: function(msg){
$("#folder").html(msg);
}
});
}
</script>
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function() {
jQuery('#folder').trigger('change');
});
function get_sub(folder)
{
$.ajax({
type: "POST",
url: "select2.php",
beforeSend: function () {
$("#subfolder").html("<option>Loading ...</option>");
},
data: "iddocs="+folder,
success: function(msg){
$("#subfolder").html(msg);
}
});
}
</script>
ok here are the form fields
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
<?php create(network, networkid, netname);?>
</select>
<select name="folder" id="folder" onChange='get_sub($(this).val())'>
</select>
<select name="subfolder" id="subfolder">
</select>
KISS it. Just put the second ajax call inside the success of the first one
You can use deferred objects, which will allow you to initiate additional actions without having to rewrite your existing event handler, and without nesting your code too much:
var req1 = $.ajax(...);
req1.done(function() { ... } ); // start your second request

getting values from textbox using jquery [output via php variable]

main.php:
<SCRIPT type="text/javascript">
$("#btnSubmit").click(function () {
alert("What will i put here!");
});
</SCRIPT>
<input type = "submit" id = "btnSubmit" value = "Try IT!" />
<div id = "show_search2">
</div>
output.php:
<?php $val = $_POST['btnSubmit'];
echo "<H1>$val</H1>"; ?>
What specific jQuery functionality can get the value of the btnSubmit and access it through $_POST and output it to the div show_search2? I used prototype.js but it provides conflict with my other JS scripts in the index.
Note: all my script source is included in index and that's why I didn't include the source in this post.
Do you mean something like this:
$("#btnSubmit").click(function (e) {
e.preventDefault();
var submitVal = $(this).val();
$.ajax({
type: "POST",
url: "url_of_your_output.php",
data: {btnSubmit : submitVal},
success: function(response) {
$("#show_search2").html(response); //response from output.php
}
});
});

Categories