speed up select2 using ajax with php - javascript

I am trying to speed up my select2 results as i have over six-thousand customers in the database. I have the input box filled with data from a mysql database and dont know what more I can try at this stage to be honest. here is my select2 javascript (Js just isnt my thing)
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<script type="text/javascript">
$(function(){
// turn the element to select2 select style
$(".js-data-example-ajax").select2(
{
ajax: {
url: "/delete.php",
dataType: 'json',
data : function(term){
return{
term: term
};
},
results: function(data){
var results = <?php echo json_encode($jsData) ?>;
$.each(data, function(index, item){
results.push({
id: item.id,
text: item.fullName
})
})
}
}
});//end select2
});//end function
in php I use a foreach loop to read the data. It works perfect without the ajax just can be very slow select a result and there will be more customers added every day. I try to send back the id and the customers full name.
<?php
$sqlSearch="SELECT first_name, last_name, id, mobile, landline FROM customer order by first_name";
echo "<select id='tbCustId' class='js-data-example-ajax' style='width: 150px' size='2' name='tbCustId' required></option>";
// echo "<select>";
$jsData = [];
foreach ($db->query($sqlSearch) as $row){
$id = $row["Id"];
$fName = $row["first_name"];
$sName = $row["last_name"];
$fullName = $fName ." ". $sName;
$jsData[] = [
"id" => $id;
"fullName" => $fullName;
];
echo "<option value=$row[id]>
$fullName
</option>";
}
echo "</select><br/>";// Closing of list box
?>

As there are too many records it taking too much time , to avoid suggestion is
Make use of Pagination or
Make use of parallel execution by firing multiple ajax request i.e. request one fetch 1 to 3000 data and parallel request fetch 3001 to 6000 data..
Example Code : might having syntax error
ajax: {
url: "/delete.php",
dataType: 'json',
data : function(term){
return{
term: term
//record no : 1 added parameter for paging
//record no : 3000
};
},
results: PushData
}
ajax: {
url: "/delete.php",
dataType: 'json',
data : function(term){
return{
term: term
//record no : 3001 added parameter for paging
//record no : 6000
};
},
results: PushData
}
function PushData(data){
var results = <?php echo json_encode($jsData) ?>;
$.each(data, function(index, item){
results.push({
id: item.id,
text: item.fullName
})
})
}

Related

PHP & JavaScript - Variables

I just basically have a View with an Associative Array with Accidents Information.
The User will be able to click in the Country. When that happen I want to show them the information about accidents related with that country.
That information comes from PHP and the Click event is captured in JQuery...
How Can I insert the var country inside the index of the
associative array that came from PHP with an Index for each country?
.on('click', function(i, row) {
var country = row.label;
accident_chart.setData([{
a: <?php echo "".$charts['accidents_status'][**NEED var country value here**]['accidents']; ?>,
y: 'Accidents',
},
{
a: <?php echo $charts['accidents_status']['Qatar']['lost_time_accidents']; ?>,
y: 'Lost Time',
}
]);
});
You can't do that. Use AJAX instead to get the accident_chart data.
.on('click', function(i, row) {
var country = row.label;
$.ajax({
type: "GET",
url: "/get_accident_chart", // Just replace it with your PHP controller function that can access your $charts variable
data: {country: row.label},
dataType: "json",
success: function(data) {
accident_chart.setData(data);
},
error: function(data) {
return data;
}
});
});
In your PHP
get_accident_chart(){
$country = $_GET['country'];
$accident_chart = array(
array(
'a' => $charts['accidents_status'][$country]['accidents'],
'y' => 'Accidents'
),
array(
'a' => $charts['accidents_status']['Qatar']['lost_time_accidents'],
'y' => 'Lost Time'
)
);
echo json_encode($accident_chart);
}

Inline CKEditor save to MySQL using AJAX/PHP

I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

How to pass the value of php to javascript using ajax

i have an array , which has to be passed from backend to frontend using ajax, i am new to ajax i know the syntax but got stuck , below is my code
backend(PHP)
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$s_res = mysql_query($s_q, $db2);
while($row= mysql_fetch_array($s_res))
{
echo $row['ans'];
}
$result = array('ans' => $row['ans'] );
Javascript code
function get_solution()
{
$.ajax({
url: 'waiting.php',
dataType: 'json',
type: 'GET',
timeout: 30 * 1000,
data: {sol:row},
success: function(json){
$('#saved').html(json.ans);
},
error: function(){}
});
}
i am getting an error in this code data: {sol:row}.
The response data from php is not in json format..
$result = array('ans' => $row['ans'] );
echo json_encode($result);
add this in your php code
Create a JSON on the PHP Side and catch it with $.getJSON jquery
Server Side:
$row_1 = array();
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$result = mysql_query($s_q) or die (mysql_error());
while($r = mysql_fetch_assoc($result)) {
$row_1[] = $r;
}
$post_data = json_encode(array('ans' => $row_1));
echo $post_data;
Client Side:
$.getJSON("result.php", function(json) {
console.log(json)
$.each( json, function( key, data ) {
//loop through the json if necessary
});
});

AJAX update MYSQL database using function called from HTML generated from PHP

I have a php page generating and displaying a table. for the last row in the table i want to display an image with an 'onclick' function attached. this will send the username for the selected row to a script that will use AJAX to update a database. The table displays fine but the AJAX is not working. my php to display the image is:
echo "<td> <img id='tblimg'
onclick='like('" . $row['Username'] . "')'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
<script type="text/javascript" >
function like(user)
{
$.ajax(
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
);
}
</script>
And here is update.php:
<?php
$con=mysqli_connect("","sam74","********","sam74");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Username = $_POST['username'];
$Liked = $_POST['liked'];
$sql = "UPDATE 'followers' SET 'Liked' = '$Liked' WHERE 'Username' = '$Username'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
There are some mistakes in this code, let me help you line by line.
echo "<td> <img id='tblimg'
onclick=\'like('" . $row['Username'] . "');\'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
Escape your quotes for the onclick event first
function like(user)
{
$.ajax({
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
});
}
add { and } to the ajax call
Remove the quotes from table name and fields
$sql = "UPDATE followers SET Liked = '$Liked' WHERE Username = '$Username'";
in ajax success and after the function begins, you can always print a message to see if your function is being called, and if php script is returning some error, use an alert for that
UPDATE
success: function(data){
alert(data); // this will print you any php / mysql error as an alert
}
UPDATE 2
Write your onclick option like this.
echo "<img onclick=\"like('" . $row['Username']. "');\"
src='like.jpg' alt='like/dislike image'
width='80px' height='30px' />";
The jQuery.ajax() function expects an object to be passed; you need to use { and } to begin and end your object literal. What you currently have is invalid JavaScript syntax, if you checked your browser's developer tools you'd see an error indicating that. So:
$.ajax(
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
);
should be
$.ajax({ // added {
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
}); // added }

Categories

Resources