jquery ajax request no displaying php result - php

I have a two-part ajax form that submits data to a php file to process the request on the server-side and return the results.
Here is the HTML form:
<div id="new_loc">
<form id="loc_form" method="post" action="">
<p><b>Country Name</b><br />
<select id="country" name="country" tabindex="1">
<option value="">Choose One</option>
<?php
$cq = mysql_query("SELECT * FROM crm_countries WHERE country_status = '1' ORDER BY country_name ASC");
while($rowc = mysql_fetch_assoc($cq)) {
echo '<option value="' . $rowc['country_code'] . '">' . ucwords(strtolower($rowc['country_name'])) . '</option>';
}
?>
</select></p>
<p id="state_list"><b>State Name</b><br />
<select id="state" name="state" tabindex="2">
<option value="">Choose One</option>
</select></p>
<p><b>City Name</b><br />
<input type="text" id="city" name="city" size="30" tabindex="3" /></p>
<p><b>Zip Code</b><br />
<input type="text" id="zip" name="zip" size="7" tabindex="4" /></p>
<p><input type="submit" id="save_zip" name="save_zip" value="Save" tabindex="5" /></p>
</form>
</div>
Then here is my jquery code to send the data to the PHP file and receive the response:
$(function(){
// THE AJAX QUERY TO GET THE LIST OF STATES BASED ON THE COUNTRY SELECTION
$('#country').change(function(){
// DISPLAYS THE LOADING IMAGE
$("#state_list").html('<img src="images/Processing.gif" />');
var ctry = $('#country').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {c:ctry}
}).done(function(result) {
$("#state_list").html("<b>State Name</b><br />" + result);
});
});
// THE AJAX QUERY TO SAVE THE NEW ZIP CODE TO THE DATABASE
$('#loc_form').submit(function(){
// DISPLAYS THE LOADING IMAGE
$("#new_loc").html('<img src="images/Processing.gif" />');
var sz = $('#save_zip').val();
var ct = $('#country').val();
var st = $('#state').val();
var ci = $('#city').val();
var zc = $('#zip').val();
$.ajax({
type: "POST",
url: "ajax.php",
datatype: "text",
data: {save_zip:sz,country:ct,state:st,city:ci,zip:zc}
}).done(function(result) {
$("#new_loc").html(result);
}).fail(function() {
$("#new_loc").html('<div class="failure">An error occurred. The form could not be submitted.</div>');
});
});
});
And lastly here is the PHP code (in one file called ajax.php) that processes the code:
<?php
session_start();
require ROOT_PATH . '/config.php';
require LAN_PATH . 'english.php';
// GETS THE STATE LIST BASED ON THE COUNTRY SELECTED
if($_POST['c']) {
$sq = mysql_query("SELECT * FROM crm_states WHERE state_country = '{$_POST['c']}' ORDER BY state_name ASC");
$sRows = mysql_num_rows($sq);
if($sRows < '1') {
$result = '<i>Error: No states found!</i>';
}
else {
$result .= '<select id="state" name="state" tabindex="2">';
while($rows = mysql_fetch_assoc($sq)) {
$result .= '<option value="' . $rows['state_abbr'] . '">' . $rows['state_name'] . '</option>';
}
$result .= '</select>';
}
echo $result;
}
// SAVES THE NEW ZIP CODE TO THE DATABASE
if($_POST['save_zip']) {
$zcq = mysql_query("SELECT * FROM crm_zip_codes WHERE zip_code = '{$_POST['zip']}' AND zip_state = '{$_POST['state']}' AND zip_country = '{$_POST['country']}'");
$zcRows = mysql_num_rows($zcq);
if($zcRows == '1') {
$result = '<div class="failure">' . ZIP_EXISTS . '</div>';
}
else {
$azq = mysql_query("INSERT INTO crm_zip_codes VALUES('{$_POST['zip']}','{$_POST['city']}','{$_POST['state']}','{$_POST['country']}','','1')");
$azRows = mysql_affected_rows();
if($azRows != '1') {
$result = '<div class="failure">' . ZIP_ERROR . '</div>';
}
else {
$result = '<div class="success">' . ZIP_ADDED . '</div>';
}
}
echo $result;
}
?>
The first AJAX call seems to work just fine. The data is submitted to the PHP file and a result is returned -> Either the values for the state select form, or the text error message.
The second AJAX call is giving me problems. The information appears to be submitted, but no result (positive or negative) is retunred from the PHP file. I have tested the PHP file through direct $_GET and $_POST requests and it works fine.
I am very new to jQuery, so I don't know where I'm getting stuck. Any help is greatly appreciated.
Thanks!

