0

Всем привет! Не получается Применить аякс функцию.

<?php 
            $DB = new Database();
            $likes = "";
        $likes = ($ROW['likes'] &gt; 0) ?  $ROW['likes'] : &quot;&quot; ;

    ?&gt;
    &lt;a onclick=&quot;like_post(event)&quot; href=&quot;&lt;?=ROOT?&gt;like/post/&lt;?php echo $ROW['postid'] ?&gt;&quot;&gt;&lt;img src=&quot;/icons/like.png&quot; style=&quot;height:25px&quot;&gt;&lt;?php echo $likes ?&gt;&lt;/a&gt; . 

Вышеописанный код показывает количество лайков. А аякс мне нужно применить чтобы операция выполнялась без перезагрузки страницы. Посмотрев несколько туториалов я прописал следующие строчки кода

 <script type="text/javascript">
function ajax_send(data,element){

    var ajax = new XMLHttpRequest();

    ajax.addEventListener('readystatechange', function(){

        if(ajax.readyState == 4 &amp;&amp; ajax.status == 200){

            response(ajax.responseText,element);
        }

    });

    data = JSON.stringify(data);

    ajax.open(&quot;post&quot;,&quot;&lt;?=ROOT?&gt;ajax.php&quot;,true);
    ajax.send(data);

}

function response(result,element){

    if(result != &quot;&quot;){

        var obj = JSON.parse(result);
        if(typeof obj.action != 'undefined'){

            if(obj.action == 'like_post'){

                var likes = &quot;&quot;;

                if(typeof obj.likes != 'undefined'){
                    likes = (parseInt(obj.likes) &gt; 0) ? &quot;Like(&quot; +obj.likes+ &quot;)&quot; : &quot;Like&quot; ;
                    element.innerHTML = likes;
                }

                if(typeof obj.info != 'undefined'){
                    var info_element = document.getElementById(obj.id);

                    info_element.innerHTML = obj.info;
                }
            }
            }
        }
    }
    function like_post(e){


        e.preventDefault();
        var link = e.target.href;

        var data = {};
        data.link = link;
        data.action = &quot;like_post&quot;;
        ajax_send(data,e.target);

    }

</script>

ajax.php

<?php

include("classes/autoload.php");

$data = file_get_contents("php://input"); if($data != ""){ $data = json_decode($data); }

if(isset($data->action) && $data->action == "like_post") { include "ajax/like.ajax.php"; }

like.ajax.php

<?php

include("classes/autoload.php");

$URL = split_url_from_string($data->link);

$_GET['type'] = isset($URL[5]) ? $URL[5] : null; $_GET['id'] = isset($URL[6]) ? $URL[6] : null;

$_SESSION['userid'] = isset($_SESSION['userid']) ? $_SESSION['userid'] : 0; $login = new Login; $user_data = $login->check_login($_SESSION['userid'],false);

//check if not logged in if($_SESSION['userid'] == 0){

    $obj = (object)[];
    $obj-&gt;action = &quot;like_post&quot;;

    echo json_encode($obj);
    die;

}

/* $query_string = explode("?", $data->link); $query_string = end($query_string);

$str = explode("&", $query_string);

foreach ($str as $value) { # code... $value = explode("=", $value); $_GET[$value[0]] = $value[1]; } */

$_GET['id'] = addslashes($_GET['id']); $_GET['type'] = addslashes($_GET['type']);

