AngularJS errorcallBack - php

I'm having some difficulty with AngularJS. Any constructive help is greatly appreciated.
This is the Angular code I'm working with
app.controller('customersCtrl', function($scope, $http) {
$scope.element = function(num){
var element_id = num;//num;
$http.get("customers.php",{params:{"id":element_id}}).then(function (response) {
$scope.myData = response.data;
}
,function errorCallback(response){
$scope.e=response.data;
console.log(e);
});
};
});
And here is my php code I'm using. All this does is return the 401 code. The section works as I can return it in a console log.
http_response_code(401);
$message = http_response_code()." No data found";
header('Content-Type: application/json');
echo json_encode($message);
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>page2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src = "javascript.js"></script>
</head>
<body ng-app="input">
<div ng-controller="customersCtrl">
<h1>Click on the contact name for company and location</h1>
<br>
<button ng-click="element(0)">Bob</button>
<button ng-click="element(1)">Jim</button>
<button ng-click="element(2)">Kim</button>
<br>
<br>
<ul>
<li ng-repeat="x in myData">
{{x}}
</li>
</ul>
<div ng-show="error != null">
<p>{{e.error}}</p>
</div>
</div>
View full list
</body>
</html>
I'm having a problem displaying the 401 message in the HTML page. What is a good way of doing this? The code will return the message but only as a console log. I need it in a HTML page. I'm quite confused on this one as I've tried multiple ways and none of them are working. Any help would be greatly appreciated
Thank you in advance!!!

Hey Man try that below:
$scope.e = '';
$scope.myData = [];
$scope.element = function(element_id){
$http({
method: 'GET',
url: "customers.php?id=" + element_id,
headers: {
'Content-Type': 'application/json'
}
})
.then(
function successCallback(response) {
$scope.myData = response.data;
callback(response);
},
function errorCallback(response) {
$scope.e = response.data;
callback(response);
}
);
}
Check on browser the network, and if no work, plz upload the network with log to "customers.php"
Best Wishes

Related

Laravel file is not uploded