You need:
$('#loc_form').submit(function(e){
e.preventDefault();
...
});
preventDefault() is needed to prevent the default submission of the form from occurring after the handler runs. The normal submission was reloading the page.

The submit event is being called and your <form> is directing the browser to nowhere action=""
Either don't use a submit button (aka use <input type="button"> or <button>) which would also require changing .submit() to .click() or use the submit button but cancel the default action.
$('#loc_form').submit(function(evt) {
var e = evt || window.event;
e.preventDefault();
...
});
Cheers

Related

Autocomplete existing textbox when selection clicked

I have a form where there are select option and a textbox. All I want to do is when I select specific option, it will pass the id to query the same table to get another column's value based on ID of selected option and then display the value in a textbox before insert/update the table.
This code will works if both field in my form using select field. So in my opinion, maybe my script for storing value in input text field is totally wrong. Please correct me if I do wrong.
My form code :
<form name="inserform" method="POST">
<label>Existing Customer Name : </label>
<select name="existCustName" id="existCustName">
<option value="">None</option>
<?php
$custName = $conn->query("SELECT * FROM customers");
while ($row = $custName->fetch_assoc())
{
?><option id="<?php echo $row['customerID']; ?>" value="<?php echo $row['customerID']; ?>"><?php echo $row['customerName']; ?></option><?php
}
?>
</select>br>
<label>Current Bottle Balance : </label>
<input type="int" id="currentBal" name="currentBal"></input><br>
<input name="insert" type="submit" value="INSERT"></input>
</form>
My script code :
<script type="text/javascript">
$(document).on("change", 'select#existCustName', function(e) {
var existCustID = $(this).children(":selected").attr("id");
$.ajax({
type: "POST",
data: {existCustID: existCustID},
url: 'existingcustomerlist.php',
dataType: 'json',
success: function(json) {
var $el = $("input#currentBal");
$el.empty();
$.each(json, function(k, v) {
$el.append("'input[value='" + v.currentBal + "']").val();
});
}
});
});
</script>
existingcustomerlist.php code:
<?php
include 'config/config.php';
$result = $conn->query("SELECT * FROM customers WHERE customerID = '" .$_POST['existCustID'] . "'");
$results = [];
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
?>
I need help to solve this.
I assume you are trying to show the results as input text element next to the #currentBal element. Try by changing the script tag inside the success callback as shown below.
$.each(json, function (k, v) {
$el.after("<input type='text' class="currentBalTemp" value='" + v.currentBal + "' />");
});
Make sure to remove the .currentBalTemp elements on change event of select otherwise duplication will be shown. Add the below code on change event.
$('.currentBalTemp').remove();

Jquery UI Sortable Update Not Firing

