I would like check the image whether existing on server file system and the file list was store into database. I want to make a ajax call to doing validation then return the result to screen with append effect. Here is my code, but don't work :( Please help me.
UPDATE: Code is workable, but it's not my expectation, because three thousand record with caused timeout and No append effect. thanks
Controller
public function getImageList()
{
$this->load->model('image_model');
$data['list'] = $this->image_model->get_image();
foreach ($data['list'] as $key){
$result[] = $this->imageValidation($key->filename);
}
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($result));
}
private function imageValidation($imgfile)
{
if(!file_exists(LOCAL_IMG_TEMP.$imgfile))
{
return "<pre>". $imgfile." Not Find"."</pre>";
}
}
View
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<title></title>
</head>
<body>
<script>
function makeAjaxCall(){
$.ajax({
type: "POST",
url: "http://127.0.0.1:8888/index.php/ajax/getImageList",
cache: false,
dataType : "json",
success: function(data){
$("p").append(data);
}
});
}
</script>
</script>
<input type='button' id='PostBtn' value='Check Image' onclick='javascript:makeAjaxCall();' />
<p></p>
</body>
</html>
try to use file_exists()
check it
Related
I am trying to learn how to use an API in Laravel and show json results in my view. This is a sample code I have made but nothing is showing. The API is with values because when I try it in Postman, it returns json results.
<html>
<head>
<meta charset="utf-8">
<title>Item Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="container">
<ul id="items" class="list-group">
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function (){
getItems();
function getItems(){
$.ajax({
url:'https://www.boredapi.com/api/activity'
}).done(function (items){
let output = '';
$.each(items, function (key, activity){
output += '<li class="list-group-item">' +
'<strong>${activity.text}</strong>${text.body}' +
'</li>'
});
});
}
});
</script>
</body>
</html>
I suspect it might have a problem with the key tags i am trying to call. I am trying to make the call from blade not needed from the controller.
json returned from the API:
{
"activity": "Write a list of things you are grateful for",
"type": "relaxation",
"participants": 1,
"price": 0,
"link": "",
"key": "2062010",
"accessibility": 0
}
Here is the completed code.
<html>
<head>
<meta charset="utf-8">
<title>Item Manager</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="container">
<ul id="items" class="list-group">
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function (){
getItems();
var output = '';
function getItems(){
$.ajax({
url:'https://www.boredapi.com/api/activity'
}).done(function (items){
let output = '';
$.each(items, function (key, activity){
output += '<li class="list-group-item">' +
'<strong>'+key+'</strong>' + activity +
'</li>'
});
$("#items").append(output);
});
}
});
</script>
</body>
</html>
try adding this:
$.ajax({
url:'https://www.boredapi.com/api/activity',
type: "GET",
},
Also console.log() your result might be helpful.
is there any way to call a controller function when someone click on a check box. Like There are 4 check box with each has a category so when a user click on particular category then it will hit an API that process the filter request from the backend. I searched on Google but there is option to change it to
But that I don't want. Do I have to use jquery or else?
As in the comment section you can achive this via JQuery/Javascript. I have added a simple example with JQuery for your reference. What I achive here is first catch all check un check events and then via Ajax I send a request to the server. So that controller function will get called. You can test this via network tab when you check or uncheck a checkbox.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Check the Status of Checkboxes</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
//Add CSRF token to headers
$.ajaxSetup({
headers:
{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
$('input[type="checkbox"]').click(function(){
const val = $(this).val()
if($(this).prop("checked") == true){
alert(val+' Checked and sending data to server')
$.ajax({
type: "POST",
url: "file", // Route
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( "Data: " + msg );
});
}else{
alert($(this).val()+' unchecked');
$.ajax({
type: "POST",
url: "file",
data: { checkbox_val:val }
})
.done(function( msg ) {
alert( 'Record removed' );
});
}
});
});
</script>
</head>
<body>
<input value="A" type="checkbox"> A
<input value="B" type="checkbox"> B
<input value="C" type="checkbox"> C
</body>
</html>
I want that every time the "plato" button is pressed (there are several because I create them inside a loop) this function is executed
"$ ('# plato'). click (function ()" but I have observed that this code is only executed when the first button is pressed. With the others it is not executed.
menu.php:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilos.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<?php
$restaurante=$_GET['restaurante'];
chdir(getcwd()."/".$restaurante);
$id_fichero= #fopen("menus.txt","r") or die("<B>El fichero no se pudo abrir");
?>
<?php
while (!feof($id_fichero))
{
if(($linea=trim(fgets($id_fichero,256),"\n\r"))!=false)
{
echo("<button type='button' class='accordion'>".$linea."</button>");
echo("<div class='panel'>");
$id_fichero2= #fopen($linea.".txt","r") or die("<B>El fichero no se pudo abrir");
while (!feof($id_fichero2))
{
if(($linea2=trim(fgets($id_fichero2,256),"\n\r"))!=false)
{
echo("<button type='button' id='plato' name='plato'>".$linea2."</button><br>");
echo("<input type='hidden' id='nombrePlato' name='nombrePlato' value='".$linea2."'>");
}
}
echo ("</div>");
}
}
?>
<div id="carrito">
</div>
<script src="collapsible.js"></script>
</body>
</html>
ajax.js
$(document).on('ready',function(){
$('#plato').click(function(){
alert("I'm here");
var url = "anadirCarrito.php";
$.ajax({
type: "POST",
url: url,
data: $('#platos').serialize(),
success: function(data)
{
$('#carrito').html(data);
}
});
});
});
I've been looking for an example of updating data with d3.xhr but have not seen anything obvious, or at least of my level of understanding. The following 2 links are close but no cigar:
from stackoverflow
from mbostock’s block
I look around more and found this example in jquery and php. I tried it and understand the code. I would appreciate if you give me an equivalent code in d3.xhr or d3.json. BTW, what is different between d3.xhr and d3.json, and when to use what? Thanks in advance.
<?php
// AJAX & PHP example
// http://iviewsource.com/codingtutorials/learning-how-to-use-jquery-ajax-with-php-video-tutorial/
if ($_GET['ip']) {
$ip = gethostbyname($_GET['ip']);
echo($ip);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Reverse IP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>
<script>
$(document).ready(function() {
$('#searchip').change(function(){
$.ajax({
type: "GET",
url: "ajax.php",
data: 'ip=' + $('#searchip').val(),
success: function(msg){
$('#resultip').html(msg);
}
}); // Ajax Call
}); //event handler
}); //document.ready
</script>
</body>
</html>
I found the solution. In fact it has less coding, :) I sincerely hope that the answer would be useful to someone.
<?php
// AJAX & PHP example
if ($_GET['ip']) {
$ip = gethostbyname($_GET['ip']);
echo($ip);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Get Reverse IP</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
Please enter a domain name
<input type="text" id="searchip">
<div id="resultip"></div>
<script>
d3.select('#searchip').on("change", function() {
d3.xhr('xhr.php?ip='+this.value, function(data) {
d3.select('#resultip').html(data.response);
})
});
</script>
</body>
</html>
I have been struggling with this for a couple days and have yet to find any real solutions online yet. I have a form that allows users to enter their email, then after they enter it fades out and is replaced by another form. I am using ajax to submit data from a form to a symfony2 controller, which stories it in the database and sends a response. However, the response ends up just sending me to a blank page with the response data displayed, instead keeping me on the same page and just fading the boxes as needed. I think my issue is with how I have the controller actions set up and the routing files.
EDIT
Well now the issue is that when I click on the submit button nothing happens. Nothing is sent to the controller, so nothing is being stored and no response is being given. What I changed was based on the answer by #PaulPro, appending the
<script> $('#emailForm').submit(submitForm); </script>
to the end of the html page. Thanks in advance for any help and insight!
The controller has 2 relevant actions, the one that renders the TWIG Template with the form, and the one that handles the ajax form submission and returns the response.
public function emailAction()
{
return $this->render('Bundle:email.html.twig');
}
public function submitEmailAction()
{
$em = $this->getDoctrine()-> getEntityManager();
$email = new Email();
$request = $this->getRequest();
$emailVar = $request->request->get('emailSignup');
$email -> setEmail($emailVar);
$em->persist($email);
$em->flush();
$return=array("responseCode"=>200);
$return = json_encode($return);
return new Response($return, 200, array('Content-Type'=>'application/json'));
}
This is the routing for those actions, most likely the culprit of it all:
Bundle_email:
pattern: /email
defaults: { _controller: Bundle:email }
requirements:
_method: GET
Bundle_submitEmail:
pattern: /submitEmail
defaults: { _controller: Bundle:submitEmail }
requirements:
_method: POST
And then here is the email.html.twig template and ajax script:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="{{asset('css/styles.css')}}" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm(){
var emailForm = $(this);
var path = "{{path('Bundle_submitEmail')}}"
$.ajax ( {
type: 'POST',
url: $("#emailForm").attr("action"),
emailSignup: $("#emailId").val(),
success: function(data){
if(data.responseCode==200 ){
$('.email-signup-form').fadeOut();
$('.share-form').delay(500).fadeIn();
}
}
});
return false;
}</script>
</head>
<body>
<form id="emailForm" action="{{path('Bundle_submitEmail')}}" method="POST" class="email-signup-form">
<input type="email" placeholder="e-mail address" name="emailSignup" id="emailId" required="true"/>
<input type="submit" value="Go">
</form>
<form class="share-form">
</form>
<script> $('#emailForm').submit(submitForm); </script>
</body>
</html>
You don't ever call submitForm (the function that tells the browser to use AJAX rather than a full page load). Just add a script at the end of your body that looks like:
<script>
$('#emailForm').submit(submitForm);
</script>