500 Internal Server Error when pass data in $.ajax - php

I am receiving a 500 internal server error when making an ajax call.
$(document).ready(function(){
$("#txtSearch").change(function(){
var search = $("#txtSearch").val();
var str = 'search=' + search;
$.ajax({
type: "POST",
url: "searchProcess.php",
data: str,
dataType: "json",
success: function(data) {
if (data["type"] == "1") {
alert('Please Enter Value To Search');
}else if (data['type'] == "2") {
alert('No Such of This Event In Database');
}else if (data['type'] == "3") {
$('#gallery').hide().html(data['data']).fadeIn('5s');
}
}
});
});
});
searchProcess.php
if (!isset($_POST["search"])) {
print json_encode(['type'=>'1']);
}else{
$seValue = "%{$_POST['search']}%";
$querySel = "SELECT * FROM gallery WHERE galleryTitle LIKE :title OR date LIKE :dat";
$stmtquerySel = $conn->prepare($querySel);
$stmtquerySel->bindParam('title',$seValue);
$stmtquerySel->bindParam('dat',$seValue);
$stmtquerySel->execute();
if ($stmtquerySel->rowCount() == 0) {
print json_encode(['type'=>'2']);
}else{
$galleryGrid = "";
while ($rowQuerySel = $stmtquerySel->fetch()) {
$id = $rowQuerySel['galleryId'];
$image = $rowQuerySel['image'];
$title = $rowQuerySel['galleryTitle'];
$date = $rowQuerySel['date'];
$galleryGrid .= "<div class='col-lg-4 col-sm-6'>
<div class=''>
<a href='gallerydetails.php?id=$id'>
<img src='img/$image' width='100%'>
<div>Event Name:$title</div>
<div>Date :$date</div>
</br></br>
</a>
</div>
</div>
";
}
$galleryGrid .="<div class='col-md-11 text-center'>
<button type='submit' class='btn btn-primary btn-lg' onClick=location.href='gallery.php'>Back</button>
</div>";
print json_encode(['type'=>'3', 'data'=>$galleryGrid]);
}
}
when I try it on localhost it run , but when upload to server then will get 500 internal error

Use this
print json_encode(array('type'=>'3', 'data'=>$galleryGrid));
instead of
print json_encode(['type'=>'3', 'data'=>$galleryGrid]);

Related

PHP and AJAX - like system - like the twitter system

I was making a 'like system' - like the twitter system - with PHP and AJAX. In a way that I can't understand, it applies to all buttons on the page when I press only one button. Please help.
enter image description here
index.php
<div id="rezbtn">
<span id="rezarea">
<button style="font-size:15px; float:left; <? if($sorus["soru_id"] == $rezs['soru_id'] && $user_id == $rezs['user_id']){ echo 'color:green;';}else{ echo ''; } ?>" class="btn rezle" id="rezle" type="button" title="<? echo $sorus["soru_id"]; ?>">
<span>#Rezle <? echo $rez["rez_id"]; ?></span>
</button>
</span>
</div>
ajax.php
if($rezuscount > 0)
{
echo "<span style='color:black;'>#Rezle ", $rezcount-1,"</span>";
}
else
{
echo "<span style='color:green;'>#Rezle ", $rezcount+1,"</span>";
}
like.js
$('.rezle').click(function(){
var soruid = $(this).attr("title");
$.ajax({
type:"POST",
url:"ajax.php",
data:{"soru":soruid},
success:function(e)
{
$('.rezle').html(e);
}
})
});
My codes are like this.
Your problem here is that you're referring to all elements with the class rezle and updating them all with the ajax html response:
$('.rezle').html(e);
try this:
$('.rezle').click(function(){
const rezle_button = this;
var soruid = $(this).attr("title");
$.ajax({
type:"POST",
url:"rezle.php",
data:{"soru":soruid},
success:function(e)
{
$(rezle_button).html(e);
}
})
});

Pass the dynamic variable when button is pressed