I try to make a page to upload some files to server side. But it does not work.
// **Here my upload.blade.php**
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Multiple Files Upload Using Dropzone with - CodingDriver</title>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">
</head>
<style>
.alert-message {
color: red;
}
</style>
<body>
<div class="container">
<h2 style="margin-top: 12px;" class="alert alert-success">Laravel Multiple Files Upload Using Dropzone -
<a href="https://www.codingdriver.com" target="_blank" >CodingDriver</a>
</h2>
<div class="row" style="clear: both;margin-top: 18px;">
<div class="col-12">
<div class="dropzone" id="file-dropzone"></div>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>
<script>
Dropzone.options.fileDropzone = {
url: 'upload/classification',
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
maxFilesize: 8,
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
removedfile: function(file)
{
var name = file.upload.filename;
$.ajax({
type: 'POST',
url: 'file.remove',
data: { "_token": "{{ csrf_token() }}", name: name},
success: function (data){
console.log("File has been successfully removed!!");
},
error: function(e) {
console.log(e);
}});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
success: function (file, response) {
console.log(response);
},
}
</script>
// **my web.php**
Route::get('upload',function(){
return view('upload');
});
Route::post('upload/classification', [imageClassificationController::class, 'uploadDataset']);
<?php
// my imageClassificationController.php
namespace App\Http\Controllers;
use App\Models\imageClassificationModel;
use Illuminate\Http\Request;
use App\Models\fileTransferModel;
use Auth;
config('projectConfigs.pathConfigs');
class imageClassificationController extends Controller
{
public function uploadDataset()
{
try{
$file = request()->file();
//echo 'File Name: '.$file->getClientOriginalName();
//return __DIR__;
//$fileName= $file->getClientOriginalName();
//return $file;
$file->move(__USERFOLDERS__.DIRECTORY_SEPARATOR.Auth::user('foldername').DIRECTORY_SEPARATOR.'image-classification'.DIRECTORY_SEPARATOR.'datasets',$file);
return $file->getClientOriginalName();
}
catch(Exception $e){
return 'test'.$e;
}
}
}
These codes return 500 internal server error. But if I return $file, it returns javascript file object. I don't know why I cant save the uploaded file. Also getClientOriginalName returns 500 internal server error. And at last, try-catch also returns 500 internal server error.
Thanks for your helps...
You've got to add the input name to the request file function, and use the Laravel File move functionality:
public function uploadDataset()
{
try{
$file = request()->file('file'); // the input name attribute
$file->move(__USERFOLDERS__.DIRECTORY_SEPARATOR.Auth::user('foldername').DIRECTORY_SEPARATOR.'image-classification'.DIRECTORY_SEPARATOR.'datasets'.DIRECTORY_SEPARATOR, $file->getClientOriginalName());
return $file->getClientOriginalName();
}
catch(Exception $e){
return 'test'.$e;
}
}

Laravel 419 after ajax post request with CSRF token applied

I've been following this guide: https://www.freecodecamp.org/news/how-to-build-a-keyword-density-tool-with-laravel/ and have found right at the end my app won't return any array. In fact when I click the submit button I notice I get a 419 console error. After checking most issues relate to the CSRF token but from check I have this is place properly.
Can anyone spot or guide me in the right direction so that my app returns something. It's not very advanced in fact it's a very simple application, but It's my first time using Laravel so any guidance is appreciated.
My index.blade.php (This contains the form and ajax request)
#extends('layouts.master')
#section('content')
<form id="keywordDensityInputForm">
<div class="form-group">
<label for="keywordDensityInput">HTML or Text</label>
<textarea class="form-control" id="keywordDensityInput" rows="12"></textarea>
</div>
<button type="submit" class="btn btn-primary mb-2">Get Keyword Densities</button>
</form>
#endsection
#section ('scripts')
<script>
$('#keywordDensityInputForm').on('submit', function (e) { // Listen for submit button click and form submission.
e.preventDefault(); // Prevent the form from submitting
let kdInput = $('#keywordDensityInput').val(); // Get the input
if (kdInput !== "") { // If input is not empty.
// Set CSRF token up with ajax.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({ // Pass data to backend
type: "POST",
url: "tool/calculate-and-get-density",
data: {'keywordInput': kdInput},
success: function (response) {
// On Success, build a data table with keyword and densities
if (response.length > 0) {
let html = "<table class='table'><tbody><thead>";
html += "<th>Keyword</th>";
html += "<th>Count</th>";
html += "<th>Density</th>";
html += "</thead><tbody>";
for (let i = 0; i < response.length; i++) {
html += "<tr><td>"+response[i].keyword+"</td>";
html += "<td>"+response[i].count+"</td>";
html += "<td>"+response[i].density+"%</td></tr>";
}
html += "</tbody></table>";
$('#keywordDensityInputForm').after(html); // Append the html table after the form.
}
},
});
}
})
</script>
#endsection
My master.blade.php (CSRF token in the head)
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Keyword Density Tool</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
body {padding-top: 5em;}
</style>
</head>
<body>
...
<main role="main" class="container mt-3">
#yield('content')
</main><!-- /.container -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
#yield('scripts')
</body>
</html>
My controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Html2Text\Html2Text;
class ToolController extends Controller
{
public function index()
{
return view('tool.index');
}
public function CalculateAndGetDensity(Request $request) {
if ($request->isMethod('GET')) {
if (isset($request->keywordInput)) { // Test the parameter is set.
$html = new Html2Text($request->keywordInput); // Setup the html2text obj.
$text = strtolower($html->getText()); // Execute the getText() function and convert all text to lower case to prevent work duplication
$totalWordCount = str_word_count($text); // Get the total count of words in the text string
$wordsAndOccurrence = array_count_values(str_word_count($text, 1)); // Get each word and the occurrence count as key value array
arsort($wordsAndOccurrence); // Sort into descending order of the array value (occurrence)
$keywordDensityArray = [];
// Build the array
foreach ($wordsAndOccurrence as $key => $value) {
$keywordDensityArray[] = ["keyword" => $key, // keyword
"count" => $value, // word occurrences
"density" => round(($value / $totalWordCount) * 100,2)]; // Round density to two decimal places.
}
return $keywordDensityArray;
}
}
}
}
?>
and my routes
Route::get('/tool', 'App\Http\Controllers\ToolController#index')->name('KDTool');
Route::post('/tool/calculate-and-get-density', 'App\Http\Controllers\ToolController#CalculateAndGetDensity');
and the error I get is this
https://imgur.com/lRYqo09
I have checked all otherwsie answer suggestions on stackoverflow but nothing I do seem's to get my any further. Thanks for any help in advance