I have been unable to get the Jquery Sortable to trigger an update when the sortable objects are moved. As a prefix - I have spent hours combing this site and the JQuery site trying to fix this problem and have yet to find a successful solution. For whatever reason the update: option does not work.
I am creating a CMS for a site, and have several AJAX scripts to dynamically update my form, as well as a TinyMCE integration. One of the AJAX calls a php script which generates the content for the Jquery Sortable to use. The Jquery Sortable is used to rearrange the positions of various pages. When it is updated it is supposed to use AJAX to run a php function that separates out the data and returns hidden fields for my form validation scripts to use. For testing purposes, right now it also returns visible text. Thank you in advance for your help
I have tried both methods in the Jquery API docs for determining when an update takes place. Here is my Jquery script.
$( function() {
$( "#sortable" ).sortable({
update: function(event, ui){
var list = new Array();
$('#sortable').find('.ui-state-default').each(function(){
var id=$(this).attr('data-id');
list.push(id);
});
var data=JSON.stringify(list);
$.ajax({
url: 'http://localhost/bpta/public2/ajax/np_order_ajax.php', // server url
type: 'POST', //POST or GET
data: {token:'reorder',data:data}, // data to send in ajax format or querystring format
datatype: 'json',
success: function(data){
$("#notes").html(data);
}
})
}
});
$( "#sortable" ).disableSelection();});
Here is a snippet of the html:
<h2>Create Page</h2>
<form action="newpage.php" method="post">
<p>Menu name:
<input type="text" onChange="" name="menu_name" value="" />
</p>
<p>Category:
<select id="category" onClick="getParents(this.value)" name="category">
<?php
$output = " ";
$cat_set = find_all_categories(false);
while ($cat = mysqli_fetch_assoc($cat_set)){
$output .= "<option value=\"";
$output .= htmlentities($cat["cat_id"]);
$output .= "\">";
$output .= htmlentities ($cat["cat_name"]);
$output .= "</option>";
}
echo $output;
?>
</select>
</p>
<div id="parent_page">
</div>
<div class ="position">
</div>
<div id = "notes">
</div>
<p>Visible:
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea id="editable" name="content" rows="20" cols="80">This is a Test!</textarea>
</p>
<input type="submit" id="submit" name="submit" value="Create Page" />
</form> <br />
np_order_ajax.php
if(isset($_POST['token'])){
$data=json_decode($_POST['data']);
$position =0;
$counter=1;
$query ="";
foreach($data as $key=>$val)
{
if ($val == "new"){
$position = $key;
}else if ($val != "new"){
$query.="UPDATE table_name SET position=".$counter." WHERE page_id=".$val."; ";
//save_record($val,$counter);
}
echo "Key: $key; Value: $val \n";
$counter++;}
echo "<p>Reorder working!</p>";
echo "<input type=\"hidden\" name=\"update\" id=\"update\" value=\"".$query."\">";
echo "<input type=\"hidden\" name=\"position\" id=\"position\" value=\"".$position."\">"; }
And here is how I am loading in Jquery:
<script type="text/javascript" src="../includes/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../includes/jquery-ui.js"></script>
EDIT: #Sortable generation
<?php
echo '
<ul id="sortable">';
global $connection;
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE category=".$_REQUEST['category'];
if ($_REQUEST['parent'] != "null" && $_REQUEST['parent'] !=null){
$query .= " AND parent_page=".$_REQUEST['parent'];
}
$query .= " ORDER BY position ASC ";
$page_set = mysqli_query($connection, $query) or die(mysqli_error($connection));
while($result = mysqli_fetch_assoc($page_set)){
$result_pg_name = $result['page_name'];
$result_id = $result['page_id'];
echo "<li class=\"ui-state-default\" data-id=\"".htmlentities($result_id)."\">".htmlentities($result_pg_name)."</li>";
//echo "<li class=\"ui-state-default\">".htmlentities($result_pg_name)."</li>";
}
echo "<li class=\"ui-state-default\" data-id=\""."new"."\">"."New Page"."</li>";
//echo ' <input type="hidden" name="pos" id="activities-input" />';
echo ' </ul>';
?>
For manually triggering events in jquery-ui sortable, instead of specifying the handler in options object, you need to bind the event handler after sortable initialization.
For example the following won't work.
$('#sortable').sortable({
update: function () {
console.log('update called');
}
});
$('#sortable').trigger('sortupdate'); // doesn't work
Following works.
$('#sortable').sortable();
$('#sortable').on('sortupdate',function(){
console.log('update called');
});
$('#sortable').trigger('sortupdate'); // logs update called.