if(isset($_GET['type']) &amp;&amp; isset($_GET['id'])){

    $post = new Post();

    if(is_numeric($_GET['id'])){

        $allowed[] = 'post';
        $allowed[] = 'user';
        $allowed[] = 'comment';

        if(in_array($_GET['type'], $allowed)){

            $post = new Post();
            $user_class = new User();
            $post-&gt;like_post($_GET['id'],$_GET['type'],$_SESSION['userid']);

            if($_GET['type'] == &quot;user&quot;){
                $user_class-&gt;follow_user($_GET['id'],$_GET['type'],$_SESSION['userid']);

            }

        }

    }

    //read likes
    $likes = $post-&gt;get_likes($_GET['id'],$_GET['type']);


    //create info
    ///////////////// 
    $likes = array();
    $info = &quot;&quot;;

            $i_liked = false;
            if(isset($_SESSION['userid'])){

                $DB = new Database();

                $sql = &quot;select likes from likes where type='$type' &amp;&amp; contentid = '$id' limit 1&quot;;
                $result = $DB-&gt;read($sql);
                if(is_array($result)){

                    $likes = json_decode($result[0]['likes'],true);

                    $user_ids = array_column($likes, &quot;userid&quot;);

                    if(in_array($_SESSION['userid'], $user_ids)){
                        $i_liked = true;
                    }
                }

            }

            $like_count = count($likes);

            if($like_count &gt; 0){

                $info .= &quot;&lt;a id='info_$_GET[postid]' href='likes.php?type=post&amp;id=$_GET[postid]'&gt;&quot;;
                $info .= &quot;&lt;br/&gt;&quot;;

                if($like_count == 1){

                    if($i_liked){
                        $info .= &quot;&lt;div style='text-align:left;'&gt;You liked this post &lt;/div&gt;&quot;;
                    }else{
                        $info .= &quot;&lt;div style='text-align:left;'&gt; 1 person liked this post &lt;/div&gt;&quot;;
                    }
                }else{

                    if($i_liked){

                        $text = &quot;others&quot;;
                        if($like_count - 1 == 1){
                            $text = &quot;other&quot;;
                        }
                        $info .= &quot;&lt;div style='text-align:left;'&gt; You and &quot; . ($like_count - 1) . &quot; $text liked this post &lt;/div&gt;&quot;;
                    }else{
                        $info .= &quot;&lt;div style='text-align:left;'&gt;&quot; . $like_count . &quot; other liked this post &lt;/div&gt;&quot;;
                    }
                }


            }

         /////////////////////////
    $obj = (object)[];
    $obj-&gt;likes = count($likes);
    $obj-&gt;action = &quot;like_post&quot;;
    $obj-&gt;info = $info;
    $obj-&gt;id = &quot;info_$_GET[id]&quot;;

    echo json_encode($obj);


}

Ошибка заключается в том что при нажатии на эту ссылку аякс не получает данные поста как url и id.

<a onclick="like_post(event)" href="<?=ROOT?>like/post/<?php echo $ROW['postid'] ?>"><img src="/icons/like.png" style="height:25px"><?php echo $likes ?></a> . 

По последовательности своего написания я могу сказать что я допустил ошибку либо здесь

   $obj = (object)[];
    $obj->likes = count($likes);
    $obj->action = "like_post";
    $obj->info = $info;
    $obj->id = "info_$_GET[id]";
echo json_encode($obj);

Либо здесь

 <script type="text/javascript">
function ajax_send(data,element){

    var ajax = new XMLHttpRequest();

    ajax.addEventListener('readystatechange', function(){

        if(ajax.readyState == 4 &amp;&amp; ajax.status == 200){

            response(ajax.responseText,element);
        }

    });

    data = JSON.stringify(data);

    ajax.open(&quot;post&quot;,&quot;&lt;?=ROOT?&gt;ajax.php&quot;,true);
    ajax.send(data);

}

function response(result,element){

    if(result != &quot;&quot;){

        var obj = JSON.parse(result);
        if(typeof obj.action != 'undefined'){

            if(obj.action == 'like_post'){

                var likes = &quot;&quot;;

                if(typeof obj.likes != 'undefined'){
                    likes = (parseInt(obj.likes) &gt; 0) ? &quot;Like(&quot; +obj.likes+ &quot;)&quot; : &quot;Like&quot; ;
                    element.innerHTML = likes;
                }

                if(typeof obj.info != 'undefined'){
                    var info_element = document.getElementById(obj.id);

                    info_element.innerHTML = obj.info;
                }
            }
            }
        }
    }
    function like_post(e){


        e.preventDefault();
        var link = e.target.href;

        var data = {};
        data.link = link;
        data.action = &quot;like_post&quot;;
        ajax_send(data,e.target);

    }

</script>

Сколько искал никак не смог найти в чём заключается ошибка. Сам браузер обрабатывает аякс функции.

  • "Вышеописанный код" покажет только ошибку Undefined variable $ROW. Думаю, все остальные проблемы такого же плана. – Ипатьев Feb 20 '24 at 09:10
  • "что я допустил ошибку либо здесь ..... либо здесь" --- не надо гадать. Надо искать ошибку профессионально. См. дубликаты. В частности включи отображение ошибок в коде. И пробуй дебажить – Алексей Шиманский Feb 20 '24 at 09:40
  • "что я допустил ошибку либо здесь" -- ну как минимум вот это "info_$_GET[id]" будет работать некорректно, замените на "info_" . $_GET['id'] или на "info_{$_GET['id']}". – Simon Feb 20 '24 at 09:47

0 Answers0