jQuery ajax keeps adding more and more elements - javascript

When a user searches for a username he gets results. When he backspaces or modifies the query, the results just keep getting added on top of the previous results instead of the results being modified and a fresh, updated result returned. I have modified the script here and there with no success yet.
My view:
<div class='container'>
<div class='row'>
<div class='col-sm-6 col-xs-12 col-centered'>
<div class='panel panel-default'>
<div class='panel-heading sticky'>
<div class='back pull-left'><a href='<?php echo site_url('chats') ?>'><span class='glyphicon glyphicon-chevron-left'></span></a></div>
<h1 class='panel-title text-center'>New Chat</h1>
<input class='form-control' id='search-field' type='text' placeholder='Username'>
</div>
<div class='panel-body'>
<ul class='users collapse'>
</ul>
</div>
</div>
</div><!--end column-->
</div><!--end row 1-->
</div><!--end container-->
My JS:
$(function() {
var $search_field = $('#search-field');
$search_field.on('keyup', searchByUsername);
$search_field.focus();
});
function searchByUsername(e) {
var username = this.value.trim();
var keyCode = e.keyCode;
var data = {username : username};
var $usersElement = $('.users');
var users = [];
// Use this condition to prevent searching when whitespace is entered
if (username) {
var request = $.ajax({
url : site_url + 'search/searchByUsername/',
method : 'GET',
data : data,
dataType : 'json'
});
request.done(function(jsonRepsonse) {
if (jsonRepsonse) {
var status = jsonRepsonse.status;
var usernames = jsonRepsonse.usernames;
if (status === 'success') {
$.each(usernames, function(index, value) {
// must be one line or will throw syntax error
users.push("<li class='user text-center'><a href='#'><span class='glyphicon glyphicon-user'></span><strong class='username'>" + value + "</strong></a></li>");
});console.log(users);
$usersElement
.append(users)
.show();
}
}
});
request.fail(function(xhr, status, error) {
console.log(error);
});
}
users.length = 0
$usersElement.hide();
}
My Codeigniter controller function:
public function searchByUsername()
{
$username = $this->input->get('username', true);
$usernames = [];
if (!empty($username)) {
$usernames = $this->find_users_model
->searchByUsername($username);
}
if (!empty($usernames)) {
$this->jsonResponse(
['status' => 'success',
'usernames' => $usernames]);
return;
}
$this->jsonResponse(
['status' => 'success',
'usernames' => ['User not found']]);
}
private function jsonResponse($response)
{
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response));
}
Result:

This is your users container:
var $usersElement = $('.users');
On ajax response, you do:
$usersElement.append(users).show();
But you're always appending, never removing. Try emptying the element before populating it with users again:
$usersElement.empty().append(users).show();

Related

Ajax For HTML Generated From Javascript

I have html being generated from Javascript to create a list of items. I also need to call a Jquery Ajax call on each of those items but since it isn't in the html from the page ready I think that might be why the Ajax isn't called. When I click the submit button it tries to refresh the page so this shows that the prevent default isn't being run.
EDIT: spelling
What am i doing wrong here?
Javascript that generates HTML:
buildCollectionList()
function buildCollectionList(){
var url = 'http://localhost:8000/api/collection_items_list/'
fetch(url)
.then((resp) => resp.json())
.then(function(data){
for (var x in data){
var wrapper = document.getElementById(`collection_scroll${data[x].post}`)
var product = wrapper.getAttribute('name')
//console.log(product)
wrapper.innerHTML = ''
/*fetch(url)
.then((resp) => resp.json())
.then(function(data){
console.log('Data:', data)*/
var list = data
for (var i in list){
if ((list[i].saved == true) && (list[i].post == product)){
var item = `
<div class="collection_save_container">
<div class="collection_save_name">${list[i].parent_collection_name}</div>
<form class="collection_save_form" action="" method="POST" id="${list[i].collection}" name="${list[i].post}">
<button type="submit" class="collection_save_btn saved" id="save_btn ${list[i].collection} ${list[i].post}"><div class="saved_text ${list[i].collection}">Saved</div></button>
</form>
</div>
</div>
`
wrapper.innerHTML += item
} else if (list[i].post == product){
var item = `
<div class="collection_save_container">
<div class="collection_save_name">${list[i].parent_collection_name}</div>
<form class="collection_save_form" action="" method="POST" id="${list[i].collection}" name="${list[i].post}">
<button type="submit" class="collection_save_btn" id="save_btn ${list[i].collection} ${list[i].post}"><div class="saved_text ${list[i].collection}">Save</div></button>
</form>
</div>
</div>
`
wrapper.innerHTML += item
}
}
//})
}
})
}
Jquery Ajax:
$(document).ready(function() {
$('.collection_save_form').submit(function(e){
e.preventDefault()
//const url = $(this).attr('action')
const url = "{% url 'savepost' 0 1000 %}"
const post_id = $(this).attr('name')
const collection_id = $(this).attr('id')
const text = $(`.saved_text ${collection_id}`).text()
var saveElement = document.getElementById(`save_btn ${collection_id} ${post_id}`);
real_url = url.replace('0', post_id).replace('1000', collection_id);
$.ajax({
type: 'POST',
url: real_url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_id': post_id,
'collection_id': collection_id,
},
success: function(response){
if (saveElement.classList.contains("saved")){
saveElement.classList.remove("saved")
$(`.saved_text${collection_id}`).text('Save')
} else if (!saveElement.classList.contains("saved")) {
saveElement.classList.add("saved")
$(`.saved_text${collection_id}`).text('Saved')
}
console.log(post_id)
},
error: function(response){
console.log('error', response)
}
})
})
});
for anyone with a similar problem: i solved this by putting an onclick event in the html that is generated by javascript

