I have a small problem here, i'm trying to have an anchor tag called "Photos", so when the user clicks on that anchor, tha Ajax will grab the results from PHP/MySQL database and display the images inside the opened lightbox.
I have tried to create something like this:
Fotos
Then Ajax:
$(document).on('click','#photos',function(event){
var imovel_id = $(this).attr('id');
$.ajax({
url: 'gallery_query',
type: 'POST',
dataType:"json",
data:{imovel_id: imovel_id},
success: function(data) {
if(data.status == 1) {
//Display images;
} else {
// Return Error message;
}
}
});
initLightbox();
});
Then my PHP query:
<?php require("includes/db_connect.php"); ?>
<?php $imovel_id = $_POST['property_id']; ?>
<?php
$query = "SELECT * FROM gallery WHERE imovel_id = '$imovel_id'";
$result = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($result) ){
?>
<?php
if($result > 0){
$data['status'] = 1;
$data['retorno'] .= '<img src="../images/imoveis/'. $row['foto_gallery'] .'>';
mysqli_close($connection);
}else{
$data['status'] = 0;
$data['retorno'] = "Erro ao exibir fotos, se o erro persistir, entre em contato conosco.";
}
echo json_encode($data);
?>
<?php } ?>
My problem is, i don't know if this is working, and what to use in Ajax success. I'm learning how Ajax works exactly, so i tried to implement it with lightbox as experiment.
Any thoughs?
Thanks!
A few pointers:
Escape your string to ensure no SQL injections are sent to your server (not escaping could allow someone to delete all your data!
<?php $imovel_id = mysqli_real_escape_string($_POST['property_id']); ?>
This is if in your database you record strings for imovel_id,
If not
<?php $imovel_id = intval($_POST['property_id']); ?>
<?php
$query = "SELECT * FROM gallery WHERE imovel_id = $imovel_id";
Sending the result:
// declare $data before, scope issue
$data = null;
if($result > 0){
$data['status'] = 1;
$data['retorno'] .= '<img src="../images/imoveis/'. $row['foto_gallery'] .'">'; // you were missing a closing quote for the image src.
}else{
$data['status'] = 0;
$data['retorno'] = "Erro ao exibir fotos, se o erro persistir, entre em contato conosco.";
}
mysqli_close($connection); // close connection regardless of returned data
echo json_encode($data);
Hope this helps.
Edit:
One last thing, if you want to display what you are receiving:
$.ajax({
url: 'gallery_query',
type: 'POST',
dataType:"json",
data:{imovel_id: imovel_id},
success: function(data) {
if(data.status == 1) {
$('#idOfElement').html(data.retorno);
} else {
// Return Error message;
}
}
});
Related
Trying to request the posts made by users and loading more posts on user's request.
Getting Unexpected end of JSON input error while making ajax request in console.
Javascript
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
url: "action.php?action=morePosts",
success: function(response){
var result = $.parseJSON(response);
console.log(result);
}
});
});
Making request to following code.
$_SESSION['posts']) stores the number of posts to be loaded in the session.
if($_GET['action']=="morePosts"){
if(isset($_SESSION['posts'])){
$_SESSION['posts'] = $_SESSION['posts'] + 4;
echo fetchAllPosts($_SESSION['posts']);
} else if(isset($_SESSION['posts'])&& $_SESSION['posts']>4){
$_SESSION['posts'] = 4;
}
}
Function for requesting all posts
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
for($i=0; $i<$array_length; $i++){
if(!empty($row[$i])){
for($j=0;$j<count($row);$j++){
$post['id']=$row[$i][0];
$post['user_id']=$row[$i][1];
$post['title']=substr($row[$i][2], 0 ,75);
$post['text']=strip_tags(mb_substr($row[$i][3],0,50));
$post['image']=$row[$i][4];
$post['date']=$row[$i][5];
}
return json_encode($post);
}
elseif(empty($row[count($row)])){
return json_encode(array());
}
}
}
Please suggest better ways of achieving this functionality,
Try to use echo instead of return and change ajax like also you din not echo the code inside elseif part:
$("#ajax_load_more").click(function(){
$.ajax({
type: "GET",
dataType: "json",
url: "action.php?action=morePosts",
success: function(response){
console.log(response);
}
});
});
try this :
function fetchAllPosts2($array_length){
$db = new db; //Class for database
$query = "SELECT * FROM `posts` ORDER BY `post_id` DESC LIMIT $array_length";
$result = $db::query($query);
$row = mysqli_fetch_all($result);
$post = array();
if($result && mysqli_num_rows($result) > 0) {
foreach($row as $key=>$value){
$post[$key]['id']=$value['id'];
$post[$key]['user_id']=$value['user_id'];
$post[$key]['title']=substr($value['title'], 0 ,75);
$post[$key]['text']=strip_tags(mb_substr($value['text'],0,50));
$post[$key]['image']=$value['image'];
$post[$key]['date']=$value['date'];
}
return json_encode($post);
}
return json_encode(['error'=>"no post found"]);
}
I have written a script i JQuery and PHP,
After the success return from PHP, AJAX function should catch a success response but I am not getting that.
Below is the code:
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
//if(data=="ok"){
if(data=="YES"){
alert("EMAIL");
}else{
alert(data);
}
//}
//if(data=="ok"){
//alert("Expenses Id already exists!");
//}else{
//alert(data);
//}
}
});
and here is the php code
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
//echo "helloooo";
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
//echo "Proceed";
}
}else{
echo "Not Okay";
}
}else{
}
}
I can see the echo value on browser and alert value also. But if condition is not working for success function???
Try set correct data type for returned data.
$.ajax({
url: 'script_admin-add-category.php',
method: 'POST',
data: {lExpensesId: lcl_ExpensesId},
dataType: 'text',
success: function (data) {
if (data === 'YES') {
alert('EMAIL')
} else {
alert(data)
}
}
})
#J Salaria as i understood your question you are having problem with jquery AJAX and PHP code as you are not getting you desired result. There are different ways to send the data through jquery ajax which i will be explain in detail.
$_POST["lExpensesId"] are you getting this ID from a HTML <form> ?.Because here i'll be showing you 3 different practiced ways to send data through ajax..
NOTE: YOUR CODE IS VULNERABLE TO SQL INJECION. I'LL BE ALSO SHOWING YOU THE METHODS TO OVERCOME.IF YOU WANT TO LEARN MORE ABOUT SQL INJECTION CLICK ON THIS LINK SQL INJECTION LINK
HTML FORM CODE :
<form action="" id="send_lExpensesId_form" method="post">
<input type="text" name="lExpensesId" id="lExpensesId" >
<input type="submit" name="submit" >
</form>
FIRST WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = $(this).serialize();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
SECOND WAY FOR SENDING DATA THIS IS THOUGH HTML <FORM>
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var form_serialize = new FormData($(this)[0]);
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:form_serialize,
contentType: false,
processData: false,
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
THIRD WAY FOR SENDING DATA THIS IS USED WHEN A LINK CLICKED OR TO DELETED THROUGH ID OR CLASS
<script>
$(document).ready(function(){
$("#send_lExpensesId_form").submit(function(e){
e.preventDefault();
var lcl_ExpensesId = $("#lExpensesId").val();
$.ajax({
type:'POST',
url:'script_admin-add-category.php',
data:{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data == "YES"){
alert("EMAIL");
}else{
alert(data);
}
}
});
});
});
</script>
HERE IT THE PHP CODE WITH mysqli_real_escape_string(); AGAINST SQL INJECTION
<?php
$servername = "localhost";
$username = "root";
$password = "admin";
$dbname = "demo";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["lExpensesId"])){
$lExpensesId = mysqli_real_escape_string($conn, $_POST["lExpensesId"]);
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
if($query_result = mysqli_query($conn, $Lquery)){
if(mysqli_num_rows($query_result )){
echo 'YES';
}else{
echo "Proceed";
}
}else{
echo "Error".mysqli_connect_error();
}
}
?>
HERE IT THE OTHER PHP CODE WITH MYSQLI->PREPARED WHICH IS BETTER AGAINST SQL INJECTION
<?php
// WITH MYSQLI PREPARED STATEMENT AGAINST SQL INJECTION
$sql = $conn->stmt_init();
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId =?";
if($sql->prepare($Lquery)){
$sql->bind_param('i',$lExpensesId);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo 'YES';
}else{
echo "Proceed";
}
}
else
{
echo "Error".mysqli_connect_error();
}
?>
I HOPE YOU GOT ANSWERE FOR YOU QUESTION IF YOU HAVE OTHER DOUBTS FEEL FREE AND COMMENT BELOW
All methods are known and many thanks for assistance. My question is that Why I am not able to get proper return from PHP. Below is my code:
var lcl_ExpensesId = $("#IExpensesId").val();
//alert(lcl_ExpensesId);
$.ajax({
url :"script_admin-add-category.php",
method :"POST",
data :{lExpensesId:lcl_ExpensesId},
success:function(data){
if(data=="ok"){
alert("Inserted");
}else{
alert(data);
}
}
});
ob_start();
/------------------FUNCTION TO READ ACCOUNTS DROPDOWN EXPENSES LIST -----------------------/
require_once 'db_config.php';
$newlist = fxn_CONFIGURATION();
$HOST = $newlist[0];
$DBNAME = $newlist[1];
$UNAME = $newlist[2];
$PSWD = $newlist[3];
$conn = mysqli_connect($HOST, $UNAME, $PSWD, $DBNAME);
//Check connection
if(!$conn){
die("Connection Failed: " .mysqli_connect_error());
}else{
if(isset($_POST["lExpensesId"])){
$lExpensesId = $_POST["lExpensesId"];
$Lquery = "SELECT ExpensesId FROM tblexpensestype WHERE ExpensesId = '$lExpensesId'";
$query_result = mysqli_query($conn, $Lquery);
if(mysqli_num_rows($query_result) > 0){
echo "ok";
}else{
echo "Proceed";
}
}
}
mysqli_close($conn);
ob_flush();
As, i am using this AJAX in my one of input keyup method so whatever I will type, each and everytime, it will execute PHP script. I am having a item as FOOD in databse. When i type "F", I got Proceed, "O" - Proceed, "O" - Proceed, "D" - ok....
When I type D, i should get "Inserted" instead of Ok....
This is my doubt that why i m getting this????
The above problem is resolved by using exit() statement in PHP as I am getting five ↵↵↵↵↵ after my values and it means I am having 5 lines of html without closing ?>. So the best way to resolve the issue is to use exit() in PHP as per need
I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...
You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().
I have written following PHP and Javascript code to prompt a user to delete a record, which works great.
I somehow do not think that this code is secure, the reason is if you run the script in a browser, and do a View-source a person will be able to see that I am using delete.php and passing an ID to delete the record.So there can be a possibility of deleting the records using delete.php
Is there a way to secure the code.
My PHP code is
<?
$rs = "SELECT * FROM my tablename";
$result = mysqli_query($con,$rs);
$data = mysqli_num_rows($result);
$responses = array();
if($data != 0) {
while($results = mysqli_fetch_assoc($result))
{
$res_id=$results['id'];
echo "<tr id='".$results['id']."'><td>".$results['_name'] ."</td>";
echo "<td><a alt='delete' href='javascript:;' onclick='fun_delete(".$results['id'].")' title='delete'><span class='glyphicon glyphicon-remove-circle'></span> ";
e
}
}
?>
My Javascript code is
<script>
function fun_delete(x)
{
//alert(x);
var result = confirm("Are you sure you want to delete the record?");
if (result) {
//alert(x);
jQuery.ajax({
url: "delete.php",
type: "post",
data: {id:x},
success: function(data){
if(data){
location.reload();
}
},
error:function(){
// JQ.fancybox.hideLoading();
alert("failure");
}
});
}
}
</script>
I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.