PHP SQL / Ajax retrievement issues - javascript

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

Related

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

jQuery ajax keeps adding more and more elements

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();

TypeError: myObservableArray is undefined

I have an observable array that I want to be able to delete entries from via a button in the HTML using the knockout.js framework. However, when I try to use the observable array this.comments in the deleteComment function, I get a TypeError: this.comments is undefined, even though it is clearly defined and has entries. this.comments is even used in the entryComments function which works perfectly fine. Am I missing something?
HTML/PHP:
<div class="textblock">
<h1>User Comments</h1>
<ul id="usercomment" data-bind="foreach: comments">
<li><p><strong data-bind="text: comment"></strong> - <strong data-bind="text: user"></strong></p>
<button data-bind="visible: display(), click: $parent.deleteComment.bind($data, $index)" >Delete Comment</button>
</li>
</ul>
</div>
<br />
<?php if (isset($_SESSION['logged_in'])): ?>
<?php if ($_SESSION['logged_in'] == true): ?>
<div class="textblock">
<ul>
<li>
<form name="commentform" data-bind="submit: enterComment.bind($data,$data.comment )">
<input type="text" data-bind="value: $data.comment"/>
<button type="submit">Submit Comment</button>
</form>
</li>
</ul>
</div>
<?php endif; ?>
<?php endif; ?>
Javascript:
var AppViewModel = function (commentList, userList) {
//Initializing data
this.displayButton = ko.observable(false);
this.comments = ko.observableArray();
this.username;
$.ajax({
url: "http://localhost/sem4/recept/UserInfo.php",
async: false,
dataType: 'json',
success: function(data) {
username = data.username;
}
});
//Giving the array values
for(var i = 0;i<=commentList.length -1;i++ ){
if(username === userList[i]){
this.comments.push(new Comment(commentList[i],userList[i],true ));
}
else{
this.comments.push(new Comment(commentList[i],userList[i], false));
}
};
//Function is called but it cannot define this.comments
this.deleteComment = function(index){
this.comments.splice(index,1);
}
//This function works without any problems
this.enterComment = function (comment) {
$.ajax({
url: "http://localhost/sem4/recept/UserInfo.php",
async: false,
dataType: 'json',
success: function(data) {
username = data.username;
}
});
this.comments.push(new Comment(comment, username,true));
$.post("http://localhost/sem4/recept/AddComment.php", {
comment: comment,
username: username
});
};
//OBJECTS
function Comment(comment, user,bool) {
var self = this;
self.comment = ko.observable(comment);
self.user = ko.observable(user);
self.display = ko.observable(bool);
};
};
this scope changes when you use a function. a regular workaround is defining a self variable at the top and using it when you need to access the whole function scope.
var AppViewModel = function (commentList, userList) {
//Initializing data
var self = this;
....
self.deleteComment = function(index){
self.comments.splice(index,1);
}
...
}
The easiest fix is to use an arrow function, as they inherit this from their context.
...
this.deleteComment = (index)=>{ // was function(index){
this.comments.splice(index,1);
}
...

AJAX call on a javascript function doesn't work

This is actually the first time I'm using ajax so honestly I don't know a single thing. Tried to read articles about ajax but no luck. What I'm trying to do here is quite simple really I just want to try to figure out how ajax works and what I should do to make it work. I wanted it so that when I try to click the login button and go to my php and display "login success" it works when the textboxes are empty it displays fields are empty but the ajax doesn't seem to work
Here is what I've done so far this is my index.php A.K.A login page
<!DOCTYPE html>
<html>
<head>
<title>O-Chat</title>
<link rel="stylesheet" type="text/css" href="index.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script101.js"></script>
</head>
<body>
<div class="content">
<div class="features">
<div><br><br><br><br><br><br><br><br><br><br>FEATURES HERE</div>
</div>
<div class="loginpart">
<div class="banner"><br><br><br>BANNER HERE</div>
<div class="login" id="divlogin">
<div class="login-header">Login</div>
<form name="loginform" class="login">
<input class="login" type="text" name="pUname" id="jUname" maxlength="35" placeholder="Username"/><br>
<input class="login" type="Password" name="pPass" id="jPass" maxlength="40" placeholder="Password"/><br>
<span class="error" id="jloginerror"></span>
<div class="button" id="login"" onclick="validate();">
</div>
</form>
<div class="login-footer" onclick="location.href='register.php'">Not yet a member?<br>Register Now! Click Here!</div>
</div>
</div>
</div>
<div class="footer">
<div class="footer-container">
Home |
About O-Chat |
Contact Us
<div style="float: right;">Copyright © 2000 - 2017 O-Chat Unlimited (071813-S) All Rights Reserved</div>
</div>
</div>
</body>
</html>
Here is my javascript file script101.js
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
document.getElementById("divlogin").style.height = '250px';
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}
<?php
echo "very successful";
?>
Remove $ from the function declaration $function validate(). You can not use $ here.
You can use it like either
$(function(){
....
});
OR
if you wants to keep name of your function then just remove $ before the function, simply use it as:
function validate(){
....
}
and on ajax , you can use
$.ajax({
method: "post",
url: "login.php",
data: data;
sucess:function(data){
$("#jloginerror").text(data);
}
});
So your full code should be like as follows:
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}
Remove $ from the function keyword and Jquery works with element id or name var uname = $("#jUname").val(); var pass = $("#jPass").val(); and do not use ; for separating and you should use , $.ajax({}), use $.ajax({}) instead of ajax({}) because its Jquery function not javascript function.
function validate() {
var uname = $("#jUname").val();
var pass = $("#jPass").val();
var data = "&uname=" + uname + "&pass=" + pass;
if(!uname.match(/\S/) || !pass.match(/\S/)) {
document.getElementById("divlogin").style.height = '275px';
document.getElementById("jloginerror").innerHTML = "Some fields are empty!";
}
else
{
document.getElementById("jloginerror").innerHTML = "";
$.ajax({
type: "post",
url: "login.php",
data: data,
sucess:function(data){
$("#jloginerror").text(data);
}
});
}
}