LARAVEL: how to send Email data from view to controller

I need to send email But Not getting email address in userController
from add.blade.php to userController#add.php
this is the code of add.blade.php file:
<div class="modal-content">
<div class="modal--blocks">
<div class="small--heading">
<form class="col s12">
<div class="input-field">
<div class="chips"></div>
</div>
<div class="input-field-btn">
<button class="btn waves-effect waves-light" type="button" id="send_email">Send Email</button>
</div>
</form>
</div>
</div>
</div>
and this is the scripte in add.blade.php file:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="css/materialize/js/materialize.min.js"></script>
$(document).on('click', '#send_email', function(){
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var instance = M.Chips.getInstance($('.chips'));
var email_address = instance.chipsData;
alert(instance);
alert(email_address);
// alert(email_address);
$.each(email_address, function(i, value){
if (!testEmail.test(value.tag)){
instance.deleteChip(i);
}
});
$("#send_email").text("processing..");
$("#send_email").prop('disabled', true);
var artist_id = "{{$artist->artist_id}}";
var request = $.ajax({
url: "{{url('/label/artist/weeklyreport/send')}}",
method: "POST",
data: { _token: $('meta[name="csrf-token"]').attr('content'), email:email_address, artist_uuid:artist_id}
});
request.done(function(resp) {
if (!resp.error) {
if (resp.result.status){
$("#modalEmailTemplates").modal('close');
$("#response_weekly_report").show();
}
}
});
});
userController.php file :
public function weeklyreportSend(Request $request) {
dd($request->email);die;
// $email = 'shiyalparesh25#gmail.';
$post = [];
$post['email'] = array_column($request->email, 'tag');
$post['subject'] = Config::get('constant.REPLAY_NAME') . "- Weekly Report";
$post['data'] = $this->get_weekly_report_data($request->artist_uuid);
$result = Helper::sendMail($post, "weekly_report");
return response()->json(['error' => false, 'result' => $result]);
}
Problem :- i'm not getting email value in Controller.if any have problem like me Please Help

Angular does not pick $scope.variable_name

