I am making a question/status posting system using JQuery and Ajax however an error is being displayed "Notice: Undefined index: status in C:\xampp\htdocs\deadline\data.php on line 5" which is my line of code "$var = $_POST['status']; "
My system works as you have to log in to post a question(using sessions) BUT the issue is with my JQuery/AJAX script as the data that I have on homepage.php is not being sent to data.php (from my understanding which is why my index 'status' is undefined).
MY CODE
<?php
include("connection.php");
session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
}
else {
header("location:login.php");
}
$sid = $_SESSION['user_id'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM `users` WHERE id='{$sid}'";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
$fname = $result['fname'];
$lname = $result['lname'];
$time = time();
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = 'status='+status;
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
</head>
<body>
<div id="global">
<form action="" onsubmit="return false">
<textarea id="status"></textarea>
<button id="postbutton">POST</button>
LOGOUT
</form>
<br/>
<br/>
<div id="allstatus">
<!-- SKELETON -->
<div id="status">
<div id="statuspic">
</div>
<div id="statusinfo">
<div id="statusname">JOnathan</div>
<div id="statustext"> this is the question</div>
<div id="statusoption"><button id="likestatus">LIKE</button></div>
<div id="statusoption"><button id="commentstatus">COMMENT</button></div>
<div id="statusoption"><button id="sharestatus">SHARE</button></div>
<div id="statusoption"><button id="statustime">TIME</button></div>
</div>
</div>
<!-- SKELETON -->
</div>
</div>
</body>
</html>
<?php
$var = $_POST['status'];
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'forum';
//connecting
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
} else {
echo " success";
}
$sql = "INSERT INTO `question`(id, question) VALUES ('', '{$var}')";
$result = $conn->query($sql);
if($result) {
echo "inserted successfuly";
}
else {
echo "failed: " . $conn->error;
}
echo " the text: " .$var. " has been added to database.";
?>
HOW IT SHOULD WORK
I want to use JQuery/AJAX on my homepage.php to send data to data.php and that data gets returned back to homepage.php. On success to be displayed in my div #statustext.
Meaning when i write a question in textarea input field the data gets stored in database and retrieved and displayed in my div on the browser.
Please help me thanks..
you should change your script like below. Ajax sends data to url in a serialize manner either you have to use form serialize which will send all the fileds info to your php url other wise if you have to send only one field value then you can do this change
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = {'status='+status};
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
First of all use .val() not .value() when you getting value of your message. Second mistake - is using two id = "sattus". Id of elements must be unique or use class = "" for ident your class of elements.
Don't give same id to more then 1 html element !
In your code :
<textarea id="status"></textarea>
and
<div id="status">
both contains same id ! Please correct it first.Also In your code as Spencer mentioned in his answer that add name attribute with value "status". No doubt as you are using jQuery selector it should pick up correct one,though you can just alert it before sending the request using AJAX.
also set data variable as var data = {status : status};
POST uses name and not id so change this:
<textarea id="status"></textarea>
To this:
<textarea name="status"></textarea>
For the data make sure it's the data for your form, and add method="post" to it so it can send POST data. For example if you gave your form an id of yourForm:
HTML
<form action="" method="post" id="yourForm" onsubmit="return false">
JS
$.ajax({
...
data: $("#yourForm").serialize(),
...
});
Related
This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.
I have a very simple form that has a field for a title and uses quill to enter a discussion. I have tried everything I can think of, but still cannot populate a mysql database with the information. I think I'm getting close, but am not quite there yet. I think the problem lies in my use of json and ajax.
Here is my html file that creates the form:
<!DOCTYPE>
<html>
<head>
<title>Discussions</title>
<meta charset="UTF-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.quilljs.com/1.2.2/quill.snow.css" rel="stylesheet">
<link href = "../css/discussionsEditor.css" rel = "stylesheet">
<script src="https://cdn.quilljs.com/1.2.2/quill.js"></script>
</head>
<body>
<div id="form-container" class="container">
<form id="discussionForm" method = "post" action ="discussionsEditor.php" role="form">
<div class="row">
<div class="col-xs-8">
<div class="form-group">
<input class="form-control" name="title" type="text" placeholder="Title">
</div>
</div>
</div>
<div class="row form-group">
<input name="discussionContent" type="hidden">
<div id="editor-container">
</div>
</div>
<div class="row">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
</div>
<script>
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
['bold', 'italic'],
['link', 'blockquote', 'code-block', 'image'],
[{ list: 'ordered' }, { list: 'bullet' }]
]
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
</script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="../js/discussionsEditor.js"></script>
</body>
</html>
Here is my javascript file where I try to use json and ajax to transfer the data.
var form = document.querySelector('form');
form.onsubmit = function() {
// Populate hidden form on submit
var discussionContent = document.querySelector('input[name=discussionContent]');
discussionContent.value = JSON.stringify(quill.getContents());
var url ="discussionsEditor.php";
var data = stringify(quill.getContents());
alert( "the data is " + data);
$.ajax({
type: "POST",
url : url,
data : discussionContent,
success: function ()
{
alert("Successfully sent to database");
},
error: function()
{
alert("Could not send to database");
}
});
return false;
};
and finally here is my php file
<?php
try
{
$pdo = new PDO('mysql:host=localhost; dbname=mydb', "user", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server:' . $e->getMessage();
include '../output.html.php';
exit();
}
$title = $_POST['title'];
echo "<br />";
echo "the title is " . $title;
$discussionContent = $_POST['discussionContent'];
echo "<br />";
echo "the discussion content is ". $discussionContent;
$sql = 'INSERT INTO Discussions(Title, DiscussionContent)
Values(:Title, :DiscussionContent)';
$statement = $pdo -> prepare($sql);
$statement -> execute(array(':Title' => $title, ':DiscussionContent' => $discussionContent));
?>
If I put 'Denise' in the title field and 'cute' in the quill discussion field, the echo statements in the php file give this result:
the title is Denise
the discussion content is {"ops":[{"insert":"Cute\n"}]}
Nothing is stored in the database.
I would appreciate and help or comments. Thanks
Use getText() method if you simply need a Text value from your quill editor like below:
var quillText = quill.getText();
If you are planning to store HTML data in DB use
var quillHtml = quill.root.innerHTML.trim();
pass the value to your ajax data like this:
$.ajax({
type: "POST",
url : url,
data: {editorContent : quillText },
success: function (data,status, xhr)
{
if(xhr.status == 200) {
alert("Successfully sent to database");
}
},error: function() {
alert("Could not send to database");
}
});
Reason to post as "editorContent" is that you can get the posted values simply by
$_POST['editorContent']
in your PHP script.
After further sanitization, insert the data to DB(either HTML or TEXT).
Hope it helps :-)
Please try the following.It may help to resolve the issue:
comment is editor id.
var quill = new Quill('#comment');
var cc = quill.container.firstChild.innerHTML;
Now cc will hold the data of your div element.That can be inserted into DB.It is just example.You can use if it helps you.
Easy way:
<form method="post" id="identifier">
<div id="quillArea"></div>
<textarea name="text" style="display:none" id="hiddenArea"></textarea>
<input type="submit" value="Save" />
</form>
If you give the form an identifier, then using jQuery you can do the following:
var quill = new Quill ({...}) //definition of the quill
$("#identifier").on("submit",function() {
$("#hiddenArea").val($("#quillArea").html());
})
Now once you have the HTML in the textarea simple post it by clicking submit button
If you want to get only the content, you can add .ql-editor to your selector : $("#hiddenArea").val($("#quillArea .ql-editor").html());
Quill.js is amazing rich text editor but there is very low amount of Youtube videos and google articles about it, other than that their documentation is hard to understand. So new users may have trouble using it.
Lets come to your code...
You need to remove all attributes from form tag except "id".
Your old:
<form id="discussionForm" method = "post" action ="discussionsEditor.php" role="form">
I suggest:
<form id="discussionForm" class="You Can Use Class">
Great, You have done everything fine in JS but you have passed the object wrongly while posting the data. (I also make some new changes)
JavaScript:-
Wait... I hope you haven't forgotten to use this code block in your JS.😅
var quill = new Quill('#service_details_editor', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
//var form = document.querySelector('form');
$("#discussionForm").on('submit', function (e) {
e.preventDefault();
// Populate hidden form on submit
var discussionContent = document.querySelector('input[name=discussionContent]');
discussionContent.value = JSON.stringify(quill.getContents());
var url ="discussionsEditor.php";
var form = new FormData(this);
$.ajax({
type: "POST",
url : url,
data : form,
contentType:false,
processData:false,
success: function (response) //Response which is come from "discussionsEditor.php" if Query run successfully.
{
alert("Successfully sent to database");
},
error: function(response)
{
alert("Could not send to database");
}
});
return false;
});
PHP:-
Your PHP may working well no doubt but I usually write PHP like this. 😄
//Connection Block Start
<?php
$host = "localhost";
$user = "root";
$password = '';
$db_name = "Your DB Name";
$con = mysqli_connect($host, $user, $password, $db_name);
if (mysqli_connect_errno()) {
die("Failed to connect with MySQL: " . mysqli_connect_error());
}
//Connection Block END
if (isset($_POST['title'])) {
$title = $_POST['title'];
$DiscussionContent = $_POST['DiscussionContent'];
$sql = "INSERT INTO Discussions(title,DiscussionContent) VALUES ('$title','$DiscussionContent')";
if (mysqli_query($con, $sql)) {
echo 1;
} else {
echo 0;
}
}
die();
exit;
}
Hi there am a beginner in php and ajax, was trying to create a simple admin page which only submit a message and the message get stored in a mysql database. (via ajax ) however it seems that the no data is being parse through when I hit the submit button(I coded it so that when the submit button is pressed, the message would be send without the page refreshing).
Could someone check to see where my error could be? thank you
admin.php
<!DOCTYPE html>
<html>
<head> <!--inseart script here -->
<script type= "text/javascript" src="js/jquery.js"></script>
</head>
<body>
Message: <input type="text" name="message" id= "message_form"><br>
<input type="submit" id= "submit_form" onclick = "submit_msg()">
<script type= "text/javascript" src="js/func_submit_msg.js"> </script>
</body>
</html>
I have created a separate function file called func_submit_msg.js
//this is a function file to submit message to database
$(document).ready(function submit_msg(){
alert('worked');
$.ajax({
type: "POST",
url: "submit_data.php"
data: { message: message_form},
})
}
a connect.php file is created to connect to mysql database
<?php
$host = "localhost";
$user = "root";
$pass = ""; // phpMyAdmin mysql password is blank ? i believe
$database_name = "test"; //
$table_name = "test_table_1"; //table that will be accessing
//connect to mysql database
$db = new mysqli($host, $user, $pass, $database_name);
//check connection?
if ($db -> connect_error) {
die("error mysql database not connected: " . $db -> connect_error);
}
else {
echo "connected successfully" ;
}
?>
a submit_data.php file is created to submit to database
<?php
include "connect.php";
$insert_data=$db-> query ("INSERT INTO test_table_1(message) VALUES ('$message_form')");
if ($db->query($insert_data === TRUE) ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
error checking code to check whether database was inserted correctly doesn't even echo out whether it is successful or not.
Updated
submit_data.php as per # Maximus2012 suggestion
<?php
include "connect.php";
$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ($_POST['message_form'])");
if ($insert_data === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
No error display but there isn't any data being recorded in the database still.
You should start by adding your success callback to your Ajax: (if you havent already)
$(document).ready(function(){
$('#submit_form').on('click', function(e){
e.preventDefault();
message_form = $('#message_form').val();
$.ajax({
type: "POST",
url: "submit_data.php",
data: {message: message_form},
success: function(data) {
$('#result').html(data);
},
error:function(err){
//handle your error
alert('did not work');
}
});
});
});
Here we use .on() as the preferred method of attaching an
event handler function
We then use .val() to get the value of the message input field
and store it in a variable to be used for POSTing to the submit_data.php script
e.preventDefault() is used so that the default event is cancelled
when click the submit button
In your html, add an element that the result can be returned to: (#result)
<html>
<head>
<script type= "text/javascript" src="js/jquery.js"></script>
<script type= "text/javascript" src="js/func_submit_msg.js"></script>
</head>
<body>
<form action="" method="POST">
Message: <input type="text" name="message" id="message_form"><br>
<input type="submit" id="submit_form">
</form>
<div id="result"></div>
</body>
</html>
Here we wrap your input in a form with the method and action
properties to ensure that the name attributes are able to be used in
POST requests
In your PHP (submit_data.php) you need to assign a value to $message_form before using it:
<?php
include "connect.php";
$message_form = $_POST['message'];
$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ('$message_form')");
if ($insert_data === TRUE ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
If all goes well, you should get some kind of result from this.
Problem solved...variable undefined. I will add full answer when stackoverflow allows me to answer own question
update, firebug is telling me that the variable barrister is undefined in plugin.php but I do define that variable (or at least I try to)
this is the line where it's supposedly undefined: if(barrister.attr("value"))
this is the line where I try to define it: var barrister = $('input:radio[name=barrister]:checked').val();
I'm using a form with a radio button to submit data. The file plugin.php is supposed to get the data using javascript/ajax and then send it to results.php so that it can be inserted into the database. Information's also retrieved from the database and is supposed to be inserted into the html. I can't figure out where it's breaking down, but I do know the database connection itself works. Any idea how I might find out the broken link? When I test it and check the database, there's no data in it.
The form
<form method="post" id="form">
<table>
<tr>
<td><label>Barrister's Exam</label></td>
<td><input type="radio" id="barrister" name="barrister" value="1" /> Pass</td>
<td><input type="radio" id="barrister" name="barrister" value="0" /> Fail</td>
</tr>
<tr>
<td>Submit</td>
<td><input id="send" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
Getting the form data with plugin.php
function my_function() { ?>
<script type="text/javascript">
$(document).ready(function(){
//global vars
var barrister = $('input:radio[name=barrister]:checked').val();
var loading = $("#loading");
var messageList = $(".content > ul");
//functions
function updateShoutbox(){
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=update",
complete: function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000);
}
});
}
//check if all fields are filled
function checkForm(){
if(barrister.attr("value"))
return true;
else
return false;
}
//Load for the first time the shoutbox data
updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){
var barrister = barrister.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to results.php
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php", data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
});
</script>
<?php
}
add_action('wp_head', 'my_function');
putting the data into "results" table of the database "year" with results.php I know the database connection works
<?php
define("HOST", "host");
define("USER", "user");
define("PASSWORD", "password");
define("DB", "year");
/************************
FUNCTIONS
/************************/
function connect($db, $user, $password){
$link = #mysql_connect($db, $user, $password);
if (!$link)
die("Could not connect: ".mysql_error());
else{
$db = mysql_select_db(DB);
if(!$db)
die("Could not select database: ".mysql_error());
else return $link;
}
}
function getContent($link, $num){
$res = #mysql_query("SELECT barrister FROM results ORDER BY date DESC LIMIT ".$num, $link);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
function insertMessage($barrister){
$query = sprintf("INSERT INTO results(barrister) VALUES('%s');", mysql_real_escape_string(strip_tags($barrister))
));
$res = #mysql_query($query);
if(!$res)
die("Error: ".mysql_error());
else
return $res;
}
/******************************
MANAGE REQUESTS
/******************************/
if(!$_POST['action']){
//We are redirecting people to our shoutbox page if they try to enter in our shoutbox.php
header ("Location: index.html");
}
else{
$link = connect(HOST, USER, PASSWORD);
switch($_POST['action']){
case "update":
$res = getContent($link, 100);
while($row = mysql_fetch_array($res)){
$result .= "<li><strong>".$row['user']."</strong><img src=\"http://eslangel.com/wp-content/plugins/myplugin/CSS/images/bullet.gif\" alt=\"-\" />".$row['message']." </li>";
}
echo $result;
break;
case "insert":
echo insertMessage($_POST['barrister']);
break;
}
mysql_close($link);
}
?>
The html where the data is returned to when retrieved from the database
<div id="container">
<ul class="menu">
<li></li>
</ul>
<span class="clear"></span>
<div class="content">
<div id="loading"><img src="http:///></div>
<ul>
<ul>
</div>
</div>
The first error I notice is that all of your radio buttons have the same ID. An ID attribute should be unique on the page. Besides this, the best tool for debugging javascript is the console.
Javascript Debugging for beginners
EDIT
Here's an example of an ajax form submit using your markup http://jsfiddle.net/UADu5/
$(function(){
// Submit form via ajax
$('#check').click(function(){
var barrister = null
$.each($("input[name='barrister']:checked"), function(){
if($(this).val() == 1)
barrister = $(this).attr('value');
});
if(barrister){
$.ajax({
type: "POST", url: "http://yearofcall.com/wp-content/plugins/myplugin/results.php",
data: "action=insert&barrister=" + barrister,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Send" });
}
});
} else {
alert('Please fill all fields!')
}
})
})
<form method="post" id="form">
<fieldset>
<legend>Grade Exams</legend>
<ul>
<li>
<p>Barrister's Exam</p>
<label>
<input type="radio" name="barrister" value="1" /> Pass
</label>
<label>
<input type="radio" name="barrister" value="0" /> Fail
</label>
</li>
<li class="submit">
<input type="button" id="check" value="Test">
</li>
</ul>
</fieldset>
</form>
I strongly recommend using Firebug, as it will show you all the requests being made and all the request/response header info so you can see if and where the AJAX is going wrong. It's also great for debugging HTML/CSS stuff!
Firebug practically changed my life when it comes to JavaScript and CSS.
I think you have error in insert statement:
//remove extra bracket and semicolon
sprintf("INSERT INTO results(barrister) VALUES('%s')", mysql_real_escape_string(strip_tags($barrister))
);
Hope it helps
Change
var barrister = $('input:radio[name=barrister]:checked').val();
to
barrister = $('input:radio[name=barrister]:checked');
should help.
I have one big file (for right now) that is supposed to:
take a variable from a select widget in a form (jQuery)
submit the form asynchronously (jQuery)
return records from a database using the variable selected from the form (php)
The problem is, the variable never seems to reach the php code.
Can anyone tell me what I'm doing wrong, please?
My code:
(all on one page)
<script type="text/javascript">
$(function() {
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.post("index.php", { zip: str}, function(data){
$('result').text(str); }, "json" );
});//end select
});//end function
</script>
<?php include_once ('../cons.php'); ?>
<?php
if (isset($_POST['zip'])){
$value = $_POST['zip'];
}else{
$value = "nada";
}
echo $value;
//I only get "nada"
?>
</head>
<body>
<div id="body">
<form id="findzip"><!-- jQuery will handle the form -->
<select name="zip">
<option value="">Find your zip code</option>
<?php //use php to pull the zip codes from the database
$mysqli_zip = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
$q_zip = "select distinct(zip) from mc m group by zip";
$r_zip = $mysqli_zip->query($q_zip);
if ((!$r_zip) || ($r_zip == NULL)) {
echo "no results ";
}
while($row_zip = $r_zip->fetch_array(MYSQLI_BOTH)) {
echo "<option value='". addslashes($row_zip['zip']) . "'>" . addslashes($row_zip['zip']) . "</option>;\n";
}//end while
?>
</select>
</form>
<!-- here's where the results go -->
<result></result>
<br/>
</div>
</body>
</html>
Your script as written is echoing out a value like "12345". But your $.post is expecting it to be type json. When I removed the json type it worked perfectly for me.
Try putting an ID on it, like so:
<select name="zip" id="zip">
Then getting the value from it like so:
$("#zip").val();