kendo ui grid edit button not working after loading persisting state - php

I am using Teleric kendo UI grid. I am using a database table to store grid options to save (persist) the grid state (column ordering, no of column default viewable etc) . It save option for every user, when the user login agin the state will automatically loded using an ajax call. Everything work fine
But the problem is that Edit button not working after loading saved state.
Please help.
thanks in advance
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<?php echo $this->session->flashdata('message');?>
<div class="panel panel-default">
<div class="panel-heading clearfix">
<div class="panel-body">
<?php
$transport = new \Kendo\Data\DataSourceTransport();
$read = new \Kendo\Data\DataSourceTransportRead();
$read->url(site_url('task/jsonMData'))
->contentType('application/json')
->type('POST');
$transport->read($read)
->parameterMap('function(data) {
return kendo.stringify(data);
}');
$model = new \Kendo\Data\DataSourceSchemaModel();
$id = new \Kendo\Data\DataSourceSchemaModelField('id');
$id->type('number');
$Name = new \Kendo\Data\DataSourceSchemaModelField('name');
$Name->type('string');
$Address = new \Kendo\Data\DataSourceSchemaModelField('address');
$Address->type('string');
$model->addField($id)
->addField($Name)
->addField($Address);
$schema = new \Kendo\Data\DataSourceSchema();
$schema->data('data')
->model($model)
->total('total');
$dataSource = new \Kendo\Data\DataSource();
$dataSource->transport($transport)
->pageSize(500)
->schema($schema)
->serverFiltering(true)
->serverSorting(true)
->serverGrouping(false)
->serverPaging(true);
$grid = new \Kendo\UI\Grid('grid');
$idField = new \Kendo\UI\GridColumn();
$idField->field('id')
->locked(false)
->width(60)
->hidden(true)
->title('ID');
$nameField = new \Kendo\UI\GridColumn();
$nameField->field('name')
->width(100)
->locked(false)
->hidden(true)
->title('Name');
$addressField = new \Kendo\UI\GridColumn();
$addressField->field('address')
->width(200)
->locked(false)
->hidden(true)
->title('Address');
$command = new \Kendo\UI\GridColumnCommandItem();
$command->click('commandClick')
->text('Edit');
$commandColumn = new \Kendo\UI\GridColumn();
$commandColumn->addCommandItem($command)
->title('Edit')
->width(125);
$excel = new \Kendo\UI\GridExcel();
$excel->fileName(' Task Export.xlsx')
->filterable(true)
->proxyURL('task/saveToExcel');
$grid->addColumn($id,
$name, $commandColumn)
->height(500)
->scrollable(true)
->editable('popup')
->dataSource($dataSource)
->resizable(true)
->reorderable(true)
->sortable(true)
->filterable(true)
->columnMenu(true)
->pageable(true)
->addToolbarItem(new \Kendo\UI\GridToolbarItem('excel'))
->excel($excel);
$grid->columnHide('function(e) { saveGridState(); }');
$grid->columnShow('function(e) { saveGridState(); }');
echo $grid->render();
?>
</div></div></div>
<div style="display:none;">
Click
<input type="hidden" name="rowIndex" id="rowIndex" value="-1" />
<input type="hidden" name="taskId" id="taskId" value="0" />
</div>
<!--to support excel import -->
<script>
function commandClick(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
console.log(dataItem);
var grid = $(e.currentTarget).closest("tr");
var row = grid.select();
var rowIndex = row.index();
var j = $('#hidden-link');
if(j)
{
$('#rowIndex').val(rowIndex);
$('#taskId').val(dataItem.id);
j.attr('href','<?php echo base_url()."task/edit";?>/'+dataItem.id)
j.click();
}
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$(".fancybox").fancybox({
'afterClose':function () {
var rowIdx = $('#rowIndex').val();
var taskId = $('#taskId').val();
if(taskId != 0 && rowIdx >= 0)
{
userData = 'id='+taskId;
$.ajax({
url: "<?php echo site_url('task/getTaskById');?>",
type: "post",
data: userData,
dataType: "json",
success: function(data){
var firstRowItem = $('#grid').data().kendoGrid.dataSource.data()[rowIdx];
firstRowItem.set('Name',data.name);
firstRowItem.set('Plant',data.address);
},
async:false,
error:function(){
alert('There is error while submit');
}
});
}
},
});
var grid = $("#grid").data("kendoGrid");
userData = "type='m'";
$.ajax({
url: "<?php echo site_url('task/getGridSavedState');?>",
type: "post",
data:{type:'m'},
// contentType:'application/json',
dataType: "json",
success: function(data){
if(data.columns)
{
options=data;
grid.setOptions(options);
}
},
error:function(){
console.log("Error loding save grid state");
}
});
});
function saveGridState()
{
var grid = $("#grid").data("kendoGrid");
gridOptions=grid.getOptions();
var request=kendo.stringify({gridOptions : gridOptions,type:'m'});
$.ajax({
url: "<?php echo site_url('task/saveGridState');?>",
type: "post",
contentType:'application/json',
data: request,
dataType: "json",
success: function(data){
console.log("stated saved");
},
error:function(){
console.log("Error in stated saved")
}
});
}
</script>