I have create this example code:
// Create connection
$conn = Connection();
$result = $conn->query("SELECT * FROM `users` WHERE 1");
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$name= $row["name"] ;
$id= $row["id"] ;
echo "<div class='media text-muted pt-3'>";
echo "<button class='mr-2 rounded btn-primary icon32 select_c'></button>";
echo "<p class='media-body pb-3 mb-0 small lh-125 border-bottom border-gray'>";
echo "<strong class='d-block text-gray-dark'>". $name ."</strong>";
echo $id;
echo "</p>";
echo "</div>";
}
I want to pass the id variable when the reference button is pressed using the post method. How can I do?
You can use value on the button then use ajax:
echo "<button class='mr-2 rounded btn-primary icon32 select_c' value='".$row["id"]."' onClick='ajaxpost(this)'></button>";
Now use Ajax:
js:
function ajaxpost(elem) {
var id = elem.value;
$.ajax({
url: "page.php",
type: "POST",
data: {
id: id
},
success: function(data) {
//what you want
}
});
}

Ajax not loading posts on live server but working on localhost

I'm trying to load posts of users from my database to the website but the ajax part isn't loading for some reason. It was working on localhost but not working on the live server. Is there some problem in the ajax code or the code written in the index page?
Here in the index page the posts_area div part isn't loading
index.php
<?php
include("includes/header.php");
if(isset($_POST['post'])){
$post = new Post($con, $userLoggedIn);
$post->submitPost($_POST['post_text'], 'none');
}
?>
<div class="main_column column">
<form class="post_form" action="index.php" method="POST">
<textarea name="post_text" id="post_text" placeholder="Got something to say?"></textarea>
<input type="submit" name="post" id="post_button" value="Post">
<hr>
</form>
<div class="posts_area"></div>
<img id="loading" src="assets/images/icons/loading.gif">
</div>
<div class="user_details column">
<h4>Popular</h4>
<div class="trends">
<?php
$query = mysqli_query($con, "SELECT * FROM trends ORDER BY hits DESC LIMIT 9");
foreach ($query as $row) {
$word = $row['title'];
$word_dot = strlen($word) >= 14 ? "..." : "";
$trimmed_word = str_split($word, 14);
$trimmed_word = $trimmed_word[0];
echo "<div style'padding: 1px'>";
echo $trimmed_word . $word_dot;
echo "<br></div><br>";
}
?>
</div>
</div>
<script>
var userLoggedIn = '<?php echo $userLoggedIn; ?>';
$(document).ready(function() {
$('#loading').show();
//Original ajax request for loading first posts
$.ajax({
url: "https://bestconnect.000webhostapp.com/includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=1&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(data) {
$('#loading').hide();
$('.posts_area').html(data);
}
});
$(window).scroll(function() {
var height = $('.posts_area').height(); //Div containing posts
var scroll_top = $(this).scrollTop();
var page = $('.posts_area').find('.nextPage').val();
var noMorePosts = $('.posts_area').find('.noMorePosts').val();
if ((document.body.scrollHeight == document.body.scrollTop + window.innerHeight) && noMorePosts == 'false') {
$('#loading').show();
var ajaxReq = $.ajax({
url: "includes/handlers/ajax_load_posts.php",
type: "POST",
data: "page=" + page + "&userLoggedIn=" + userLoggedIn,
cache:false,
success: function(response) {
$('.posts_area').find('.nextPage').remove(); //Removes current .nextpage
$('.posts_area').find('.noMorePosts').remove(); //Removes current .nextpage
$('#loading').hide();
$('.posts_area').append(response);
}
});
} //End if
return false;
}); //End (window).scroll(function())
});
</script>
</div>
ajax_load_posts.php
<?php
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['posts'])) {
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>
<?php
header("Access-Control-Allow-Origin: *");
include("../../config/config.php");
include("../classes/User.php");
include("../classes/Post.php");
$limit = 10; //Number of posts to be loaded per call
if (isset($_GET['userLoggedIn']))
{
$posts = new Post($con, $_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST, $limit);
}
?>

Success function doesn't work

I'm trying to delete image box with ajax, my class="box" doesn't disappear when i click delete but my image has been deleted from database and unlink from folder, can anyone see if somethings wrong with my code, thanks in advance!
My code :
<ul>
<?php while ($result = mysql_fetch_array($sql)) { ?>
<li class="box">
<div class="image-box">
<div class="items-image" style="background-image: url(upload/<?php echo $result['img_1']; ?>);"></div>
<p class="error" style="display: none;">Can't delete</p>
<div class="items-footer">
<a class="delete" id="<?php echo $result['img_id']; ?>"><i class="fa fa-trash fa-lg"></i></a>
</div>
</div>
</li>
<?php } ?>
</ul>
$(document).ready(function(){
$(".delete").on('click', function(evt){
var del_id = $(this).attr('id');
var prop_id = "<?php echo $ID; ?>";
$.ajax({
type:'POST',
url:'image_delete.php',
data: ({delete_id : del_id, product_id: prop_id}),
success: function(data) {
if(data == '0') {
$(".error").show();
} else if(data == '1') {
$(this).parents(".box").animate({ backgroundColor: "#003" }, "slow").animate({ opacity: "hide" }, "slow");
}
}
});
});
});
image_upload.php
<?php
include 'connect.php';
$path = "upload/";
if(isset($_POST['delete_id'])){
$delete_id = $_POST['delete_id'];
$product_id = $_POST['product_id'];
$check = mysql_query("SELECT COUNT(img_id) as cnt FROM fm_product_image WHERE p_id_img = '$product_id'") or die(mysql_error());
$getcheck = mysql_fetch_array($check);
if($getcheck['cnt'] == '1') {
echo '0';
} else {
$sql = mysql_query("SELECT img_1 FROM fm_product_image WHERE img_id = '$delete_id'") or die(mysql_error());
$result = mysql_fetch_array($sql);
$delete = $result['img_1'];
$unlink = $path.$delete;
if (unlink($unlink)) {
mysql_query("DELETE fm_product_image FROM fm_product_image WHERE img_id = '$delete_id'") or die(mysql_error());
echo '1';
} else {
echo '0';
}
}
}
?>
Use remove:
$(document).ready(function(){
$(".delete").on('click', function(evt){
var del_id = $(this).attr('id');
var prop_id = "<?php echo $ID; ?>";
var box = $(this).closest(".box");
$.ajax({
type:'POST',
url:'image_delete.php',
data: ({delete_id : del_id, product_id: prop_id}),
success: function(data) {
if(data == '0') {
$(".error").show();
} else if(data == '1') {
box.animate({ backgroundColor: "#003" }, "slow").animate({ opacity: 0 }, "slow");
box.remove();
}
}
});
});
});
note: $(this) refers to the ajax object and opacity is a value from 1 to 0

mysql ajax search query

hello friends i am making a live search with the help of ajax and mysql. the problem is that when we write something suppose a alphabet "a" then it gives live results but when i put a space and then write any alphabet suppose "a" then results does no shows up . how can we ignore the spaces in the search ?? my code is
ajax search.php
<script type="text/javascript">
$(document).ready(function(){
$(".search").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ $.trim(searchbox);
if(searchbox=='')
{
$('#display123').hide();
}
else
{
$.ajax({
type: "POST",
url: "friends/search1.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display123").html(html).show();
}
});
}return false;
});
});
</script>
mysql search1.php
<?php include($_SERVER["DOCUMENT_ROOT"]."/sexy/include/connection.php");
if($_POST)
{
$q=$_POST['searchword'];
$sql_res=mysql_query("select * from users_profile where fname like '%$q%' or Email like '%$q%' order by rand() LIMIT 10");
while($row=mysql_fetch_array($sql_res))
{
$fname=$row['fname'];
$lname=$row['lname'];
$img=$row['profile_pic'];
$country=$row['country'];
$uid=$row['uid'];
$re_fname='<b>'.$q.'</b>';
$re_lname='<b>'.$q.'</b>';
$final_fname = str_ireplace($q, $re_fname, $fname);
$final_lname = str_ireplace($q, $re_lname, $lname);
?>
<div class="display_box" >
<span><img src="<?php echo $img; ?>" width="50" height="50" style="float:left; margin-right:6px" /></span>
<div class="searchtext"><a href="profile.php?f_id=<?php echo $uid;?>"><?php echo $final_fname; ?> <br/>
<span style="font-size:10px; color:#999999"><?php echo $country; ?></span></a></div></div>
<?php
}
}
else
{
}
?>
You can trim whitespaces before using the variable in query, like:
$q= trim($_POST['searchword']); //remove whitespaces from front and end

Categories