using ajax to get data from a database with php [duplicate]

every type i run this it calls the error: OnError function and i can't see why it doesn't call the success: OnSuccess,
JS:
$(document).ready(function () {
// retreving data on button click
$("#data-submit").click(LoadDataThroughAjaxCall);
//loading screen functionality - this part is additional - start
$("#divTable").ajaxStart(OnAjaxStart);
$("#divTable").ajaxError(OnAjaxError);
$("#divTable").ajaxSuccess(OnAjaxSuccess);
$("#divTable").ajaxStop(OnAjaxStop);
$("#divTable").ajaxComplete(OnAjaxComplete);
//loading screen functionality - this part is additional - end
});
// ajax call
function LoadDataThroughAjaxCall() {
$.ajax({
type: "POST",
url: "Ajax/dataloader.php",
data: '{}',
dataType: "json",
success: OnSuccess,
failure: OnFailure,
error: OnError
});
// this avoids page refresh on button click
return false;
}
// on sucess get the xml
function OnSuccess(response) {
//debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var tweets = xml.find("Table");
showOnATable(tweets);
}
// show data on a table
function showOnATable(tweets) {
//debugger;
var headers = [];
var rows = [];
// header section
headers.push("<tr>");
headers.push("<td><b>tweets</b></td>");
headers.push("<td><b>created</b></td>");
headers.push("<td><b>source</b></td>");
headers.push("</tr>");
// rows section
$.each(tweets, function () {
var tweets = $(this);
rows.push("<tr>");
rows.push("<td>" + $(this).find("tweet_text").text() + "</td>");
rows.push("<td>" + $(this).find("created_at").text() + "</td>");
rows.push("<td>" + $(this).find("source").text() + "</td>");
rows.push("</tr>");
});
var top = "<table class='gridtable'>";
var bottom = "</table>";
var table = top + headers.join("") + rows.join("") + bottom;
$("#divTable").empty();
$("#divTable").html(table);
}
// loading screen functionality functions - this part is additional - start
function OnAjaxStart() {
//debugger;
//alert('Starting...');
$("#divLoading").css("display", "block");
}
function OnFailure(response) {
//debugger;
alert('Failure!!!' + '<br/>' + response.reponseText);
}
function OnError(response) {
//debugger;
var errorText = response.responseText;
alert('Error!!!' + '\n\n' + errorText);
}
function OnAjaxError() {
//debugger;
alert('Error!!!');
}
function OnAjaxSuccess() {
//debugger;
//alert('Sucess!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxStop() {
//debugger;
//alert('Stop!!!');
$("#divLoading").css("display", "none");
}
function OnAjaxComplete() {
//debugger;
//alert('Completed!!!');
$("#divLoading").css("display", "none");
}
PHP:
<?php
//if(isset($_POST['data'])==true&&empty($_POST['data'])==false){
require_once('../connection.php');
function clean($str)
{
if(get_magic_quotes_gpc())
{
$str= stripslashes($str);
}
return str_replace("'", "''", $str);
}
//Sanitize the POST values
//$username = clean($_POST['data']);
//$result=sqlsrv_query($conn,"execute sp_ORDER_BY_name '$username'");
$result=sqlsrv_query($conn,"select tweet_text,source from tweets");
if($result) {
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
echo $row['tweet_text'].", ".$row['source']."<br />";
}
}else {
//Login failed
echo 'Name not found';
}
}
//}
?>
HTML FORM:
</head>
<body>
<div id="banner">
<h1>P-CAT version 0.1</h1>
</div>
<div id ="content">
<h2>Sreach Catigroies</h2>
<select id="data2">
<option value="">Plece select one of the follwing</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input name="data" id="data" type="text" />
<input type="submit" id="data-submit" value="Grab">
<div id="divTable">
</div>
</div>
<div id="divLoading" style="display: none; position: absolute; top: 50%; left: 40%;
text-align: left;">
<span>
<img src="Images/ajax-loader.gif" alt="Image not found." /></span>
<br />
<span style="text-align: left; padding-left: 8px;">Loading ...</span>
</div>
<div id="navbar">
<input type="button" value="EDIT">
<input type="button" value="HISTORY">
<input type="button" value="SETTINGS">
<input type="button" value="SEARCH">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/global.js"></script>
</body>
You have to response a json from php like,
if(sqlsrv_has_rows($result) > 0) {
//Login Successful
$xml='<Table>';
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC) ) {
$xml.='<tweet_text>'.$row['tweet_text'].'</tweet_text>';
$xml.='<source>'.$row['source'].'</source>';
// create xml tag for created_at
}
$xml.='</Table>';
echo json_encode(array('d'=>$xml));
return TRUE;
} else {
//Login failed
echo json_encode(array('d'=>'Name not found'));
}

Categories

Resources