Trying to pass variable from $.post to php - php

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();

Related

Ajax State, City Drop Down Menu

I'm trying to create a program that when you select a state from the drop down menu, it will display the list of cities for that state in another drop down menu that you can select from. After you choose your city and state, you type in an address, hit submit, and it will display the full address on a new php file.
My issue at the moment is I can get the states displayed, but when the state is selected, it is not giving me the list of options for that city in the second drop down menu. Any help is appreciated, thanks!
You can view the behavior at this link
select.php
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<!DOCTYPE html>
<form action = "display.php">
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select state</option>
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<input type = submit>
</form>
fetch.php
<?php
include(accounts.php);
if(isset($_POST['get_option']))
{
( $dbh = mysql_connect ( $hostname, $username, $password ) )
or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$state = $_POST['get_option'];
$find=mysql_query("select city from zipcodes where state='$state'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['city']."</option>";
}
exit;
}
?>
1)First of all your state option's value attribute is missing
echo "<option value='".$row["state"]."'>".$row["state"]."</option>";
2)Include(accounts.php); accounts.php should be enclosed by double quotes
3) And city option's value attribute is missing
echo "<option value='".$row["city"]."'>".$row["city"]."</option>";
4) Instead of echoing each time concatenate and echo finally like this
$options="";
while($row=mysql_fetch_array($find))
{
$options.= "<option value='".$row["city"]."' >".$row["city"]."</option>";
}
echo $options;
Warning!!!
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
I've modified your code a little. Tried to do it the elegant way. You had wrote too much of superfluous code. You didn't need a <form> element to perform the asked operation. Anyway below is the modified code.
<!DOCTYPE html>
<head>
<title>Address Generator</title>
</head>
<body>
<p id="heading">Address Generator</p>
<center>
<!-- <div id="select_box"> -->
<select name="select_box" id="select_box">
<?php
include ( "accounts.php" ) ;
( $dbh = mysql_connect ( $hostname, $username, $password ) ) or die ( "Unable to connect to MySQL database" );
print "Connected to MySQL<br>";
mysql_select_db( $project );
$select=mysql_query("select state from zipcodes group by state");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['state']."</option>";
}
?>
</select>
<select id="new_select">
</select>
<div id='2'> </div>
<br><br>
<input type = text name="address">Address
<br><br>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#select_box').on('change', function() {
var state = $(this).val();
$.ajax({
url: 'fetch.php',
type: 'POST',
data: {state: state},
success: function(response)
{
var response = JSON.parse(response);
$('#new_select').find('option').remove();
var option = '';
$.each(response.cities, function(key, val) {
option = option + "<option value='" + val + "'>" + val + "</option>";
});
$('#new_select').append(option);
}
});
});
});
</script>
</body>
I've added Jquery before the end of </body> tag. This doesn't hinder your current code execution. However you could always preload it but that tactic is for later.
Since you didn't need any <form> element so I've completely removed it. You can always add it according to your convenience.
I'm running a loop on the cities array of the object response that I'm getting from fetch.php.
parsing the JSON data using JSON.parse() function.
You'll need to json_encode your json variable which will store the corresponding citites data.
I hope this helps. Any further queries are welcome too.

Can't add content to mysql via jquery ajax

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.

JQuery/AJAX script not sending data to php file?

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(),
...
});

Passing Variable to PHP from dynamic dropdown