Ajax POST with mysqli database query

I am trying to get Ajax to POST to another.PHP file in the same directory as the main index. The idea is that I want an online diary that people can write into and have it instantly updated in the database.
Currently, my ajax looks like this
$('#diary').on('input propertychange', function() {
$.ajax({
type: "POST",
url: "updatedatabase.php",
data: {content: $('#diary').val()},
success: function( msg ) {
alert('Data Saved: ' + msg);
},
dataType: "text"
});
});
My PHP looks like this, on the updatedatabase.php page
<?php
session_start();
if ($_POST['content']) {
$link = mysqli_connect("location", "username", "password", "databasename");
if (mysqli_connect_error()) {
echo "Could not connect to database";
die;
}
$query = "UPDATE `users` SET `Diary` = '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE email = '".mysqli_real_escape_string($link, $_SESSION['email'])."' LIMIT 1";
if (mysqli_query($link, $query)) {
echo "Success";
} else {
echo mysqli_error($link);
echo "Failure";
}
}
?>
Full HTML + PHP at start of main page:
<?php
session_start();
$link = mysqli_connect(databaseinfo);
if (mysqli_connect_error()) {
echo "Could not connect to database";
die();
}
if (empty($_COOKIE['userId']) && (empty($_SESSION['email']))) {
header('Location: index.php');
}
$query = "SELECT email FROM users WHERE email = '".mysqli_real_escape_string($link, $_COOKIE['userId'])."' ";
if (!mysqli_query($link, $query)) {
header('Location: login.php');
die();
}
if(isset($_POST['logout'])) {
unset($_SESSION['email']);
setcookie('userId', '', time() - 60 * 60);
header('Location: login.php');
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style type="text/css">
body {
background-image: url("images/landscape.jpg");
}
h1 {
text-align: center;
margin: 15px auto 30px auto;
}
#diary {
min-height: 40vw;
}
</style>
</head>
<body>
<div class="container">
<div class="container">
<h1>Secret Diary</h1>
<form method="POST">
<div class="form-group">
<button type="submit" name="logout" id="logout" class="btn btn-info">Logout</button>
</div>
</form>
</div>
<div class="form-group">
<div class="form-group">
<textarea class="form-control" name="diary" id="diary" rows="3" placeholder="shhh"></textarea>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#diary').on('input propertychange', function() {
$.ajax({
type: "POST",
url: "updatedatabase.php",
data: {content: $('#diary').val()},
success: function( msg ) {
alert('Data Saved: ' + msg);
},
dataType: "text"
});
});
</script>
</body>
</html>
I have tried changing from .on to .bind, I've tried different variations of the ajax code and update database code, I've tried looking around StackOverflow.
p.s I understand there are a couple of security errors in the mysqli query injections. This is mainly for my own practice and learning journey but I am struggling to figure this one out.
Many thanks in advance.
Use .on('change') to bind to the input event.
Also, don't use the slim minified jquery library if you're going to use ajax, it's not included. See jQuery 3 slim ajax basic example
EDIT: I got the script working, with this piece of html/js:
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#diary').on('change', function() {
$.ajax({
type: "POST",
url: "updatedatabase.php",
data: {content: $('#diary').val()},
success: function( msg ) {
alert('Data Saved: ' + msg);
},
dataType: "text"
});
});
</script>
You should use the change in jQuery like this:
$('#diary').on('change', function() {
code...
});
or
$(document).on('change', '#diary', function() {
code...
});
or if the #diary is not dynamically created (in runtime) you could do:
$('#diary').change(function() {
code...
});

Using jquery.load() function to load an angular page