From the API docs
Notice that when the options object is retrieved and then serialized into a string through JSON.stringify(options), then each field that is a function will be lost. This is limitation of the serialization that the JSON.stringify does. You need to either explicitly set the fields that were functions after parsing the object back or you need to use some custom implementation for serialization to handle the serialization of the JavaScript functions.
So you need to bind the command button to the function again: at least I think that is what they mean. So try adding a basic jQuery ('selector').on('click') function after the setOptions.

var grid = $("#grid").data("kendoGrid");
userData = "type='m'";
$.ajax({
url: "<?php echo site_url('task/getGridSavedState');?>",
type: "post",
data:{type:'m'},
dataType: "json",
success: function(data){
if(data.columns)
{
options=data;
if(options.editable)
{
//popout last column i.e command column
edit= options.columns.pop()
//add new command column explicitly.
commandCol={"command":[{"text":"Edit","click":commandClick}],"title":"Edit","width":125};
options.columns.push(commandCol);
grid.setOptions(options);
}
}
},
error:function(){
console.log("Error loding save grid state");
}
});

Related

Passing Variable Value from PHP to Ajax and Changing Attribute Value in HTML

My PHP is returning this data to Ajax...
echo $data6['favorite_properties_id'];
I am updating it in one function and trying to send it to another using following html and jquery .
<img class="<?php if($favorite == 1){ echo 'alreadyfavorite';} else { echo 'addtofavorite';} ?>" pid="<?php echo $propertyid; ?>" fpid="<?php while($data5=$select5->fetch()){echo $data5['favorite_properties_id'];} ?>" src="../images/system/addtofavorite.png">
This is my jquery...
$('.alreadyfavorite1').click(function() {
event.preventDefault();
var del_id = $(this).attr('fpid');
var $ele = $(this).parent().parent().parent();
var reference = this;
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
del_id: del_id
},
success: function(data)
{
$ele.fadeOut(1000).delay(1000).remove(1000);
}
});
});
// On Search Property Results Page - Add to Favorite Button (Heart)
$('.addtofavorite').click(function() {
event.preventDefault();
var ins_id = $(this).attr('pid');
var del_id = $(this).attr('fpid');
var reference = this;
/* alert(del_id);
alert(ins_id); */
$.ajax(
{
type: 'POST',
url: '../controllers/favoritesaddremove.php',
data:
{
ins_id: ins_id
},
success: function(data)
{
$(reference).toggleClass("addtofavorite alreadyfavorite");
$('.alreadyfavorite').attr('fpid', data);
}
});
});
The second function is not working, but if i refresh the page then the second function is working...
First assign some id to the image and change fpid to data-fpid(data-attribute):
<img class="asdasd" id="aid" data-fpid="something">
In your success try:
success: function(data)
{
$('#aid').data('fpid', data); //this should update the value in data-fpid
}

