AJAX Request For Like Link Not Working - javascript

I'm working on a like system with PDO, PHP and AJAX.
But, its not working.
Here's the PHP Code.
$get_likes_sql = "SELECT * FROM `likes` WHERE post_id=:post_id AND liker_id=:my_id";
$get_likes = $db->prepare($get_likes_sql);
$get_likes->execute(array(
":post_id" => $post_id,
":my_id" => $my_id
));
$likes_numrows = $get_likes->rowCount();
if ($likes_numrows == 0) {
echo "<a class='like-link' id='$post_id' title='Like'>Like</a>";
} else {
echo "<a class='like-link' id='$post_id' title='Unlike'>Unlike</a>";
}
Here's the AJAX script.
$(document).ready(function(){
$(document).on('click', '.like-link', function(){
if($(this).attr('title')=='Like'){
$.post('ajax.like.php',{pid:$(this).attr('id'),action:'like'},function(){
$(this).text('Unlike');
$(this).attr('title','Unlike');
});
}else{
if($(this).attr('title')=='Unlike'){
$.post('ajax.like.php',{pid:$(this).attr('id'),action:'unlike'},function(){
$(this).text('Like');
$(this).attr('title','Like');
});
}
}
});
});
The Problem is that nothing happens after clicking on like link neither on unlike link.

This is where debugging comes into place. First off, let's see if the AJAX call succeeds. Put in console.log('foo'); statements, with different strings to trace what the JavaScript code does. If the AJAX call is being made, you should be able to see it in the debugger as well.
After that, you should be able to see the results going into the PHP script. You can dump the variables at the top var_dump($_POST);exit;.
There should also be some code where the $_POST variable is linked to $post_id and $my_id.
Since this isn't the complete code example, I can only help you this much. Please let us know if you managed to debug it. Else the complete code example would be nice for us to help you out some more.

use Console.log function to see which part of your code is executed and which is not

Related

Refresh page when value is = 1