Delete using ajax with a ajax request

I have the below that doesn't seem to work. Where am i going wrong.
The requesting data works fine but when I want to delete using the id from the retrieved data it doesn't do anything.
date.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document)
.ready(function () {
$(".date,.site")
.change(function () {
var site = $("#site")
.val();
var id = $("#date")
.val();
var dataString = 'id=' + id + '&site=' + site;
$.ajax({
type: "POST"
, url: "process.php?process=dselect"
, data: dataString
, cache: false
, success: function (html) {
$(".data")
.html(html);
}
});
});
});
$(document)
.ready(function () {
$(document)
.click('.delete', function () {
var id = $("#data")
.val();
var dataString = 'id=' + id;
alert(dataString);
$.ajax({
type: 'POST'
, url: 'process.php?process=delete'
, data: dataString
, success: function (data) {
if (data == "YES") {
alert("Holiday Deleted")
} else {
alert("can't delete the row")
}
}
});
});
});
</script>
</head>
<body>
<form method="get" action="index.php">
<select name="site" class="site" id="site">
<option>Select Site</option>
<option value="Self Park North">Self Park North</option>
<option value="Self Park South">Self Park South</option>
<option value="Valet North">Valet North</option>
<option value="Valet South">Valet South</option>
<option value="Summer Special">Summer Special</option>
<option value="cleaners">Cleaners</option>
</select>
<br />
<input name="date" type="date" value="" id="date" class="date" />
<p>Select Patroller</p>
<select name="data" class="data" id="data" size="20" style="width:400px;">
</select>
<br />
<input name="delete" type="button" value="delete" class="delete" id="delete" />
<input name="Submit1" type="submit" value="submit" />
</form>
process.php
case "delete":
include('dbconnect.php');
if ($_POST['id']) {
$id = $_POST['id'];
$query = "DELETE FROM taken WHERE id = '$id'";
if ($conn - > query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: ".$conn - > error;
}
}
break;
any help would be appreciated.
I can't tell without complete information - error messages, the definition of the variables you're showing us in the PHP snippet etc. You should check your error logs to see what's actually going on.
That said, there's an error around this:
if ($conn - > query($sql) === TRUE) {
If you try running something simple in PHP to test whether you can expand operators that way you'll see something like the following:
$ php -a
Interactive mode enabled
php > $a = (object) array("1" => "one", "two" => 2);
php > echo $a->two . PHP_EOL;
2
php > echo $a -> two . PHP_EOL;
2
php > echo $a - > two;
PHP Parse error: syntax error, unexpected '>' in php shell code on line 1
You can see that surrounding the operator by whitespace is OK, but splitting it up isn't.
This would cause your script to break, but because you haven't included the errors you're seeing I can't be sure it's the only problem.

ReferenceError: data is not defined or 403 Forbidden

and thank you in advance for reading this. I'm new in php and jquery. I've managed to do few forms in php that worked, and now feel a big need (because of how my webpage is shaping) to make them work with jquery. I'm trying but something is not right. This is the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method ="post" id="form_Add">
<br>
<div class="Add_field" id="title_div">Title:<input typee="text" class="Add_text" maxlength="100" name="title" id="title"></div>
<br>
<div class="Add_field">Discription:<input typee="text" class="Add_text" maxlength="1000" name="discription" id="discription"></div>
<br>
<div class="Add_field" id="content_div">Content:<textarea class="Add_text" maxlength="65535" name="content" id="content" rows="5" cols="15"></textarea></div>
<br>
<div class="Add_field"><label for="shortstory"><input typee="radio" name="prose" class="" id="shortstory" value="1">Short story</label></div>
<div class="Add_field" id="prose_div"><label for="chapter"><input typee="radio" name="prose" class="" id="chapter" value="2">Chapter</label></div>
<br>
<div class="Add_field" id="typey">type:
<select name="type1">
<option value="1" selected="selected">Fantasy</option>
<option value="2">Action</option>
<option value="3">Romance</option>
</select>with elements of
<select name="type2" id="type2">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>and
<select name="type3" id="type3">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>
</div>
<div class="Add_field"><input typee="submit" name="Add_story" class="Add_button" id="submit_story" value="Add story"></div>
</form>
<div id="response">Something</div>
That is script:
<script>
$('#form_Add').on('submit', function (e) {
e.preventDefault();
checkAdd();
});
var selectType = function(){
var type2 = $('#type2').val();
if(type2 === ""){
$('#type3').attr('disabled', 'disabled');
$('#type3').val("");
}
else{
$('#type3').removeAttr('disabled');
}
}
$(selectType);
$("#type2").change(selectType);
function checkAdd(){
var title = $('#title').val();
var content = $('#content').val();
if(title === ""){
$('#titleErr').remove();
$('#title_div').append("<p id='titleErr'>Please add the title.</p>");
}
else{
$('#titleErr').remove();
}
if(content.replace(/ /g,'').length <= 18){
$('#contentErr').remove();
$('#content_div').append("<p id='contentErr'>Content needs to be at least 19 characters long.</p>");
}
else{
$('#contentErr').remove();
}
if($("#shortstory").not(":checked") && $("#chapter").not(":checked")){
$('#proseErr').remove();
$('#prose_div').append("<p id='proseErr'>Check one of the above.</p>");
}
if($("#shortstory").is(":checked") || $("#chapter").is(":checked")){
$('#proseErr').remove();
}
if($("#titleErr").length == 0 && $("#contentErr").length == 0 && $("#proseErr").length == 0){
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', { // when using this bit of script I get 403 Forbidden in Firebug console
title: $('#title').val(),
discription: $('#discription').val(),
content: $('#content').val(),
prose: $('input[name=prose]:checked').val(),
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
}, function(d){
alert(d);
console.log(d);
$('#response').html(d);
});
}
/*
var postData = $("#form_Add").serialize(); // when using this bit of script instead of one on top, I get alert fail and ReferenceError: data is not defined in Firebug console
var formURL = $("#form_Add").attr("action");
$.ajax(
{
url : formURL,
typee: "POST",
data : postData,
datatypee: 'json',
success:function(data, textStatus, jqXHR)
{
alert("success");//data: return data from server
console.log(data.error);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("fail");
console.log(data.error);
}
});
}
*/
};
</script>
And here is php code:
<?php
session_start();
if(isset ($_SESSION['arr'])){
$arr = $_SESSION['arr'];
$uid = $arr['id'];
}
$title = $discription = $content = $prose ="";
if (isset($_POST["Add_story"])) {
$title = stripslashes($_POST["title"]);
$title = mysqli_real_escape_string($connection , $title);
$discription = stripslashes($_POST["discription"]);
$discription = mysqli_real_escape_string($connection , $discription);
$content = stripslashes($_POST["content"]);
$content = mysqli_real_escape_string($connection , $content);
$prose = stripslashes($_POST["prose"]);
$prose = mysqli_real_escape_string($connection , $prose);
$type1 = $_POST["type1"];
$type2 = $_POST["type2"];
$type3 = $_POST["type3"];
$pQuery = "INSERT INTO prose (u_id, data, title_s, discription_s, content_s, prose_s, type1_s, type2_s, type3_s, shows_s)
VALUES ('{$uid}', CURDATE(), '{$title}', '{$discription}', '{$content}', {$prose}, '{$type1}', '{$type2}', '{$type3}', 0)";
$resultP = mysqli_query($connection, $pQuery);
if ($resultP) {
$title = $discription = $content = $prose ="";
}
else {
die("Query failed." . mysqli_error($connection));
}
}
?>
Php code is on the top of the document. Source is on bottom and form is in the middle (I'm using jquery-1.11.1.min.js - source is added in main page, as this one is included in it). I've also tried putting php in separate file and pointing to it through form action instead of <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> but without any joy. I'm guessing my problem is with post data. It probably has to be in an array or object (and I'm doing it wrong) and when it reaches processing there is some sort of incompatibility. Probably using select and radio buttons complicates the process.
Any tips you can share I will greatly appreciate. Thank you for your time.
You have a serious typo in your submit button
<input typee="submit" name="Add_story"
^ extra "e"
which should read as
<input type="submit" name="Add_story"
Your code's execution relies on your conditional statement:
if (isset($_POST["Add_story"])){...}
Plus, you've made the same typo for all your other inputs typee="xxx"
Change them all to type
A simple CTRL-H (typee/type) in a code editor such as Notepad++ even in Notepad will fix that in a jiffy.
I noticed you have given id's to both <select name="type2" id="type2">
and <select name="type3" id="type3"> but not for <select name="type1">, so that could also be another factor that could affect your code's execution, seeing that you have:
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
Edit:
You've also put a commented message which I only saw now and should have been made clear in your question:
// when using this bit of script I get 403 Forbidden in Firebug console
over to the right of
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', {
so I didn't see that.
Try changing it to either, and in single quotes only:
$.post('<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>', {
or
$.post('your_file.php', $(this).serialize(), function(data){
This page may help:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
It contains an example in there that you can base yourself on.
which contains
$.ajax({
type: 'POST',
url: 'post_receiver.php',
data: $(this).serialize()
})
and may need to be added to your script.
You commented out url : formURL, - try using url: 'your_PHP_file.php', in its place, that being the PHP/SQL file that you're using.
If none of this helped, than let me know and I will simply delete this answer.

Get the results of a form to a div without opening the results new page

How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?
<div id="welcome">
<form action="result.php" method="post">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="">Anyplace</option>
.
.
.
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="">Anything</option>
.
.
.
</select>
<input type="submit" class="button" value="Ok Go!"/>
<input id="current" name="current" type="hidden"/>​
</form>
</div>
If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.
Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.
Ajax goes in your javascript code, and looks like this:
$('#mySelect').change(function() {
var sel = $(this).val();
//alert('You picked: ' + sel);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
Here is a working solution for your own example, using AJAX:
HTML MARKUP:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').on('click', function(e){
e.preventDefault(); //prevent default action
var ct = $('#city').val();
var dt = $('#date').val()
var ty = $('#type').val();
var curr = $('#current').val();
$.ajax({
url: 'result.php',
type: 'POST',
data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
success: function(response){
$('#welcome').html(response);
}
});
});
$('#mycurr').click(function(){
var resp = prompt("Please type something:","Your name");
$('#current').val(resp);
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcome">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="sumwhere">Anyplace</option>
<option value="anutherwhere">Another place</option>
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="sumthing">Anything</option>
<option value="anutherthing">Another thing</option>
</select>
<input type="submit" id="mybutt" class="button" value="Ok Go!"/>
<input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
<input id="current" name="current" type="hidden"/>
</div>
</body>
</html>
PHP Processor file: result.php
$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];
if ($date == '') {
$date = 'Some other date';
}
$r = '<h1>Results sent from PHP</h1>';
$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';
$r .= '<h2>And that\'s all she wrote....</h2>';
echo $r;
You can do something like this using jQuery Ajax
Use following code inside your head tag or footer
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript>
$('document').ready(function(){ //after page load
$('.button').on('click', function(e){
e.preventDefault(); //prevent default action
$.ajax({
'url': 'result.php',
'type: 'POST',
'success': function(response){
$('#welcome').html(response);
}
});
});
});
</script>
valit's the action="result.php" who makes your page reload
You shloud try to give an id to your form, and using a simple ajax call :
$("#formId").submit(function() {
$.ajax({
url: 'result.php',
success: function(response) {
$("#welcome").setValue(response); // update the DIV
}
});
return false; // prevent form submitting
});
Cheers

Categories