I'm having a problem passing a variable selected from a dynamic drop dropdown to a PHP file. I want the PHP to select all rows in a db table that match the variable. Here's the code so far:
select.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>"); var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
$.ajax({
type: 'POST',
url: 'display.php',
data: {'result': myval},
});
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<?php include "display.php"; ?>
<div id="result2"></div>
</body>
</html>
And here's the display.php that I want the variable passed to. This file will select the criteria from the db and then print the results in select.php.
<?php
class DisplayResults
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowResults()
{
$myval = $_POST['result'];
$sql = "SELECT * FROM specialities WHERE 'myval'=sp_name";
$res = mysql_query($sql,$this->conn);
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($res))
{
while($row = mysql_fetch_array($result)){
echo "<tr><td>";
echo $row['sp_name'];
echo "</td><td>";
echo $row['sp_code'];
echo "</td></tr>";
}
echo "</table>";
//}
}
return $category;
}
}
$res = new DisplayResults();
?>
I'd really appreciate any help. Please let me know if I can provide more details.
Link to db diagram: http://imgur.com/YZ0SuVw
The first dropdown draws from the profession table, the second from the specialties table. What I'd like to do is to display all of the rows in the jobs table that match the specialty selected in the dropdown box. This will require the result from the variable (result) from the dropdown to be converted into the spec_code that is in the job table. Not sure exactly how to do this. Thanks!
Well it's impossible to answer your question correctly as we don't know whether it's the category or type field which is to be used in your SQL query.
Below is some concept code which should point you in the right direction.
But first, a few comments..
HTML/JS
When you're checking that the cat and type variables are 'greater than 0' on submit you should parse the values to integers first as post values are sent as text by default.
Your myval value is impossible to decipher, please specify your intention.
For further reference your repeated jQuery queries like $("select#type") can be stored in a variable like var $type = $("select#type") and then be referenced like $type.attr('disabled', 'disabled'). I'm not 100% sure how jQuery caches the results but in theory it should require less processing from jQuery, also it's reduces duplicated code.
PHP
Check that the supervariable indexes are set by using isset() or !empty() before using the values otherwise an warning (or notification, can't recall) will be shown. So instead of $myvar = $_POST['myfield'] do $myvar = isset( $_POST['myfield'] ) ? $_POST['myfield'] : "";
Make sure that you escape or cast/sanitize values before they're using a SQL query. For the MySQL library you'd use the mysql_real_escape_string() function.
The mysql library is deprecated and prone to hacks. Usage of the newer mysqli library is highly recommended.
Again, no idea if the sp_name column is for the category or type field. I've included both.
All though it weirdly works to put the value first in your where expression (before the colum name) it's against normal practice and not recommended. Instead of 'myval'=sp_name do sp_name='myval'.
Fixed your loop showResults().
You never called the method showResults() in display.php. Also note that it returns a value so we must also print it to screen.
HTML/JS
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>wait...</option>"); var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
// Fetch values and parse them to integers
var cat = parseInt( $("#category").val(), 10 );
var type = parseInt( $("#type").val(), 10 );
if(cat>0 && type>0)
{
$("#result").html('your choice: '+type);
// Prepare data
var data = {
category: cat,
type: type
}
$.ajax({
type: 'POST',
url: 'display.php',
data: data
});
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form" action="">
Choose a category:<br />
<select id="category">
<?php echo $opt->ShowCategory(); ?>
</select>
<br /><br />
Choose a type:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
<?php include "display.php"; ?>
<div id="result2"></div>
</body>
</html>
display.php
<?php
class DisplayResults
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "db_config.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowResults()
{
// Fetch values from POST and escape/cast the values to prevent SQL injection
$category = (int) ( isset( $_POST['category'] ) ? $_POST['category'] : 0 );
$type = (int) ( isset( $_POST['type'] ) ? $_POST['type'] : 0 );
// Use the values in your SQL query
//
// PLEASE CHANGE THE COLUMN NAMES TO MATCH YOUR SOLUTION
//==================
$sql = "SELECT * FROM specialities WHERE category='". $category ."' and type='". $type ."' ";
$res = mysql_query($sql,$this->conn);
echo "<table border='1'>";
echo "<tr><th>id</th><th>Code</th></tr>";
while($row = mysql_fetch_array($res))
{
echo "<tr><td>";
echo $row['sp_name'];
echo "</td><td>";
echo $row['sp_code'];
echo "</td></tr>";
//}
}
echo "</table>";
return $category;
}
}
$res = new DisplayResults();
// Get and print results
echo $res->showResults();
?>

Post result from a query via php in same page with Ajax

I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.

Categories