Managing strings with ajax post request and jquery - php

I am working on a check box based filter operation for a website.This has multiple checkboxes which filter a list of records on different parameters.Similar to what is done here.Now I have managed to achieve some success,and I have filtered the records based on first set of checkboxes.Here is the js function for it.
HTML:
<input type="checkbox" id="checkbox1" class="checkbox1" value="<?php echo $suburb['suburb_name']?>" name="Suburb_check[]" onClick="changeResults();" onChange="" >
Javascript:
function changeResults(){
var data = { 'venue[]' : []};
$("input[name=Suburb_check[]]:checked").each(function() { var chck1 = $(this).val();
data['venue[]'].push($(this).val());
dataString =data['venue[]'.toString()].toString();
});
$.ajax({
type : 'POST',
url : 'process.php',
data : "dataString="+dataString,
success : function(data){
$('#project_section').html(data);
}
});
}
What this does is filters the records + loads the second set of check boxes.1st set check box)=>for Regions and 2nd is =>for Localities
I have created an array to pass the check box values and then converted it to a string(.toString) and passed to the .php file.
Similarly I created a function for 2nd set of checkboxes.
HTML
<input type="checkbox" onClick="changeLocality();" id="localityCheck" value="<?php echo $locality['locality_name'];?>" name="Locality_check[]">
JS
function changeLocality(){
var dataLocality = {'locality[]' : []};
$("input[name=Locality_check[]]:checked").each(function() {
var chcklocal = $(this).val();
dataLocality['locality[]'].push($(this).val());
localityString =dataLocality['locality[]'.toString()].toString();
});
$.ajax({
type : 'POST',
url : 'processLocality.php',
data : "localityString="+localityString,
success : function(dataLocality){
$('#project_section').html(dataLocality); // replace the contents coming from php file
}
});
}
Pass the values to a php file but when I try to get them using $_POST,the strings I get mixed into each other i.e the region values go into locality string and vice-versa(Tried this using array with same result so switched to strings).
I am not able to fix this.Why is this happening
This are the php files i post values to.
processLocality.php
<?php session_start();
include_once("includes/classes/db_connect.php");
include_once("pagination/paginator.class.php");
$pages = new Paginator();
$regions = "'".$_POST['dataString']."'";
echo $regions;
$arr = explode(",",$regions);
$getFormatedSuburb = implode("','",$arr);
$locality = "'".$_POST['localityString']."'";
echo $locality;
$arrLocal = explode(",",$locality);
$getFormatedLocality = implode("','",$arrLocal);
//Here I get the strings mixed with each other!!
?>
I have added some expression to the string for passing it to the IN clause of SQL query in the needed format.
Now the strings I get contains values from both regions and localities.I want both separately as they are two different parameters for filtering records
Pune East,
Pune West, //1 and 2 are regions
Aundh,
Kalyaninagar //3 and 4 are localities
Also,I would like to know is my approach correct.Any better way of achieving this?
Any help appreciated.
Thanks

Try changing your selectors. Instead of this:
$("input[name=Suburb_check[]]:checked")
....
$("input[name=Locality_check[]]:checked")
Do this:
$("input[name=Suburb_check]:checked")
....
$("input[name=Locality_check]:checked")
Also the markup has to be in the form:
<input type="checkbox" name="Suburb_check">
With the same name for each checkbox group. The name can not contain "[]"

Related

PHP AJAX HTML: changing unique table data in foreach loop