Hello im trying make a system for when on value on my datebase is 1 my index page refresh. this is my code!
All PHP code works, only my index.php not refresh.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
$("#numseiCategoria").html(data);
window.setTimeout(update);
})
}, 5000);
</script>
loadMensagens.php
<?php
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET condicao='$condicao'");
echo "
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
}
?>
updateMensagens.php
<script>
$(document).ready(function(){
location.reload();
});
</script>
At a glance there are a couple of reasons your page isn't reloading. Firstly, the reload method being wrapped in that .ready() probably prevents it from being called, as I believe the ready event only fires when the DOM first loads.
$(document).ready(function(){
location.reload(); // Will never fire if script is added to DOM after initial load.
});
But I think there's another issue as your code simply appends this HTML...
<div id='a'></div>
<script>
$.ajax({url:'updateMensagens.php', success:function(result){
$('#a').html(result)
}});
</script>";
...onto the end of #numseiCategoria's inner text, which probably doesn't make the browser execute the script anyway (I'm assuming that jQuery's .html() is basically an alias for innerHTML here, I can't be bothered to go and check).
But, in terms of good practices, there's more to it than that...
updateMensagens.php seems to be incredibly redundant, unless there's more to it than you're showing. Let's have a think about how you intended it to work, ignoring the fact that your method of adding scripts to the page is incorrect.
You have your main script in index.php, which sends a get request to loadMensagens.php, which does some database stuff. So far so good...
Your PHP script then echoes some JS, which your main script appends to the page. This JS tells the client to send another get request, this time to updateMensagens.php, and to once again append the result to the page.
This second request returns only a script telling the browser to reload the page. And now we've run into problems.
This is a really awkward and long-winded way to go about this, especially once you try to scale the approach up to larger projects. You're trying to do certain things with PHP which are much more easily done with JS. I'll briefly highlight a couple of things for you.
Firstly, echoing HTML back to the client like that is not great, it gets very unwieldy very quickly. It's much cleaner to return any necessary data to the front end as JSON (or a similar format) and handle generating HTML with JS. jQuery makes generating complex documents rather easy, as you're already using it I'd recommend that approach.
Secondly, this system of using ajax requests to fetch a script from the server to append to the page to perform a simple action with JavaScript is diabolical. Please see my untested, 4AM alternative.
index.php
<script>
inverval_timer = setInterval(function update() {
$.get("base_de_dados/update/loadMensagens.php", function(data) {
let res = JSON.parse(data);
if(res.condiciao === true) {
location.reload();
}
});
}, 5000);
</script>
loadMensagens.php
<?php
$return = [];
include_once '../bdados.php';
$fila = $conn->query("SELECT * FROM tickets_update");
while($Filas = $fila->fetch_assoc()){
$condicao = $Filas['condicao'];
}
if($condicao == 1){
$return['condicao'] = true;
$condicao = 0;
$queryAtualizar = $conn->query("UPDATE tickets_update SET
condicao='$condicao'");
} else {
$return['condicao'] = false;
}
echo json_encode($return);
As an addendum, you seem to be using setTimeout wrong. On one hand I'm quite sure the method is supposed to take 2 arguments, but on the other hand I'm not sure why it's being used at all.
Goodnight.

Minor difficulties with Ajax and PHP interaction

I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>

How do you assign values to the results of a jquery/ajax post?

I'm posting data to a php page using jquery. I want to then have the response from the page be able to be put into php variables on the original page. I don't want to append a DIV or show the results in the HTML. (This seems to be the only thing people do with post.)
Here's the jquery:
$(document).ready(function ()
{
$('#drpdown').change(function()
{
drpdownval=$('#drpdown').val();
$.post("page2.php",{incomingval:drpdownval},function(result))};
});
});
PHP page2.php:
<?php
$valtoworkwith = $_REQUEST['incomingval'];
......../// do something
?>
I want to then do something on page2.php then send specific values back to the jquery to work with. How? How do I assign them a name or separate them out??
EDIT
My jquery needed a number and not text.
Here's the jquery:
$(document).ready(function ()
{
$('#drpdown').change(function()
{
drpdownval=$('#drpdown').val();
$.post("page2.php",{incomingval:drpdownval},function(result){
if(result != 1){ ///could not put result !="hello" or != hello
$("#signup").overlay().load();
}
)};
});
});
Simply go here, it's as clear as it can get...
https://api.jquery.com/jQuery.ajax/
That's the documentation page for $.ajax, and if you scroll down you will have excellent examples you can start from.
Use JSON to get your inter-connectivity going, meaning the data exchange between client and server entirely through AJAX. Here's a link to a StackOverflow answer which goes into detail about how to make that happen, using PHP for the back end:
jQuery AJAX Call to PHP Script with JSON Return
Are you trying to do something like that?
if (!empty($_POST['incomingval'])){
$valtoworkwith = $_POST['incomingval'];
//do some stuff
echo $valtoworkwith;
}
Or if you want to sent back a JSON
<?php
function doSomeStuff($input) {
//instead of that do some stuff and return back something that makes sense
$output = $input;
//
return $output;
}
if (!empty($_POST['incomingval'])){
header('Content-Type: application/json');
$valtoworkwith = $_POST['incomingval'];
$res = doSomeStuff($valtoworkwith);
$data = array('incomingval' => $valtoworkwith, 'response' => $res);
echo json_encode($data);
}
?>
I hope that helped you because the answer it self was kind of vague.
Tested with postman
The in JS you can do with a promise
$(document).ready(function ()
{
$('#drpdown').change(function()
{
drpdownval=$('#drpdown').val();
$.post("page2.php",{incomingval:drpdownval})
.then(function(data){ //look how awesome the promise looks
console.log(data.response); //do something with it
})
});
});

Ajax and jquery not sending data correctly to php

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Javascript echos PHP command, not PHP variable

The jquery code:
$('.up_IMG').click(function() {
if (notLoggedIn()) return false;
alert('Got to here');
});
The function (attempt #1): in quotes:
function notLoggedIn() {
alert('here');
logged_in = "<?php echo json_encode($logged_in); ?>";
alert('Logged in: ' + logged_in);
}
OR json_encoded (attempt #2):
function notLoggedIn() {
alert('here');
logged_in = <?php echo json_encode($logged_in); ?>;
alert('Logged in: ' + logged_in);
}
When attempt #1 fn is called, the first code block's alert displays:
The second code block does nothing.
The PHP variable does exist and has the value zero.
Any thoughts as to what's happening?
If you're calling this code with a 'click', at that point it's too late for PHP to help you asynchronously.
PHP runs when the page is loaded, not after. It's a matter of timing. PHP can never output something that doesn't exist yet, so it will always be blank.
Explanation of Solution:
The question was caused by a misunderstanding of the relationship between PHP and javascript.
Once the page has rendered (that is, inside jQuery's $(document).ready()), all PHP regular variables no longer exist. The PHP super-variables exist (such as $_SESSION, but not $logged_in.
To possible solutions:
Store logged-in value in a super-global: e.g. $_SESSION['logged-in'], or
Use AJAX inside the javascript $(document).ready() to query PHP if the user is logged in, and receive the answer in the AJAX function's success: function.
Simple explanation of AJAX and how it works

Categories