Below is my HTML code.
<div class="container" ng-app="mintcart">
<div class="panel panel-default" ng-controller="categoriesctrl">
<input type="hidden" ng-model="session.sid" value="<?php echo session_id();?>"/>
<div class="panel-body">
<div class="row">
<ul class="nav nav-pills">
<?php
$i = 0;
while($i < count($list)){
$name = $list[$i]['categoryName'];
$id = $list[$i]['id'];
$normalUrl = $list[$i]['normalImageUrl'];
$hoverUrl = $list[$i]['hoverImageUrl'];
if($i == 0){
echo "<li role='presentation' class='active' ng-click='loadproducts($id)'><a href='#' >$name</a></li>";
} else {
echo "<li role='presentation' ng-click='loadproducts($id)'><a href='#''>$name</a></li>";
}
$i++;
}
?>
</ul>
</div>
</div>
</div>
</div>
ANd below is my JS code.
var app = angular.module('mintcart',[]);
app.controller('categoriesctrl', function($scope, $http){
var auth = {};
$http({
method: 'GET',
url: baseurl + 'api/get_product_categories'
}).then(function successCallback(response) {
$scope.categories = response.data.categories;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.loadproducts = function(item_id) {
alert($scope.session.sid);
$http({
method: 'GET',
url: baseurl + 'api/get_items_in_category_cart/' + item_id
}).then(function successCallback(response) {
$scope.items = response.data.products;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
//$scope.Language = lang;
};
});
When the loadproducts function is called the alert($scope.session.sid); gives me "undefined". I can't understand why my element is not being picked up.
Any help is greatly appreciated.
php works on the server side, you need to set the variable using a javascript not on the view.
Create a variable in JavaScript which gets the returned content of PHP.
var sessionid = <?php echo session_id();?>
then , you can access the variable in controller,
var app = angular.module("MyApp", []);
app.controller("categoriesctrl", function($scope) {
$scope.session.sid = sessionid ;
console.log($scope.session.sid);
});

database won't refresh when I search for a different query. -ajax

ok let me try to explain this as detail as I can.
I have these different inputs. It has passenger names, ticket numbers and rloc.
I am trying to search the passengers let's say by ticket number.
I have this search button to search into the database for the ticket number.
I got the ticket number and I am trying to find the next ticket number by clicking the next button. It works up to this point. (these are done by using ajax)
What is making me stuck is. If I didn't refresh the page, the database would stay to the database used when I click next.
sample if I input 111 searched the record, pull it out and I click next it'll go for record 112 then 113 with another click but without refreshing the page, I input 111 and search which still works but if I click next again it'll show the record of 114 instead of 112.
I thought it might be something about the .on() event for binding purpose but still not getting it right. Can someone give me an extra eyes please? Thank you.
Here is my html which is really basic
<div class="container">
<div class="title">
<h1>Ticket search</h1>
</div>
<div class="update-info">
<h3>{{$num}} files have been convert and updated.</h3>
</div>
<div class="sub-container">
<div class="form-field">
<label>Ticket Number : </label>
<input class="ticket-field" type="text" name="ticketNumber" value="" placeholder="Please enter ticket number">
</div>
<div class="button-field">
<input type="submit" class="btn-search"value="Search">
<button class="btn-update">Update</button>
<button class="btn-prev" name="previous">PREV</button>
<button class="btn-next" name="next">NEXT</button>
</div>
<input type="hidden" name="ticketHolder" value="">
</div>
<div id="text-field">
</div>
</div>
my js search using jquery and ajax
$("div.container").on("click", ".btn-search", function(event) {
event.preventDefault();
var noError = true;
var ticketNumber = $.trim($("input[name='ticketNumber']").val());
if($.isNumeric(ticketNumber) || ticketNumber==""){
noError = true;
}else{
noError = false;
$("input[name='ticketNumber']").val('');
alert("please enter a number");
}
if(noError){
$("#text-field").empty();
$.ajax({
method: "post",
url: "/search",
dataType: "json",
data: {ticketNumber:ticketNumber},
success: function(data){
if(data.length>1){
$.each(data,function(index,item){
$("#text-field").append("<h3 class='block-hearder'><span>"+item['dateOfFile']+"</span><span>"+item['paxName']+"</span><span>"+item['airlineName']+"</span></h3><div class='text-block'>"+item['content']+"</div>");
});
$( "#text-field" ).accordion( "destroy" );
$( "#text-field" ).accordion({
collapsible: true
});
}else{
$.each(data,function(index,item){
$("#text-field").append("<div class='text-block-single'>"+item['content']+"</div>"+"<script>");
searchNext(item['systemName'],item['ticketNumber']);
if(item['content'].indexOf('S') != 0){
$('.btn-prev').button( "enable" );
$('.btn-next').button( "enable" );
}
});
}
$("input[name='ticketNumber']").val('');
}
});
}
}); //end btn-search
my searchNext() for js
function searchNext(systemName, ticketNumber){
var systemName = systemName;
var ticketNumber = Number(ticketNumber);
// Making sure this function doesn't get called twice
if( !this.wasRun ){
$(".btn-next").click(function(event) {
event.preventDefault();
$.ajax({
method: "post",
url: "/next",
dataType: "json",
data: {systemName: systemName, ticketNumber: ticketNumber},
success: function(data){
$("#text-field").empty();
$("#text-field").append("<div class='text-block-single'>"+data['content']+"</div>");
if(data['content'].indexOf('>') > 0){
if((ticketNumber + 1) == data['ticketNumber']){
ticketNumber++;
searchNext(ticketNumber, data['systemName']);
}
}else{
$('.btn-next').button( "disable" );
}
}
});
}); //end btn-next
}
this.wasRun = true;
} //end searchNext()
in my php, my search()
public function search(){
$data = array();
/* Check if ticket number entered is not null and is number */
if(($_POST['ticketNumber'] != null) && (is_numeric($_POST['ticketNumber']))){
$ticketNumber = trim($_POST['ticketNumber']);
}else{
$ticketNumber = "";
}
if(strlen($ticketNumber) == 10 ){
$model = Document::where('ticketNumber', '=', $ticketNumber)->get();
}else{
$data['content'] = 'entery valid ticket number (10 numbers)';
}
$index = 0;
if(sizeof($model)>0){
foreach ($model as $key => $value) {
$document = $value->getAttributes();
$data[$index]['content']=$document['fileContent'];
$data[$index]['dateOfFile']=$document['dateOfFile'];
$data[$index]['systemName']=$document['systemName'];
$data[$index]['ticketNumber']=$document['ticketNumber'];
$index++;
}
}else{
$data[$index]['content'] = "Sorry the document does not exist, or hasn't been update yet, please click update and try again.";
}
echo json_encode($data);
} //End search function
in my php next() which searches the next record
public function next(){
$data = array();
$systemName = $_POST['systemName'];
$nextTicketNumber = $_POST['ticketNumber'] + 1;
//used to get the nextTicketNumber if there is a sequential nextTicketNumber
$model = Document::where('systemName', '=', $systemName)
->where('ticketNumber', '=', ($nextTicketNumber))->get();
if(sizeof($model) == 0){
$data['content'] = 'Reached end of record';
return json_encode($data);
}
//Getting all the same system number and stores the tickets in an array to find the max ticketNumber
$getAllModel = Document::where('systemName', '=', $systemName)->get();
$allTicketNumber = [];
if(sizeof($getAllModel) > 0){
foreach($getAllModel as $key => $value){
$allTicketNumber[] = $value->ticketNumber;
}
}
$maxTicketNumber = max($allTicketNumber);
if($nextTicketNumber > $maxTicketNumber){
$data['content'] = 'Reached end of record';
}else{
$data['content'] = $model[0]->fileContent;
$data['ticketNumber'] = $model[0]->ticketNumber;
$data['systemName'] = $model[0]->systemName;
}
echo json_encode($data);
}

PHP SQL / Ajax retrievement issues

I have a web application where I get the data from a mysql database and put it in the website with the help of handlebars templating.
First of all, the PHP i use looks something like this:
<?php
function isXHR() {
return isset( $_SERVER['HTTP_X_REQUESTED_WITH'] );
}
function connect(){
global $pdo;
$pdo = new PDO("mysql:host=localhost;dbname=personal", "user", "password");
}
function get_blog_posts( ) {
global $pdo;
$stmt = $pdo->prepare('
SELECT url, title, location, date, author, content, thmb
FROM photolog
LIMIT 50');
$stmt->execute();
return $stmt->fetchAll( PDO::FETCH_OBJ );
}
Then i use a javascript function that I call inside the document.ready(...) that looks like:
function loadBlogPosts(){
var photos = {
init: function( config ) {
this.config = config;
this.setupTemplates();
this.fetchphotos();
this.helpers();
$.ajaxSetup({
url: 'index.php',
type: 'POST'
});
},
setupTemplates: function() {
this.config.photoListTemplate = Handlebars.compile( this.config.photoListTemplate);
},
helpers: function(){
Handlebars.registerHelper("foreach",function(arr,options) {
if(options.inverse && !arr.length)
return options.inverse(this);
return arr.map(function(item,index) {
item.$index = index;
item.$first = index === 0;
item.$last = index === arr.length-1;
item.$rest = index >= 1;
return options.fn(item);
}).join('');
});
},
fetchphotos: function() {
var self = photos;
$.ajax({
dataType: 'json',
success: function(results) {
self.config.photosList.empty();
for(i=0;i<results.length;i++){
results[i].author = results[i].author.toLowerCase();
results[i].title = results[i].title.toUpperCase();
results[i].location = results[i].location.toUpperCase();
}
if ( results[0] ) {
self.config.photosList.append( self.config.photoListTemplate( results.reverse() ) );
} else {
self.config.photosList.append('<li>Nothing returned.</li>');
}
}
});
}
};
photos.init({
photoListTemplate: $('#photo_blog_template').html(),
photosList: $('div#blog_list')
});
}
And then put the data into the template:
<div id="blog_list">
<script id="photo_blog_template" type="text/x-handlebars-template">
{{#foreach this}}
{{#if $first}}
<div class="4u">
<div class="photo">
<a id="single_image" href="{{url}}"><img src="{{thmb}}" alt=""/></a>
</div>
</div>
<div class="8u post">
<header>
<h2>{{title}}</h2>
<h3>{{location}}</h3>
<div class="antet">
<div class="author">{{author}}</div>
<div class="date">{{date}}</div>
</div>
</header>
<p>{{content}}</p>
</div>
{{/if}}
{{#if $rest}}
<div class="3u post-small">
<div class="photo">
<a id="single_image" href="{{url}}"><img src="{{thmb}}" alt=""/></a>
</div>
<header>
<h2>{{title}}</h2>
<h3>{{location}}</h3>
<div class="antet">
<div class="author-small">{{author}}</div>
<div class="date-small">{{date}}</div>
</div>
</header>
<p>{{content}}</p>
</div>
{{/if}}
{{/foreach}}
</script>
</div>
The problem appears on the new android browsers, and after I close the application/page and open it with ctrl+shift+T. It doesn't show the page, it just shows the json file. The page is at stefanperju.com

Categories

Resources