I did a bunch of reaserch but it seems that I cant find a good answer to my question.
I have this code here:
while($row = mysqli_fetch_row($query)){
$result .= '
<script>
function Click'.$DOMid.'01(){answer("'.$DOMid.'","'.$row[2].'", "accept");}
function Click'.$DOMid.'02(){answer("'.$DOMid.'","'.$row[2].'", "decline");}
</script>
<div id = "'.$DOMid.'" style = "box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; padding:10px; border: 1px solid #0f0f0a;">
<p>
Freundschaftsanfrage von: '.$row[2].'
</p>
<button id = "'.$DOMid.'01" onclick="Click'.$DOMid.'01">Accept</button>
<button id = "'.$DOMid.'02" onclick="Click'.$DOMid.'02">Decline</button>
</div>
';
$DOMid = $DOMid+1;
}
$result .= '<script>
function answer(id, user, type){
$.ajax({
method: "POST",
url: "systems/friends_system.php",
data:{type: type, user, <?php echo json_encode($log_username);?>}
}).done(function(r){
if(r.charAt(0) == "_"){
window.location = "message.php?msg=" + r;
}else{
_("id").style.display = "none";
}
});
}
</script>';
echo $result;
exit();
its PHP code and it generates html and the javascript for each element.
But I think my javascript part isnt parsed at that point to the browser throws an error that the Clickxxx functions are not defined.
The resulting code looks like this:
<script>
function Click001(){answer("0","Drop", "accept");}
function Click002(){answer("0","Drop", "decline");}
</script>
<div id="0" style="box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; padding:10px; border: 1px solid #0f0f0a;">
<p>
Freundschaftsanfrage von: Drop
</p>
<button id="001" onclick="Click001">Accept</button>
<button id="002" onclick="Click002">Decline</button>
</div>
<script>
function answer(id, user, type){
$.ajax({
method: "POST",
url: "systems/friends_system.php",
data:{type: type, user, <?php echo json_encode($log_username);?>}
}).done(function(r){
if(r.charAt(0) == "_"){
window.location = "message.php?msg=" + r;
}else{
_("id").style.display = "none";
}
});
}
</script>
Onclick is a html event, and consider that the Click001 is a function, so call it with it's parentheses:
...button id="001" onclick="Click001()">...
you need to call your function, also this is a better use of js
while($row = mysqli_fetch_row($query)){
$result .= '
<script>
function Click(accept)
{
if(accept){
answer("'.$DOMid.'","'.$row[2].'", "accept");
}else{
answer("'.$DOMid.'","'.$row[2].'", "decline");
}
}
</script>
<div id = "'.$DOMid.'" style = "box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; padding:10px; border: 1px solid #0f0f0a;">
<p>
Freundschaftsanfrage von: '.$row[2].'
</p>
<button id = "'.$DOMid.'01" onclick="Click(true)">Accept</button>
<button id = "'.$DOMid.'02" onclick="Click(false)">Decline</button>
</div>
';
$DOMid = $DOMid+1;
}
$result .= '<script>
function answer(id, user, type){
$.ajax({
method: "POST",
url: "systems/friends_system.php",
data:{type: type, user, <?php echo json_encode($log_username);?>}
}).done(function(r){
if(r.charAt(0) == "_"){
window.location = "message.php?msg=" + r;
}else{
_("id").style.display = "none";
}
});
}
</script>';
echo $result;
I reinvented the Code
It looks like this now:
$result .= '
<div id = "'.$DOMid.'" style = "box-shadow: 5px 5px 2px #0f0f0a; margin: 10px; width:300px; height: 105px; padding:10px; border: 1px solid #0f0f0a;">
<p style = "height: 75px;">
<span style = "line-height: 75px; margin: auto 2px;">
Freundschaftsanfrage von: '.$row[2].'
</span>
<span style = "line-height: 75px; margin: auto 2px;">
<img src = "/user/'.$row[2].'/profile_pic.png" height = 60px width = 50px alt= "'.$row[2].'">
</span>
</p>
<button id = "'.$DOMid.'01" onclick="answer('.$DOMid.', \''.$row[2].'\', \'accept\')">Accept</button>
<button id = "'.$DOMid.'02" onclick="answer('.$DOMid.', \''.$row[2].'\', \'decline\')">Decline</button>
</div>';
every JavaScript is now in the original file and takes just parameters.
No Generic Javascript needed.
Related
I have an Infinite Scroll that loads more data (from DB) upon scrolling to the bottom,
However, when I try to include that file in another .PHP file and write any HTML tag at its top, it won't load more posts.
On console, I get an error as
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (test.php:126)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)`
My code goes as :
getData.php
<?php
require_once('db.php');
if (! function_exists('getData')) {
/**
* #param int $offset
* #param int $limit
* #return array|null
*/
function getData($offset, $limit, $conn) {
$offset = (int)$offset;
$limit = (int)$limit;
$sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $sqlQuery);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$cleanRow = [];
foreach ($row as $column => $value) {
$cleanRow[$column] = htmlentities($value);
}
$rows[]= $cleanRow;
}
return $rows;
}
}
Index.php
<?php
require_once ('getData.php');
$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
'rows' => $rows,
'offset' => $offset,
];
$data = json_encode($data);
// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
echo $data;
exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
font-family: Arial;
background: #e9ebee;
font-size: 0.9em;
}
.post-wall {
background: #FFF;
border: #e0dfdf 1px solid;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
width: 500px;
}
.post-item {
padding: 10px;
border: #f3f3f3 1px solid;
border-radius: 5px;
margin-bottom: 30px;
}
.post-title {
color: #4faae6;
}
.ajax-loader {
display: block;
text-align: center;
}
.ajax-loader img {
width: 50px;
vertical-align: middle;
}
</style>
<div class="post-wall">
<div id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
<input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// load the initial rows on page load
let initialData = <?= $data ?? '' ?>;
if (initialData) {
if (initialData.rows) {
addrows(initialData.rows);
$('.ajax-loader').hide();
}
}
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e) {
if ($(window).scrollTop() + 1 >= $(document).height() - $(window).height()) {
if ($(".post-item").length < $("#total_count").val()) {
let offset = $('#offset').val();
getMoreData(offset)
}
}
});
}
function getMoreData(offset) {
$('.ajax-loader').show();
$(window).off("scroll");
let pageUrl = window.location.href.split('?')[0];
$.ajax({
url: pageUrl + '?dataOnly=1&offset=' + offset,
type: "get",
success: function (response) {
response = JSON.parse(response);
if (response.rows) {
addrows(response.rows);
if (response.offset) {
$('#offset').val(response.offset);
}
$('.ajax-loader').hide();
}
windowOnScroll();
}
});
}
function addrows(rows) {
let postList = $("#post-list");
$.each(rows, function (i, row) {
let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
postList.append(rowHtml);
});
}
</script>
Now please note that the above code works completely fine, as infinite scroll does exactly what it needs to be.
But when I place it inside another file like
test.php
<div>
<?php include("index.php"); ?>
</div>
the first few posts (7) load and along with the loader.gif at the bottom. That's all.
Any help is greatly appreciated.
After basic understanding on what the error is trying to say, I finally figured out this as
ERROR:
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.success (test.php:126)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)
JSON should start with a valid JSON value – an object, array, string, number, or false/true/null. This response started with a < (hence the “Unexpected token <”).
That unexpected token, <, is a strong clue that the response was HTML instead of JSON.
The root cause is that the server returned HTML or some other non-JSON string.
So what I did was, just simply cut the JSON code into the top of the test.php leaving everything as it is.
index.php
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
font-family: Arial;
background: #e9ebee;
font-size: 0.9em;
}
.post-wall {
background: #FFF;
border: #e0dfdf 1px solid;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
width: 500px;
}
.post-item {
padding: 10px;
border: #f3f3f3 1px solid;
border-radius: 5px;
margin-bottom: 30px;
}
.post-title {
color: #4faae6;
}
.ajax-loader {
display: block;
text-align: center;
}
.ajax-loader img {
width: 50px;
vertical-align: middle;
}
</style>
<div class="post-wall">
<div id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
<input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// load the initial rows on page load
let initialData = <?= $data ?? '' ?>;
if (initialData) {
if (initialData.rows) {
addrows(initialData.rows);
$('.ajax-loader').hide();
}
}
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e) {
if ($(window).scrollTop() + 1 >= $(document).height() - $(window).height()) {
if ($(".post-item").length < $("#total_count").val()) {
let offset = $('#offset').val();
getMoreData(offset)
}
}
});
}
function getMoreData(offset) {
$('.ajax-loader').show();
$(window).off("scroll");
let pageUrl = window.location.href.split('?')[0];
$.ajax({
url: pageUrl + '?dataOnly=1&offset=' + offset,
type: "get",
success: function (response) {
response = JSON.parse(response);
if (response.rows) {
addrows(response.rows);
if (response.offset) {
$('#offset').val(response.offset);
}
$('.ajax-loader').hide();
}
windowOnScroll();
}
});
}
function addrows(rows) {
let postList = $("#post-list");
$.each(rows, function (i, row) {
let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
postList.append(rowHtml);
});
}
</script>
test.php
<?php
require_once ('getData.php');
$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
'rows' => $rows,
'offset' => $offset,
];
$data = json_encode($data);
// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
echo $data;
exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>
<div class="some">
<?PHP include("index.php"); ?>
</div>
And Voila. It works perfectly fine.
Thanks to #WesleySmith & #AngelDeykov for the time they spared on this.
I want to add state name in my state mysql table in database using PHP and Ajax but the modal box is not submitting the information. I posted all my code for single button submission in model box and are as follows:
My directory structure is:
test.html
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="./model.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js">
</script>
</head>
<body>
<button id="add_state">Add State</button>
<div>
<?php
include('server/connection.php');
$sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select name='StateName'>";
echo "<option>select</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value=$row[StateName]> $row[StateName] </option>";
}
echo "</select>";
?>
</div>
<div id="add_state_model" class="add_state_model">
<div class="add_state_model_content">
<span class="state_model_close">×</span>
<form id="state_submit_form" method="post" action="">
<label>Enter State:</label>
<input type="text" name="state">
<input type="submit" name="state_submit">
</form>
<div class="message_box" style="margin-left: 60px;"></div>
</div>
</div>
<script src="./model.js"></script>
</body>
</html>
and for backend i am using javascript and PHP
model.js
var add_state_model = document.getElementById('add_state_model');
var add_state_button = document.getElementById('add_state');
var add_state_span = document.getElementsByClassName('state_model_close')[0];
add_state_button.onclick = function(){
add_state_model.style.display = "block";
}
add_state_span.onclick = function(){
add_state_model.style.display = "none";
}
window.onclick = function(event) {
if (event.target == add_state_model) {
add_state_model.style.display = "none";
}
}
$(document).ready(function(){
var delay = 1000;
$('[name="state_submit"]').click(function(e){
e.preventDefault();
var state = $('#state_submit_form').find('[name="state"]').val();
if(state === ''){
$('.message_box').html(
'<p><span style="color:red;">Please enter state name!</span></p>'
);
$('[name="state"]').focus();
return false;
}
console.log(state);
$.ajax({
type: "POST",
url: "server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="./tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
});
});
And also there is server page addstate.php
<?php
if ( ($_POST['state']!="") ){
$state = $_POST['state'];
include('connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
//insert query for registration
$insertSql = "INSERT INTO `tbl_state_info`(`StateName`) VALUES ('$state')";
if ($conn->query($insertSql) === TRUE) {
echo "<span style='color:green;'>
<p>State added to dropdown</p>
</span>";
}else{
printf("Error: %s\n", $conn->error);
}
}
?>
and connection.php file
<?php
// set the timezone first
if(function_exists('date_default_timezone_set')) {
date_default_timezone_set("Asia/Kolkata");
}
$conn = new mysqli('localhost', 'root', '');
//check connection
if($conn->connect_error){
die("Connection Failed".$conn->connect_error);
}
//connect database
mysqli_select_db($conn, 'crm');
?>
and the css file model.css, it is used for Model Box pop up
.add_state_model {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.add_state_model_content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 30%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.state_model_close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.state_model_close:hover,
.state_model_close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
I am getting this below error:
Make me correct if I am not wrong
You can visit this URL this will help you to solve your problem How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?
Or try to change URL path
I have tried on my end it's working for me
url: "http://localhost/CRM/server/addstate.php",
to
url: "server/addstate.php"
If any help feel free to ask me
in your ajax request
data object accept only json object and you have passed query string
try this code
$.ajax({
type: "POST",
url: "http://localhost/CRM/server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
and second thing settimeout accept delay in miliseconds which i have specified 1 second
I have a ajax page (search.js) attach to my main page and setinterval every 2 sec. In my main page, I have div tag (class="view") which able to slide down and cut off the interval. Everything work exactly fine but I have problem, when I click (onClick="show()"), all my div tag slide down togather. But my objective is to click and slide down individual for each div tag. I have try to troubleshoot but is not working due to lack of knowledge. Would appreciate if anyone can help me here. thanks alot.
$allresponse = $_SESSION['allresponse'];
$json = json_encode($allresponse);
$db = json_decode($json,true);
for( $i = 0; $i < count($db); $i++)
{
$data = $db[$i];
?>
<div style="width:100%; height:100%; border-style:none; padding:5px; border-color:rgba(0, 0, 0, 0.2); border-width:4px; font-size:14px; overflow: hidden; margin:0px 0px 5px 0px; ">
<div style="float:left; margin:0px 5px 0px 0px; border:4px solid rgba(0, 0, 0, 0.2); border-radius:2px;">
<img src="<?php echo $data["companyIcon"]?>" width="49" height="47" style="border-radius:2px;">
</div>
<?php echo $data["productName"]?>
<div style="float:right; margin:0px 8px 0px 0px;">
<?php
echo $data["City"];
echo "</br>";
?>
</div>
<div class="view" style="font-size:12px; overflow:hidden; text-overflow:ellipsis; border-style:solid; display:-webkit-box;-webkit-line-clamp:2; -webkit-box-orient:vertical; height:40px; border:2px solid rgba(0, 0, 0, 0.2); border-radius:2px; padding:0px 2px 2px 2px;">
<?php
echo $data["Description"];
?>
</div>
<div style="float:right; margin:0px 8px 0px 0px;">
<div onClick="show()" style="cursor:pointer; font-size:12px; color:#8080FF; float:left;">Show <div style="color:#FFF; font-weight:bold; float:right;">/</div></div>
<div onClick="hide()" style="cursor:pointer; font-size:12px; color:#8080FF; float:right;"> Hide</div>
</div>
</div>
<?php
}
search.js
var Interc = null;
function search_city()
{
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState === 4 && hr.status === 200)
{
document.getElementById("citybox").innerHTML = hr.responseText;
}
};
hr.open("GET", "searchcity.php?t=" + Math.random(),true);
hr.send();
}
var Interc = setInterval(search_city,2000);
var Interr = null;
function search_radius()
{
var hr = new XMLHttpRequest();
hr.onreadystatechange = function()
{
if(hr.readyState === 4 && hr.status === 200)
{
document.getElementById("radiusbox").innerHTML = hr.responseText;
}
};
hr.open("GET", "searchradius.php?t=" + Math.random(),true);
hr.send();
}
var Interr = setInterval(search_radius,2000);
var Interp = null;
function search_product(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function()
{
if(hr.readyState === 4 && hr.status === 200)
{
document.getElementById("productbox").innerHTML = hr.responseText;
}
};
hr.open("GET", "searchproduct.php?t=" + Math.random(),true);
hr.send();
}
Interp = setInterval(search_product,2000);
function show()
{
clearInterval(Interc);
clearInterval(Interr);
clearInterval(Interp);
var $divView = $('div.view');
var innerHeight = $divView.removeClass('view').height();
$divView.addClass('view');
$('div.view').animate({height: (($divView.height() == 40)? innerHeight: "160px")}, 500);
}
function hide()
{
$('div.view').animate({height:40},500);
Interr = setInterval(search_radius,2000);
Interc = setInterval(search_city,2000);
Interp = setInterval(search_product,2000);
}
Your show() and hide() functions seem incorrect.
In show() it is odd, but legal to have a $ for the first character of the variable $divView in JavaScript (it is normal in PHP). It looks like you remove the class="view" attribute from the <div> tags that have it set and then turn around on the next line and add it back. Presumably, you want to know the height when the tag isn't there, but I don't think it does a re-layout until after your show() function completes.
Try commenting out the lines that invoke animate and see if the size change happens instantaneously instead of over the animation period.
The <div> where PHP initially prints out the city, does not seem to have an id="citybox" attribute, but document.getElementById("citybox").innerHTML = hr.responseText; seems to expect one. Similarly the <a> tag where your product name is inserted by PHP does not have an id="productbox" attribute, but document.getElementById("productbox").innerHTML = hr.responseText; seems to expect one.
Also, won't you have a one <div> tag per database record with class="view" set? The code seems to only anticipate one such tag on the page. Or, do you only really expect to get a single row of JSON back from your database query?
Finally, I generally use $.ajax() rather than working directly with the browsers raw XMLHttpRequest object.
I want to upload multiple image in folder and also save in database. Problem is that, my images are not moving in folder. i don't know why? but same code is running on localhost. I paste my code please help me:
var abc = 0; // Declaring and defining global increment variable.
$(document).ready(function() {
// To add new input file field dynamically, on click of "Add More Files" button below function will be executed.
$('#add_more').click(function() {
$(this).before($("<div/>", {
id: 'filediv',
}).fadeIn('slow').append($("<input/>", {
name: 'file[]',
type: 'file',
id: 'file'
}), $("<br/><br/>")));
});
// Following function will executes on change event of file input to select different file.
$('body').on('change', '#file', function() {
if (this.files && this.files[0]) {
abc += 1; // Incrementing global variable by 1.
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd" + abc).append($("<img/>", {
id: 'img',
src: 'x.png',
alt: 'delete'
}).click(function() {
$(this).parent().parent().remove();
}));
}
});
// To Preview Image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name) {
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
#import "http://fonts.googleapis.com/css?family=Droid+Sans";
form{
background-color:#fff
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family:'Droid Sans',sans-serif
}
#formdiv{
width:500px;
float:left;
text-align:center
}
form{
padding:40px 20px;
box-shadow:0 0 10px;
border-radius:2px
}
h2{
margin-left:30px
}
.upload{
background-color:red;
border:1px solid red;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0 green;
box-shadow:2px 2px 15px rgba(0,0,0,.75)
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow:0 0 5px rgba(0,0,0,.75)
}
#file{
color:green;
padding:5px;
border:1px dashed #123456;
background-color:#f9ffe5
}
#upload{
margin-left:45px
}
#noerror{
color:green;
text-align:left
}
#error{
color:red;
text-align:left
}
#img{
width:17px;
border:none;
height:17px;
margin-left:-20px;
margin-bottom:91px
}
.abcd{
text-align:center
}
.abcd img{
height:100px;
width:100px;
padding:5px;
border:1px solid #e8debd
}
b{
color:red
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="image.js"></script>
<link rel="stylesheet" type="text/css" href="image_style.css">
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<button id="save" name="save" type="submit" class="btn btn-success btn-sm upload" id="upload">SAVE</button>
if(isset($_POST['save'])){
for($i = 0; $i < count($_FILES['file']['name']); $i++){
$image = $_FILES['file']['name'][$i];
$target_path = "http://rental.thedigitalmarketingonline.com/uploads/vehicle_snap/".$image;
if(($_FILES['file']['size'][$i] < 100000)){
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)){
echo '<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
}else{
echo '<span id="error">please try again!.</span><br/><br/>';
}
}else{
echo '<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
first as #Gautam said, use form tag to be able to submit data,
second $target_path should be a real path such as "uploads/vehicle_snap/" as satya said
third this is not a good security practice, there is no filters to filter if this is an image or not so an attacker may upload php files and compromise your server/website
try filtering uploads by checking if the extension of the files is an image extension, you can do this by doing this:
$allowed_ext = ["png","jpg","jpeg","etc.."];
if(in_array(end(explode('.',$file['name'])),$allowed_ext)){
//uploading code goes inside here
}
I guess your data is not getting posted as you have not used form tags.
try using this and check if it works
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<button id="save" name="save" type="submit" class="btn btn-success btn-sm upload" id="upload">SAVE</button>
</form>
This question already has answers here:
How to access a model method with javascript
(2 answers)
Closed 8 years ago.
Please have a loook at the following code
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
//$this->requestAction('/flip2/correctAnswer')
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="acertei" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="Errei" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
$("#acertei").on("click", function() {
$.ajax({
url: "/flip2/correctAnswer",
success: function(data) {
// Do whatever you need to do with the response here.
},
});
});
});
</script>
This is the View of a CakePHP page. $this->requestAction('/flip2/correctAnswer') will call the correctAnswer() method in Controller.
Here If I call the $this->requestAction('/flip2/correctAnswer') on page load, this works fine. I need to call this when the Acertei button is clicked, so I added it to the Ajax as proposed by a fellow SO user. However, it didn't work, the function do not get called. Why is this?
I would recommend first giving your Acertei button a unique ID like "acertei" for example (it currently shares the ID of "2" with its sibling button). Then with jQuery you can do the following:
$("#acertei").on("click", function() {
$.ajax({
url: "/flip2/correctAnswer",
success: function(data) {
// Do whatever you need to do with the response here.
},
});
});
This adds a click event to the Acertei button that will start an AJAX request to the 'flip2/correctAnswer' URL.