im working in a personal project right now and im mixing jquery and angularjs
and this week i face one problem that is the next
what im trying to do is load an angular page into a div using jquery.load()
(jquery part)
Test1.php
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<button class="btn btn-default" id="sss" type="button">load angular page into div using jquery</button>
<div id="tarkan"></div>
<script>
$("#sss").on("click", function (e) {
$("#tarkan").load("/elements/test2.php");
});
</script>
(angular part)
test2.php
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("https://www.w3schools.com/angular/customers.php").then(function (response) {
$scope.myData = response.data.records;
});
});
</script>
</body>
</html>
the test1.php gives me this
{{ x.Name + ', ' + x.Country }}
instead the data of the angular page.
today my partial solution to this is the use of iframes instead of using jquery.load
<div id="tarkan"></div>
<iframe id="tarkan2" src="" width="100%" height="700px" frameborder="0" scrolling="no" ></iframe>
<script>
$("#sss").on("click", function (e) {
//its not working
$("#tarkan").load("/elements/test2.php");
//its working
$("#tarkan2").attr("src", "/elements/test2.php");
});
</script>
my final question is there a way to load the angularpage into a div using jquery load?
any explanations or solutions are very welcome :)
you could achieve this with only angular : by using directive for the data and have a button click in the controller that would load the directive .. the directive is shown only if the $scope.show is true.
var app = angular.module('myApp', []);
app.controller('Mycontroller', function($scope) {
$scope.show = false;
$scope.getData = function() {
console.log("hi");
$scope.show = true;
};
})
app.directive('customersCtrl', function() {
return {
restrict: 'E',
controller: function($scope, $http) {
$http.get("https://www.w3schools.com/angular/customers.php").then(function(response) {
$scope.myData = response.data.records;
});
},
templateUrl: 'test2.tpl.html'
}
});
here is a working plunker

php function call with ajax

I am trying to call a php function when an HTML button is clicked.i have done some searching and found that its impossible to do this directly and i should use ajax.
so this is my attempt so far which is not working.this is my test.php and the function is also in this page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.NextPage').on('click', function() {
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
alert(response);
}
});
});
});
</script>
</head>
<body>
<button type="button" class="NextPage">go to nextpage</button>
<?php
if (isset($_POST['x'])) {
if ($_POST['x'] == 1) {
$data = function1();
echo json_encode($data);
exit;
}
}
function function1() {
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
get the value of the x from ajax call.
$x = $_POST['x'];
then use it.
EDIT
First you have to check weather your variable is set or not..
if(isset($_POST[x]))
{
$x = $_POST['x'];
}
try this
I've practically used your code and got it working. Your PHP is just fine, as for your AJAX call, it must have success or done to benefit the returned data.
The code for reference is here
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="mobile-web-app-capable" content="yes">
<link rel="shortcut icon" sizes="196x196" href="">
<link rel="stylesheet" type="text/css" href="" />
</head>
<body>
<div id="abc"></div>
<button type="submit" class="NextPage">go to nextpage</button>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
JavaScript
$(document).ready(function() {
$('.NextPage').click(function() {
$.ajax({
type:'post',
url:'service.php',
data:{x:1}
}).done(function(data) {
$("#abc").text(data);
});
});
});
PHP
<?php
$x = $_POST['x'];
if ($x == 1) {
function1();
}
function function1() {
echo "This is function 1";
}
function function2() {
echo "This is function 2";
}
First off, you need to set your button to type="button", then, make an AJAX request, then the missing part on your code is the backend part which processes the request. Then the backend responds to that call. After that you can just do what you please on that response. Consider this example:
<?php
// this part handles the AJAX request
if(isset($_POST['x'])) {
if($_POST['x'] == 1) {
$data = function1();
// a call has made, then give a response
echo json_encode($data);
exit;
}
}
function function1() {
// do some processing
return 'Hi user! im function #1';
}
function function2() {
return 'Hi user! im function #2';
}
?>
<!-- make its type "button" -->
<button type="button" class="NextPage">go to nextpage</button>
<div id="notification"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.NextPage').click(function(){
$.ajax({
url: 'test.php',
data: {x: 1},
type: 'POST',
dataType: 'JSON',
success: function(response) {
$('#notification').html('Your ajax call has been successful<br/> and this is a notification').css({background: 'yellow'});
}
});
});
});
</script>
What makes you think it is impossible to call a php function directly. This is exactly what is done in CodeIgniter PHP MVC framework. You can call a php function with arguments inside a php class directly in CodeIgniter and that is actually what is done always.

Categories