PHP - how to retrieve value of input type file on Ajax / JQuery page

I can retrieve input type text, textarea, select on Ajax / JQuery page. Then variable values are passed to PHP process page where data are retrieve using POST method and data inserted into database table. All things are working fine.
But when I try to retrieve value of input type file variable on Ajax / Query page, it is giving blank value. I tried different codes to do it which I found from internet.
Please advise so I can make necessary changes in my script to make it working.
personal_details.php
<form name="AddForm" id="AddForm" novalidate>
<div class="control-group form-group">
.
.
<input type="file" name="file_photo" id="file_photo">
.
.
other fields like Name, Mail etc
.
.
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary">Send Message</button>
</div>
</form>
personal_details.js
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
.
.
var file_photo = $("file#file_photo").val();
//var file_photo = $('#file_photo')[0].files[0];
//var file_photo = document.getElementById("file_photo").files[0];
$.ajax({
url: "./user/personal_details_p.php",
type: "POST",
data: {
name: name,
email: email,
file_photo: file_photo,
},
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
personal_details_p.php
$str_name = "";
if (isset($_POST["name"])) { $str_name = trim($_POST["name"]); }
$str_email = "";
if (isset($_POST["email"])) { $str_email = trim($_POST["email"]); }
$str_photo = "";
if(isset($_FILES['file_photo'])) { $str_photo = trim($_FILES['file_photo']['name']); }
.
.
SQL Query to insert data
.
.
$response['status']='SUC';
$response['message']="Data inserted successfully";
echo json_encode($response);
return;
Easy Ajax Image Upload with jQuery, PHP
All textbox, textarea and file type variables will be available on PHP process page with the same name like they have on HTML form page.
I have made my own function for asynchronous upload with progress bar. I will try to write example for you. Also add enctype="multipart/form-data" attribute to your form.
var file_photo = $("file#file_photo").val();
var form = file_photo.parents('form');
file_photo.on('change', processUpload);
var processUpload = function() {
var formData = new FormData(form[0]);
$.ajax({
url: "./user/personal_details_p.php",
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload) {
myXhr.upload.addEventListener('progress', progressHandling, false);
}
return myXhr;
},
success: function(json) {
file_photo.val(''); // Empty file input after upload
},
error: function() {
// Do whatever you want as error message
},
data: formData,
cache: false,
contentType: false,
processData: false
});
};
var progressHandling = function(e) {
if(e.lengthComputable) {
// Uploaded bytes: e.loaded / Maximum bytes: e.total
}
};
you can use https://github.com/blueimp/jQuery-File-Upload. It has various options and its documentation is also good. so if you can use plugin you can go with this
Please Try below code for file upload.
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
// my edit for File upload code starts here
var FileData = $('#file_photo').prop('files')[0];
var form_data = new FormData();
form_data.append('file', FileData);
// my edit for File upload code ends here
$.ajax({
url: "./user/personal_details_p.php",
type: "POST",
data: {
name: name,
email: email,
file_photo: file_photo,
},
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});
For accessing file you should have to do like this in jquery:
$(function() {
$("#AddForm input,#AddForm textarea, #AddForm file").jqBootstrapValidation({
preventSubmit: true,
submitSuccess: function($form, event) {
event.preventDefault();
var name = $("input#name").val();
var email = $("input#email").val();
var file_data = $("#file_photo").prop("files")[0];
var form_data = new FormData();
form_data.append("doc_upload", file_data)
var data_text=$('form').serializeArray();
$.each(data_text,function(key,input){
form_data.append(input.name,input.value);
});
$.ajax({
url: "./user/personal_details_p.php",
contentType: false,
processData: false,
data: form_data,
cache: false,
success: function(data)
{
//alert(data);
var $ResponseText_L=JSON.parse(data);
.
.
if condition
.
.
},
})
},
});

fullcalendar (jquery + json + php) - save div color attribute to mysql

So I managed to follow one of the tutorials for the fullcalendar script to hook up the jquery based calendar to my MySQL database, allowing me to write and read calendar events into the database.
The variables handed over from jquery to mysql are things such as the unique event ID, start date, end date, title, etc. but sadly, not the tab color of the event. Since I am using draggable "external events", which basically are draggable buttons that you can drag n drop onto the calendar (which naturally all have different colors), I am now having the problem that I cannot make fullcalendar extract the color of the div and then pass it over via PHP into my MySQL database.
So here is the question:
How can I adjust the jquery script to extract the var color = event.backgroundColor; variable and add it on to my php script?
I have no clue about jquery nor javascript, hence would really appreciate help. I also tried to throw a few bucks towards a freelance programmer but even he ultimately gave up.
Here the code I have so far:
Fullcalendar script in calendar.php
<script>
$(document).ready(function() {
var zone = "08:00"; //Change this to your timezone
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
json_events = s;
}
});
var currentMousePos = {
x: -1,
y: -1
};
jQuery(document).on("mousemove", function (event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events .external-event').each(function() {
// store data so the calendar knows to render an event upon drop
$(this).data('event', {
title: $.trim($(this).html()), // use the element's text as the event title
//color: $.trim($(this).backgroundColor()), // use the element's bgcolor as the events background
stick: true // maintain when user navigates (see docs on the renderEvent method)
});
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
eventReceive: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
var color = event.backgroundColor;
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
$('#calendar').fullCalendar('updateEvent',event);
console.log(event);
},
eventDrop: function(event, delta, revertFunc) {
var title = event.title;
var start = event.start.format();
var end = (event.end == null) ? start : event.end.format();
var color = event.backgroundColor;
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventClick: function(event, jsEvent, view) {
console.log(event.id);
var title = prompt('Event Title:', event.title, { buttons: { Ok: true, Cancel: false} });
if (title){
event.title = title;
console.log('type=changetitle&title='+title+'&eventid='+event.id);
$.ajax({
url: 'process.php',
data: 'type=changetitle&title='+title+'&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status == 'success')
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
},
eventResize: function(event, delta, revertFunc) {
console.log(event);
var title = event.title;
var end = event.end.format();
var start = event.start.format();
var color = event.backgroundColor;
$.ajax({
url: 'process.php',
data: 'type=resetdate&title='+title+'&start='+start+'&end='+end+'&eventid='+event.id+'&color='+color,
type: 'POST',
dataType: 'json',
success: function(response){
if(response.status != 'success')
revertFunc();
},
error: function(e){
revertFunc();
alert('Error processing your request: '+e.responseText);
}
});
},
eventDragStop: function (event, jsEvent, ui, view) {
if (isElemOverDiv()) {
var con = confirm('Are you sure to delete this event permanently?');
if(con == true) {
$.ajax({
url: 'process.php',
data: 'type=remove&eventid='+event.id,
type: 'POST',
dataType: 'json',
success: function(response){
console.log(response);
if(response.status == 'success'){
$('#calendar').fullCalendar('removeEvents');
getFreshEvents();
}
},
error: function(e){
alert('Error processing your request: '+e.responseText);
}
});
}
}
}
});
function getFreshEvents(){
$.ajax({
url: 'process.php',
type: 'POST', // Send post data
data: 'type=fetch',
async: false,
success: function(s){
freshevents = s;
}
});
$('#calendar').fullCalendar('addEventSource', JSON.parse(freshevents));
}
function isElemOverDiv() {
var trashEl = jQuery('#trash');
var ofs = trashEl.offset();
var x1 = ofs.left;
var x2 = ofs.left + trashEl.outerWidth(true);
var y1 = ofs.top;
var y2 = ofs.top + trashEl.outerHeight(true);
if (currentMousePos.x >= x1 && currentMousePos.x <= x2 &&
currentMousePos.y >= y1 && currentMousePos.y <= y2) {
return true;
}
return false;
}
});
</script>
calendar.php - > external events aka the draggable event buttons
<div class="box box-solid">
<div class="box-header with-border">
<h4 class="box-title">Draggable Audits</h4>
</div>
<div class="box-body">
<!-- the events -->
<div id="external-events">
<div class="external-event bg-aqua">FO Check-In</div>
<div class="external-event bg-blue">FO Check-Out</div>
<div class="external-event bg-light-blue">HSKP Room</div>
<div class="external-event bg-teal">Fitness Centre</div>
<div class="external-event bg-yellow">Reservation</div>
<div class="external-event bg-orange">F+B Breakfast</div>
<div class="external-event bg-green">F+B A La Carte</div>
<div class="external-event bg-lime">F+B Chinese</div>
<div class="external-event bg-red">F+B Chinese PDR</div>
<div class="external-event bg-purple">FO Club IC</div>
<div class="external-event bg-fuchsia">F+B Lobby Lounge</div>
<div class="external-event bg-muted">Ballroom Event</div>
<div class="external-event bg-navy">SEC Fire Drill</div>
<div class="checkbox">
<label for="drop-remove">
<input type="checkbox" id="drop-remove">
remove after drop
</label>
</div>
<button id="trash" type="button" class="btn btn-primary btn-danger btn-lg">DRAG HERE TO DELETE</button>
</div>
</div>
<!-- /.box-body -->
</div>
process.php script that handles the reading and writing into the MySQL table
(Note: fetching the color field works fine, but I have no way of writing the color data into the table since I cant extract the event.backgroundcolor() variable from jquery)
<?php
session_start();
include '../plugins/MySQL/connect_db.php';
$con = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$type = $_POST['type'];
$holidex = $_SESSION['Holidex'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$color = $_POST['color'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`, `color`, `holidex`) VALUES('$title','$startdate','$startdate','true','$color','$holidex')");
$lastid = mysqli_insert_id($con);
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid' and holidex='$holidex'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate', holidex = '$holidex' where id='$eventid' and holidex='$holidex'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid' and holidex='$holidex'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT * FROM calendar where holidex='$holidex'");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
$e['color'] = $fetch['color'];
array_push($events, $e);
}
echo json_encode($events);
}
?>

Appending jQuery AJAX response to an existing DIV

This the HTML code that displays the first two comments in my site. I want if a user clicks on the Load more comments button, it should load the fetched comments that is returned via the jQuery AJAX and append it to the two divs in .comment_data div but it is not working even though the AJAX seems to be returning the expected result.
This is the HTML code:
<div class = 'feeds'>
<div class = 'comments'>
<div class = 'comment_data>
<div class = 'per_comment'>
<p> slideToggle!</p>
</div>
<div class = 'per_comment'>
<p> classToggle!</p>
</div>
<button class='morecomments' value='7' name = 'more' type='submit'>
Load more comments</button>
</div>
</div>
</div>
And this is the AJAX code:
$(".morecomments").click(function () {
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id },
dataType: "html"
});
request.done(function( msg ) {
$(this).prev('.per_comment').html( msg );
});
});
And the comments.php code:
if(isset($_POST['post']) )
{
$post_id = $_POST['post'];
$qry = "SELECT user_id, comment FROM comments WHERE post_id = ? ORDER BY time DESC LIMIT 1, 1000";
$q = $conn->prepare($qry) or die("ERROR: " . implode(":", $conn->errorInfo()));
$q->bindParam(1, $post_id);
$q->execute();
if($commentz = $q->fetchAll()){
foreach ($commentz as $comment){
echo "<div class = 'per_comment'>";
echo "<p>". $comment[0] ." ". $comment[1] . "</p>";
echo "</div>";
}
}
}
Try the following:
$(".morecomments").click(function () {
var $this = $(this);
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: { post : post_id },
dataType: "html"
});
request.done(function( msg ) {
$this.prev('.per_comment').html( msg );
});
});
this isn't what you think it is. Try setting the context property of the ajax options:
$(".morecomments").click(function () {
var post_id = $(this).val();
var request = $.ajax({
url: "comments.php",
type: "POST",
data: {
post: post_id
},
dataType: "html",
context: this
});
request.done(function (msg) {
$(this).prev('.per_comment').html(msg);
});
});

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

Categories