I'm new to PHP and Ajax. I am trying to create a table of object data where I can select the displayed data based on a <select><option>... form.
I have a PHTML template which looks like the following:
<?php
$content = "";
// creates data selector
$content .= "
<form id = select_data>
<select id = data_selection>
<option value = data1>Data 1</option>
<option value = data2>Data 2</option>
<option value = data3>Data 3</option>
<option value = data4>Data 4</option>
</select>
<input id = selected_data type=submit />
</form>";
// creates table header
$content .= "
<tr>
<th>Data</th>
</tr>";
$array_ids = array(1, 2, 3); // etc, array of object id's
foreach ($array_ids as $array_id) {
$object = // instantiate object by array_id, pseudocode
$object_data = $object->getData('default-data'); // get default data to display
// create table item for each object
$content .= "
<tr>
<td><p>$object_data</p></td>
</tr>";
}
print $content;
?>
This prints out the table content, loads objects by their id, then gets and displays default data within the <p> tag.
And then I have some Javascript which looks like the following:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){ // get selected data type
e.preventDefault();
var data_selected = $("#data_selection :selected").val(); // create var to pass to ajax
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected},
success: function(data){
$("p").html(data); // replace all <p> tag content with data
}
});
});
});
</script>
This Javascript gets the selected data type, creates a variable out of it to pass on to the ajax which then calls post.php, which looks like the following:
<?php
$attribute = false;
if (isset($_POST['data_selected'])){
$data = $_POST['data_selected']; // assigns variable out of ajax data
$object = //instantiate object, again pseudocode
$object_data = $object->getData($data); // get new data to replace into the ```<p>``` tag
echo $object_data;
}
?>
The problem is that the Javascript that I have changes every single <p> tag to the last data iterated by the foreach loop because each <p> tag is not uniquely identified and the Ajax does not update the data based on a unique identifier, such as maybe the $array_id. Which brings me to my attempted solution.
I tried to identify each <p> tag with the following:
<td><p id = $array_id>$object_data</p></td>
And then creating a new Javascript variable out of the array ID:
var p_tag_id = <?php echo $array_id; ?>;
And finally making the Ajax success function target element ID's based on var p_tag_id:
$("#" + p_tag_id).html(data);
While this does not change all the <p> tags like previously, it only changes the final <p> tag and leaves all instances before it unchanged because the Javascript is not iterating over each <p> tag, or because the foreach loop does not call the Javascript as a function for each $array_id.
How can I rewrite this code so that the Ajax updates the data of each table item uniquely instead of updating them all with the same data? Is there a better way to approach this problem?
You need a way to identify the table row containing the <p> tag you wish to update, and perhaps the value attribute of the SELECT element could help.
You can get the number of the clicked option from your data_selected variable by using slice to strip-off the last character (i.e. the number):
var num = data_selected.slice(-1) - 1;
(Subtract 1 because the table rows are zero-indexed)
Then, in the AJAX code block's success function:
$('table tr').each(function(i,v){
if (i == num){
$(v).find('td').find('p').html(data);
}
});
The above grabs all the table rows (as a collection) and loops through them one-by-one. In the function, i is the index number of the row and v is the row itself. Index numbers begin at zero, which is why you earlier subtracted 1 from the (for eg) data3 [3] value, leaving num == 2. When you find the right row number, use .find() to find the <td> in that row, and then the <p> in that <td> and Bob's yer uncle.
I haven't tested the above code so there could be bugs in the example, but off-the-cuff this approach should work.
I figured out a solution. I assigned the $array_id to each <p> tag after all in order to identify them uniquely:
<td><p id = $array_id>$object_data</p></td>
Then I looped over all the <p> tags and assigned the $array_id of this <p> tag to a variable like so:
$("p").each(function() {
var array_id = $(this).attr("id");
And finally I made the Ajax success target elements based on their ID:
$("#" + array_id ).html(data);
Here is the full Javascript code for anybody who is interested. Hopefully this helps someone else out!
<script>
$(document).ready(function(){
$('#select_data').on('submit', function(e){
e.preventDefault();
var data_selected = $("#data_selection :selected").val();
$("p").each(function() {
var array_id = $(this).attr("id");
$.ajax({
type: "POST",
url: 'post.php',
data: {data_selected: data_selected, array_id: array_id},
success: function(data){
$("#" + array_id).html(data);
}
});
});
});
});
</script>

Autocomplete in the text box in PHP, Ajax and MySQL

Using Autocomplete text box to retrieve the data from the MySQL database table. my Ajax coding is working to retrieve the small amount of data. In my database table, I have more 300,000 records. The coding is not working when I used large data.
Please give suggestion about to retrieve a large data.
Which method is best to retrieve the data.
See my coding. It works fine to retrieve a small amount of data
<input type="text" name="protein_name" id="protein_name">
$("#protein_name").keypress(function (e){
var protein_name = $("#protein_name").val();
if(protein_name != "") {
$.ajax({
url: '<?php echo base_url(); ?>/index.php/Protein_Main/protien_search',
data: {protein_name: protein_name},
dataType: "json",
type: "POST",
success: function (res) {
$("#protein_name").autocomplete({
source: res
});
}
});
} });
PHP Coding
$query = $this->db->query("SELECT `Name_of_the_Protein` FROM `protein` WHERE Name_of_the_Protein Like '".$protein_name."%'");
$protein = $query->result();
echo json_encode($protein);
Autocomplete requires a few things.
An input element
<input type="text" id="nmRecipientSearch">
A couple of local javascript arrays:
(One containing a list of potential selections, and another with numeric unique ids corresponding to each selection)
var aryRecipientsFull=["Aaron","Adon","Andrew"];
var aryLrId=["1","2","3"];
A javascript .autocomplete handler bound to the input element:
$( "#nm_recipient_search" ).autocomplete({ source: aryRecipientsFull,
select: function( event, ui )
{
var numPosition,numLrId = 0;
//Find the index position within the array for the selected item (e.g. Adon)
numPosition=aryRecipientsFull.indexOf(ui.item.label);
//Set a variable to the numeric value corresponding to the selected item (e.g. 2)
numLrId=aryLrId[numPosition];
//Populate a hidden input field (nm_lr_id) to the numeric value
$('#nm_lr_id').val(numLrId);
//Set the focus to the next field once a selection has been made
$('#nm_text').focus();
}
});
A CSS style to ensure the autocomplete results appear above everything else:
ul.ui-autocomplete
{
z-index: 1100;
}
A couple of things to consider:
I'd recommend starting off using static arrays just to ensure that the UI looks okay
If you need to (re)populate the arrays dynamically then you may need to bind a .keyup event to the search field, perform an AJAX call to a PHP page which then does a query as you've suggested, but make sure that you limit the number of resulting records (perhaps 10 or 20 records).
Simply add "LIMIT 20" to the end of your SELECT query to achieve this.
I hope that helps.

Converting the result of a jquery function into a variable I can use in PHP

With help from this forum I have completed a form which uses jQuery and the resulting JSON data. I would like to take it one stage forward.
I have written a user FORM which has a textbox, when the user starts to type in the name of a company the jquery function runs and performs a look up on the data table and returns any matches in json format.
The user can then select the required company name and this then gets inserted in to the the textbax. At the same time the name of the campany logo is inserts in to another textbox as a .png file.
My company name textbox and image name textbox:
<input name="ClientName[]" placeholder="Client name" class="imaindatesel" id="search-box_1" type="text" size="60" maxlength="40" />
<input name="CompanyImage[]" type="text" id="company_image_1" class="ui-autocomplete-input"/>
My jquery function:
$(document).ready(function() {
$('#search-box_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'check_name.php',
dataType: "json",
data: {
name_startsWith: request.term//,
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#company_image_1').val(names[1]); //<---- I would like to use this as a PHP variable
$("#SelectView").hide();
// The line below is all I added to get the result I needed.
$("#LookUpCompanyImage").html("<img src=\"../../../conf/conf_images/boards/" + names[1] + "\">");
}
});
})
My PHP script
$query = $db->query("SELECT RecordID, CompanyName, ImageName FROM conf_image_depository WHERE CompanyName LIKE '".$_GET['name_startsWith']."%' GROUP BY CompanyName ORDER BY CompanyName ASC");
$data = array();
while ($row = $query->fetch_assoc()) {
//$data[] = $row['CompanyName']. " " . $row['ImageName'];
$name = $row['CompanyName'].'|'.$row['ImageName'];
array_push($data, $name);
}
//return json data
echo json_encode($data);
The result of the ajax call:
["British Airways|British-Airways.png","British Assessment Bureau|british-assessment-bureau.png","British Gas|BritishGas.png","British Sugar|BritishSugar.png"]
At the moment I have a textbox which is populated by "$('#company_image_1').val(names[1]);".
What I need to do is use "$('#company_image_1').val(names[1]);" from the jquery function and convert it in to a PHP variable.
The reason is, after the user has selected a company returned by the jquery function,JSON contains the company name and the image name of ther company logo. I then want to do two things, display the image on screen and use the name of the image in a MySQL insert.
Again, many thanks for your time.
I would create another ajax call in the select function which posts the image name to php.
So you would need to create an ajax call something like this:
$.ajax({
url : 'save_name.php',
dataType: "POST", // Set the dataType to POST, so we can send data to php
data: {
name: names[1],
},
success: function( data ) {
console.log('successfully sent the name');
}
});
Then in the php file save_name.php you can catch the $_POST variable and retrieve the name value out of it. Something like this.
if(isset($_POST['name'])){
// Post name is set so we can use it.
$name = $_POST['name'];
}
And then of course you use sql to update your database with the name value.
I have worked out how to resolve my issue. All I needed to do was to add the following line of code:
$("#SelectView").hide();
$("#LookUpCompanyImage").html("");
I have edited my post to reflect the changes I made

Separating <td> in a <tr> using jquery when pulled from an onclick event

Before we start I am fairly new to jquery and do not know most of the functions and capability, so I do not know if there is an easy trick to do this that I am missing.
I am having an issue where I am using a search function to display a table of results using Jquery, ajax and PHP. Once the results table is displayed from the search, I have a clickable link on the final row of the table. This link should get the data from the row you clicked on and set it to a $_SESSION in PHP. I can get the correct data fine, I just cannot separate out each <td> field individually. I wish to do this by adding in a comma or a symbol that I could use to identify each separate field once in PHP. This is an issue as I wish to put it into an array to auto-fill some input on the next page that you get redirected too. Can anyone help or point me in the right direction for this.
Jquery + ajax
$('#resultviews').on("click",".buttonaslink",function(){
var tabler = $(this).closest("tr").text();
tabler = ('tabler=' + tabler);
alert(tabler);
$.ajax({
type: "POST",
url: "rowsession.php",
data: tabler,
cache: false,
success: function(html){
$('#resultviews').html(html).show();
}});
return false;
});
PHP how results are displayed in the table from first ajax POST
while ($row = mysqli_fetch_array($view)){
$id = $row['companyId'];
$company = $customers[$id];
$company = ucwords($company);
echo "<tr><td class='tabled'>". $row['ip']."</td><td class='table'>". $row['Subnet']."</td><td class='table'>".$row['hostName']."</td><td class='table'>". $row['owner']."</td><td class='table'>". $company ."</td><td class='table'>".$row['siteName']."</td><td class='table'><button id='rowbtn' class='buttonaslink'>Edit</button> / <button id='rowdel' class='btnaslink'>del</button><tr>";
}
You can try this approach:
var tabler = $(this).closest("tr").find("td")
.map(function() {
return $(this).text();
})
.get()
.join(",");
It takes a value from every td element of the row and joins them with a comma. If you need to remove a trailing comma, you can use this code:
if(tabler.length) {
tabler = tabler.substring(0, tabler.length - 1);
}

Jquery UI Multi datepicker issue on retrieving dates

i am using this http://multidatespickr.sourceforge.net/#method-addDates to enable multiple date select. everything works fine but i am wondering how to get the selected dates to PHP.
below is the html code.
<input type="text" name="outgoing_call_dates" value="" id="outgoing_call_dates_id" class="hasDatepicker">
as you can see value tag is empty always when i add, its normally appending to the end but not value tag is doing the same. please check this image.
Original source : http://multidatespickr.sourceforge.net/#method-addDates (example : From input)
Please help me find a way
HTML
<input id="datePick" type="text"/>
<input id="get" type="button" value="Get" />
JS
$('#datePick').multiDatesPicker();
$('#get').on("click",function(){
var dates = $('#datePick').val();
if(dates !=''){
dataString = 'dates='+dates;
$.ajax({
type:"POST",
url : "URL_TO_PHP_FILE",
data : dataString,
dataType : 'json',
success : function(data) {
alert(data);
}
)};
}
});
PHP
$dates = ($_POST['dates']);
echo json_encode($dates);
value attribute defines default value. If you change the value of input element, it won't be inside source with value="YOUR_ENTERED_VALUE" .
To access value in client side, you can use JS or jQuery.
For example using jQuery:
var dates = $('#outgoing_call_dates_id').val();
In pure JS:
var dates = document.getElementById('outgoing_call_dates_id').value;
For PHP,
when you'll receive it on your action page.
On that page,
use this:
$dates = $_POST['outgoing_call_dates'];
or
$dates = $_GET['outgoing_call_dates'];
depending on the method you use.
Please have a look # this....!
Hope this will fix your issue :)
<no codes :|>
http://jsfiddle.net/3t4j9/23/

Categories