I have data-binding listing working fine. In listing, I have first column for order level. All data is coming from Ajax based server side.
HTML CODE:
<div class='general_content' id="designations_items">
<div class="listing-grid">
<div class="listing_wrapper">
<!--Listing Columns-->
<div class="column heading option_cols">
Order Level
</div>
<div class="column heading desig_cols">
Designation Name
</div>
<div class="column heading desig_cols">
Job Description
</div>
<div class="column heading option_cols">
Options
</div>
<!--Listing Data-->
</div>
<form name="desig_order_level" action="<?php echo $url?>manage/designation_order_level/" id="desig_order_level">
<div class="listing_wrapper" data-bind="foreach: Designations">
<div class="column data_display option_cols">
<input name="orders[]" data-bind="value: Desig_Order" class="fancyInput_smaller">
</div>
<div class="column data_display desig_cols" data-bind="text: Desig_Name"></div>
<div class="column data_display desig_cols" data-bind="text: Desig_Desc"></div>
<div class="column data_display option_cols">
Remove
</div>
</div>
</form>
</div>
</div>
This is my JS code:
function GetDesignations(handleData) {
$.ajax({
url: 'get_designations.php',
type: "post",
data: '',
dataType: 'json',
success: function(data){
handleData(data);
},
error:function(data){
alert('Failed');
}
});
}
$(function () {
var Designation_ViewModel = function() {
var self = this;
self.Designations = ko.observableArray();
self.update = function() {
GetDesignations(function(output){
self.Designations.removeAll();
$.each(output, function (i) {
self.Designations.push(new deisgnation_data_binding(output[i]));
});
});
};
self.addnewItem = function () {
var newitem = JSON.parse('{"Name":"'+$("#Name").val()+'", "Desig_desc":"'+$("#Desig_desc").val()+'"}');
self.Designations.push(
new deisgnation_data_binding(newitem)
);
};
self.removeToDoItem = function(item) {
self.Designations.remove(item);
};
};
var Designation_ViewModel = new Designation_ViewModel();
var y = window.setInterval(Designation_ViewModel.update,1000);
ko.applyBindings(Designation_ViewModel, document.getElementById("designations_items"));
});
var deisgnation_data_binding = function (data) {
return {
Desig_Order: ko.observable(data.Desig_Order),
Desig_Name: ko.observable(data.Desig_Name),
Desig_Desc: ko.observable(data.Desig_Desc)
};
};
After few seconds, listing is being auto updated for new records... In that case, order level is also getting new database entries for each record.
Issue is that at user side I cannot input new values in order level input box to update, when I select the text box to enter new value all listing gets update due to this reason unable to let user update order level.
As I see your records are updated every 1 second due to
var y = window.setInterval(Designation_ViewModel.update,1000);
I think you should use setTimeout instead of setInterval here. setTimeout will execute update function only once
window.setTimeout(Designation_ViewModel.update,1000);
Related
Hey I am trying to insert into mysql/php/ajax with multiforms on a page.
The insert works fine, but form nr 2, sets form nr 1´s data into the mysql DB.
I have 4 forms on each page, it is a firecheck on a dorm, where I need to check 28 kitchens if they keep the standard firerules.
so what I need is the little goldcorn to make this work :) so each form, only respond on the data in that form.
Here is my code:
<div class="content">
<a class="hide" id="1a" name="1a">1A</a><br>
<form action="" id="1a" method="" name="1a" novalidate="novalidate">
<div class="wrapper">
<div class="table">
<br>
<br>
<div class="row header">
<div class="cell">
1A
</div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Døre
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="door" name="door" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Skilte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="skilt" name="skilt" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Nødlys
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="lys" name="lys" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandtæppe
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_t" name="b_t" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandspørjte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_s" name="b_s" rows="3">Ok</textarea>
</div>
</div>
</div>
<input id="dato" name="dato" type="hidden" value="<?php echo date(">") ?> <!--class = "btn btn-success btn-block" -->/>
<button class = "send" id = "insert-data1a" name = "insert-data1a" onclick = "insertData1a()" type = "button">Insert Data</button><br>
<p id = "message1a"></p>
</div><!--end wrapper -->
</form>
</div><!--end content -->
<script type = "text/javascript">
function insertData1a() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1a.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1a").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
the next form, looks the same, but new insert-data name and form name.
Insert Data
<script type="text/javascript">
function insertData1b() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1b.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1b").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
<?php
include('db.php');
$door=$_POST['door'];
$skilt=$_POST['skilt'];
$lys=$_POST['lys'];
$b_t=$_POST['b_t'];
$b_s=$_POST['b_s'];
$dato=$_POST['dato'];
$stmt = $DBcon->prepare("INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
$stmt->bindparam(':door', $door);
$stmt->bindparam(':skilt', $skilt);
$stmt->bindparam(':lys', $lys);
$stmt->bindparam(':b_t', $b_t);
$stmt->bindparam(':b_s', $b_s);
$stmt->bindparam(':dato', $dato);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
the one for b, looks almost the same
$stmt = $DBcon->prepare("INSERT INTO 1_b(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
In addition to Bakayaro's answer, if all your forms got the same fields, you can optimize your code to use only one javascript function and one PHP insert script.
Factorise your code ! Rembember one thing : DRY (Don't Repeat Yourself)
HTML
Add a click listener on each .send button instead of using onclick() on them
Add specific ID on each different form, with kitchen ID
Add data to .send button with related form's kitchen ID
Example for kitchen 1A:
<!-- Add specific ID with kitchen ID -->
<form action="" id="kitchen1a" method="" name="1a" novalidate="novalidate">
...
<!-- Add data to each .send button with related form's kitchen and remove onclick() -->
<!-- data-kitchen="1a" -->
<button class = "send" id = "insert-data1a" name = "insert-data1a" data-kitchen="1a" type = "button">Insert Data</button>
Don't use same ID on different HTML elements, as your a and form tag.
Javascript
Use click listener
Get active form's data from each field's name
Working example based on your code:
$('.send').on('click', function(e) {
var kitchen = $(this).data('kitchen');
var form = $('#kitchen' + kitchen);
var data = {
door: form.find('[name="door"]').val(),
skilt: form.find('[name="skilt"]').val(),
lys: form.find('[name="lys"]').val(),
b_t: form.find('[name="b_t"]').val(),
b_s: form.find('[name="b_s"]').val(),
dato: form.find('[name="dato"]').val(),
// add active kitchen in your POST data
kitchen: kitchen,
};
// AJAX code to send data to php file.
$.ajax({
type: "POST",
// use same PHP script for each forms
url: "insert.php",
data: data,
dataType: "JSON",
success: function (data) {
// use kitchen's specific message tag
$("#message" + kitchen).html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
// alert(err);
console.log(err);
}
});
});
PHP file
Use one single PHP script for each form and generate table name in your SQL query from given kitchen value.
Working example based on your code:
$kitchen = $_POST['kitchen'];
// if your kitchens are all formatted like this : 1a, 2c, 14a, ...
preg_match('/(\d)+([a-z])/', $kitchen, $matches);
$stmt = $DBcon->prepare("INSERT INTO " . $matches[1] . '_' . $matches[2] . "(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
Generated query for your 1a form:
INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato) VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)
If I do understand well, you have multiple forms on one page and the second form posts the values of the first form.
I think the problem is that you're using tha same ids on the fields of the forms.
Take a look at:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
These are the fields from insertData1a() function and it's the same in the other function:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
So basically the problem is that you're referencing the same fields in the second function.
The id attribute must be a unique id for an HTML element, so you should use different ids in each form or if you're already using different ids (you didn't post the html of the second form) you just have to rewrite the elements in your second function.
I'm currently new in backbone.js. I use CodeIgniter as my PHP Framework.
I'm developing an existing system which uses a backbone.js library. My problem is easy if i will do it in jquery but since this uses a backbone.js, I should do it the same way. This what happens.
Once the page is loaded, i will populate the users inside a select box. then with a button 'ADD'. I will populate also the uses already added inside the ul element to list all the users with an x anchor if you want to delete the user.
I append the user in the list after success ajax in create warehouse user. I use jquery to append. Now the click event to delete is not working because backbone already done rendering the views. How to re render backbone click event for newly added element?
Below is my sample code
HTML CODE
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-list"></i> User Access
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form method="POST" action="<?php echo base_url();?>warehouse/user" id="add-warehouse-user-form">
<div class="col-lg-4">
<div class="form-group">
<label for="users">Available Users </label>
<input type="hidden" name="wh_id" id="wh_id" value="<?php echo $warehouse->wh_id; ?>" />
<select class="form-control" name="users" id="users">
<?php if(!empty($users)){
foreach($users as $row){
//if(in_array('Head',$row->user_access) AND $row->status == 'ACTIVE'){
echo '<option value="'.$row->user_id.'">'.$row->first_name.' '.$row->last_name.'</option>';
//}
}
}?>
</select>
</div>
</div>
<div class="col-lg-1">
<div class="form-group">
<label for="users"> </label>
<input type="submit" class="btn btn-success form-control" value="Add" />
</div>
</div>
</form>
</div>
</div><br />
<div class="row">
<div class="col-lg-12">
<div class="col-lg-5">
<ul class="list-group" id="list_user">
<?php if(!empty($userlist)){
foreach ($userlist as $ul) {
echo '<li class="list-group-item">'.$ul['name'].' <span class="badge badge-delete"><a class="deleteUser" href="#" data-id="'.$ul['module_id'].'" data-uid="'.$ul['id'].'" data-name="'.$ul['name'].'">x</a></span></li>';
}
} ?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
Warehouse model
var WarehouseUserModel = Backbone.Model.extend({
urlRoot: Config.apiBaseUrl + "/warehouse/user",
defaults: {
wh_id: "",
users: ""
}
});
var WarehouseUserDelModel = Backbone.Model.extend({
urlRoot: Config.apiBaseUrl + "/warehouse/user"
});
Warehouse View
var WarehouseView = Backbone.View.extend();
//-------------- add user to warehouse --------------//
var WarehouseUserAddNewView = Backbone.View.extend({
el: "#add-warehouse-user-form",
loaderEl: "#form-loader",
events:{
"submit": "createWarehouseUser"
},
createWarehouseUser: function (e) {
var self = this;
e.preventDefault();
var formData = Util.getFormData($(self.el));
var warehouseUser = new WarehouseUserModel(formData);
//disable form
$(self.el).find(" :input").prop("disabled", true);
//show loader
$(self.loaderEl).removeClass("hidden");
warehouseUser.save({}, {
success: function (model, res, options) {
if (res.status == "error") {
Util.formError(res.data);
var errorTemplate = _.template($("#toast-error-template").html());
toastr.error(errorTemplate({errors: res.data}));
//re-enable form
$(self.el).find(" :input").prop("disabled", "");
//hide loader
$(self.loaderEl).addClass("hidden");
} else {
//location.href = res.data.redirectUrl;
/** append user to list and remove from select box **/
$('#list_user').append('<li class="list-group-item">'+$("#users option[value='"+$("#users").val()+"']").text()+' <span class="badge badge-delete"><a class="deleteUser" href="#" data-id="'+res.data.id+'" data-uid="'+$("#users").val()+'" data-name="'+$("#users option[value='"+$("#users").val()+"']").text()+'">x</a></span></li>');
$("#users option[value='"+$("#users").val()+"']").remove();
//re-enable form
$(self.el).find(" :input").prop("disabled", "");
//hide loader
$(self.loaderEl).addClass("hidden");
}
}
});
},
initialize: function () {},
});
//-------------- remove user from warehouse --------------//
var WarehouseUserDeleteView = Backbone.View.extend({
el: ".deleteUser",
events:{
"click": "deleteWarehouseUser"
},
deleteWarehouseUser: function (e) {
elem = $(e.currentTarget)[0];
var self = this;
e.preventDefault();
var warehouseUser = new WarehouseUserDelModel({'id':$(elem).data('id')});
warehouseUser.destroy({
success: function (model, res, options) {
console.log(model);
console.log(res);
console.log(options);
if (res.status == "error") {
Util.formError(res.data);
var errorTemplate = _.template($("#toast-error-template").html());
toastr.error(errorTemplate({errors: res.data}));
} else {
/** append user to select box and remove from lists **/
$("#users").append("<option value='"+$(elem).data('uid')+"'>"+$(elem).data('name')+" </option>");
$(elem).parents('li.list-group-item').remove();
}
}
});
},
initialize: function () {},
});
new WarehouseUserAddNewView();
new WarehouseUserDeleteView();
The actual code that renders your list of users will probably always be jquery - backbone does not come with default render functionality. However, it is common practice to put code that will render the entire contents of the el in a render method of the view. That way it can be called initially, and then called again whenever conditions have changed.
It looks like your general approach is to use each view a bit like an event handler. Each has a single event attached, with one sizeable method to do some work. That's fine as long as it's working for you, but you can also have a more complicated view than handles multiple functions. I might recommend you use your WarehouseView to keep a list of users, and handles both a reusable render, and the delete method you have already written:
var WarehouseView = Backbone.View.extend({
el: '#list_user',
initialize: function(options) {
this.users = (options && options.users) || [];
// render once on intialize
this.render();
},
events: {
// listen for delete clicks on contained elements
'click .deleteUser': 'deleteWarehouseUser',
},
deleteWarehouseUser: function(ev) {
// your same method code should work here
},
render: function() {
// render the list of users you have
this.$el.html('');
for (var i = 0; i < this.users.length; i++) {
// use jquery to add the user to your list as a <li>
}
}
});
var warehouseView = new WarehouseView();
If you use this approach, then inside your add new user method you can do things like:
// ... create your user variable
warehouseView.users.push(user);
warehouseView.render();
The delete (client-side) can also consist of removing a particular user from your view's list, and then rerendering.
You can arrange backbone objects pretty much any way you like, but I hope this recommendation helps. Also note that once you feel more comfortable, creating a Backbone Collection for your users is the more "backbone-y" way to do things rather than a plain array.
I'm working on a new website, and i want to learn more about JSON
The website is using jQuery and PHP
I have a jQuery window that gets opend to add a new menu item or submenu item. In this window is also standing a select menu with the added menu and submenu items.
If i have added a new item than it will be added by an ajax request into the database, ofcourse i want to try to avoid window refreshing to see the new added items in the select menu.
The next code is triggering my window and sends the form to a PHP script.
`
var SITE_URL = "http://martin.eenwittekerst.nl/";
$$.ready(function() {
$( "#dialog_add_menu" ).dialog({
autoOpen: false,
modal: true,
width: 900,
open: function(){ $(this).parent().css('overflow', 'visible');
$$.utils.forms.resize() }
}).find('button.submit').click(function(){
var $el = $(this).parents('.ui-dialog-content');
if ($el.validate().form()) {
var filename = SITE_URL+"/admin/requests/menu.php";
$.ajax
({
type: "POST",
url: filename,
data: "do=add&"+$('form#menu').serialize()+"",
success: function(msg)
{
document.getElementById("return_message").innerHTML = msg;
}
});
var filename2 = SITE_URL+"/admin/reloads/menuItems.php";
$.ajax({
type: "GET",
url: filename2,
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//do your stuff with the JSON data
alert(data);
}
});
$el.find('form')[0].reset();
$el.dialog('close');
}
}).end().find('button.cancel').click(function(){
var $el = $(this).parents('.ui-dialog-content');
$el.find('form')[0].reset();
$el.dialog('close');;
});
$( ".open-add-menu-dialog" ).click(function() {
$( "#dialog_add_menu" ).dialog( "open" );
return false;
});
});
`
This is included a part where i'm testing with JSON, i will put that piece of code here again where i'm trying to do the JSON thing
`
var filename2 = SITE_URL+"/admin/reloads/menuItems.php";
$.ajax({
type: "GET",
url: filename2,
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//do your stuff with the JSON data
alert(data);
}
});
`
At the end i have an alert that's not giving anny respons, not even an empty alert
Sorry for beeing a noob in this, but this is my first time i'm doing this. I have tested a lot what's standing on the internet without success.
The code in my PHP code is verry simple and only for testing ofcourse
`
include(BASE_DOC."config.php");
include(BASE_DOC."classes/cls.db.php");
// Open the database connection
$cOpenDB = new database_connection;
echo $cOpenDB->db_open(DB_HOST, DB_USER, DB_PASS, DB_TABLE);
$rows= array();
$sql = mysql_query("SELECT * FROM menu_items") or die(mysql_error());
while($data = mysql_fetch_array($sql))
{
$rows[] = $data['id'].",".$data['menu_item_name'];
}
echo json_encode($rows);
?>
`
Now i dont understand how to get the JSON array from my PHP script and how to rebuild the HTML of my select menu
Here i have the code of my HTML of the windowedbox to add a new sub- menu item
`
<!-- Add New Menu Item -->
<div style="display: none;" id="dialog_add_menu" title="Voeg een nieuw menu item toe">
<fieldset id="menu">
<form action="" class="full validate" id="menu">
<div class="row">
<label for="d2_menu_item">
<strong>Menu item naam</strong>
</label>
<div>
<input class="required" type="text" name="menu_name" id="menu_name" />
</div>
</div>
<div class="row">
<label for="d2_menu_item_alt">
<strong>Menu item alt</strong>
</label>
<div>
<input class="required" type="text" name="menu_alt" id="menu_alt" />
</div>
</div>
<div class="row">
<label for="d2_menu_item_sub">
<strong>Wordt dit een submenu item?</strong>
</label>
<div>
<select name="sub_option" id="sub_option">
<option value="n">Nee</option>
<option value="y">Ja</option>
</select>
</div>
</div>
<div class="row" id="showMenuItems">
<label for="d2_select_menu_item">
<strong>Selecteer een Menu item om een submenu item aan te koppelen</strong>
</label>
<div>
<div id="sub_menu_item_of">
<select name="sub_of" id="sub_of">
<option>Kies een menu item om een sub menu item aan te koppelen</option>
<?PHP
$cMenuItems = new menu();
echo $cMenuItems->menuItemsSelect("'menu_item_name','menu_item_alt'", "menu_items");
?>
</select>
</div>
</div>
</div>
</form>
<div class="actions">
<div class="left">
<button class="grey cancel">Annuleren</button>
</div>
<div class="right">
<button class="submit">Voeg menu item toe</button>
</div>
</div>
</fieldset>
</div>
<!-- End if #dialog_add_menu -->
`
For the first time is this a real pain in the ass to do, but if someone can help me with this than i'm forever greatfull to you all!
If you have anny questions or need more information let me know!
Sorry for sometimes my poor english
Kind regards
Martin Meijer
When debugging ajax, you have to make sure
- the ajax request did sent (check you firebug network console)
- the php did return a reponse : log before the return "json_encode($rows);"
- the ajax did got a correct reponse : add a error block in your ajax call :
$.ajax({
...
error: function(response) {
alert(JSON.stringify(response));
}
});
Also check you php.log file.
I am currently using Ajax/JS to submit a form without a page refresh or button click. I have set a timer with keyup to trigger the function. I have tested it with one input field and works well but now that other input fields have been added I am getting no results echoed out by the PHP. I have checked with firefox bug tool and the results are being stored. I am not sure if this a JS or PHP issue.
How can I properly echo the value of input field after the user has stop typing? EXAMPLE
JS/AJAX
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
var name = $("#contact_name, #email, #phone, #address, #website").val();
dataString = 'name='+ name;
});
});
</script>
HTML/PHP Snippet
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
Rather than trying to do a mass assignment, you'll need to build up your data. E.g., you currently have:
var name = $("#contact_name, #email, #phone, #address, #website").val();
That jquery should match on the first identifier it matches, most likely the element with id contact_name, and that will be the only value name has, where as you're hoping to get several form fields of data.
In fact, you shouldn't need to build up dataString at all, as your data will be submitted by post via the form.
Rewriting the JS:
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
In your index.php, you can then access the form values in the $_POST array, e.g. $_POST['contact_name'].
I am grabbing the values of several input fields with the help of an Ajax/JS function. The issue is that the values of the textbox are not being echoed. I checked with the firebug tool and it shows that the post is performed but there is a blank value. Why is the PHP not echoing the value when the JS function submits it?
EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
HTML
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
</form>
You need to use .serialize() on the form probably
Friend first understand the Javascript behaviour.
When you post a form, it becomes one request to the server. At the same time when you send an ajax to server it becomes another separate request to the server
So you should either do form post or ajax.
As you are using ajax here you, in the ajax request you have to pass data separately in data parameter
<script type="text/javascript">
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
data: $('#contact_form').serialize(), // check this line
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>