favorite button ajax - javascript

i have problem with my ajax code it didn't work i don't know why.
here is my code:
this php code is in other page that named favourite.php
i have problem with my ajax code it didn't work i don't know why.
here is my code:
this php code is in other page that named favourite.php
$test = $_SESSION['ww'];
$x = $_SESSION['x'];
$SelectQry2 = "select * from favorites where User_Id = ".$test." and User_Post = ".$x."";
$slc = mysqli_query($link , $SelectQry2);
if (mysqli_num_rows($slc)> 0){
$DeleteQry = "DELETE from favorites where User_Post = ".$x."";
$del = mysqli_query($link , $DeleteQry);
}else{
$url = $_SERVER['REQUEST_URI'];
$InsertQry = "insert into favorites";
$InsertQry .="(`User_Id` ,`User_post`, `url`) VALUES";
$InsertQry .=" ('$test' ,'$x', '$url')";
$fav = mysqli_query($link, $InsertQry);
}
$(document).ready(function(e){
e.preventDefault();
$("button").on("click", function(){
var data = $(this).serialize();
$.ajax({
type: "POST",
data: data,
url: "favourite.php",
success: function(data){
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
});
<button>favorite</button>

Related

how to get value of each indiviual message using javascript and ajax

i am trying to create a favorite button, that when clicked will favorite the message without reload. everything is coded correctly, except i am having trouble figuring out how i will send each message's individual ID to the ajax response.
my ajax:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.ajax({
data: data,
type: "post",
url: "favorite.php?message=529", // here i put 529 as an example,
i need it to be a variable that changes based on which message has been clicked.
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
my HTML.
<form class="favourite-form" method="post">
<a class="msg-icon " href="<?php echo "reply?message=" . $row['msgid'] . ""; ?>"></a>
<button type="submit" name="fav" value="<?php echo $row['msgid'] ?>" ></button>
</form>
My php relies on the id of messages to be sent via $_GET METHOD.
my php :
$user_id = $_SESSION['active_user_id'];
extract($_GET);
$id=$_GET['message'];
$q=$db->prepare("SELECT msgid,date,text
FROM messages
WHERE to_id=? and msgid=?");
$q->bindValue(1,$user_id);
$q->bindValue(2,$id);
$q->execute();
$row2=$q->fetch();
$d=$row2['date'];
$fav_questionq=$db->prepare("SELECT *
FROM messages
LEFT JOIN users
ON messages.to_id=users.id
WHERE users.id=? AND messages.msgid=?
");
$fav_questionq->bindValue(1,$user_id);
$fav_questionq->bindValue(2,$id);
$fav_questionq->execute();
$frow=$fav_questionq->fetch();
$fquestion= $frow['text'];
$result = $db->prepare("SELECT * FROM fav_messages
WHERE username=? AND message=?");
$result->bindValue(1,$user_id);
$result->bindValue(2,$id);
$result->execute();
if($result->rowCount()== 1 )
{
$deletequery=$db->prepare("DELETE FROM fav_messages WHERE message=?");
$deletequery->bindValue(1,$id);
$deletequery->execute();
}
else
{
$insertquery = $db->prepare("INSERT INTO fav_messages (username,message,fav_question,fav_date) values(?,?,?,?)");
$insertquery->bindValue(1,$user_id);
$insertquery->bindValue(2,$id);
$insertquery->bindValue(3,$fquestion);
$insertquery->bindValue(4,$d);
$insertquery->execute();
}
?>
how can i send each message id via ajax this way.
You can do:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault();
var data = $(this).serialize();
// Here, you will get the individual id before submiting the form
var mssg_id = $(this).find('button[name="fav"]').val();
$.ajax({
data: data,
type: "post",
url: `favorite.php?message=${mssg_id}`, // It will be added to the url ES6 method
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Edit
url: "favourite.php?message="+mssg_id,
What i would do is just to add a hidden input in the form of the view, try this:
<input type="hidden" name="msgid" value="<?php echo $row['msgid' ?>" />

Jquery-ajax doesn't succeed

I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).

Ajax result show undefined

I want to ues ajax polling for show user update by followers like facebook.
So I collect this code and apply in my page, Which append only 'undefined' one after one.
What is my wrong here in my code please.
At below I give my full polling script and related file
my Table name: updateside
id - work_id - parent_id - from_id - to_id - sub - detail - img - created
..........................................................................
AI - work_id, parent_id etc. all data submit by user post form
My JavaScript
function waitForMsg(){
$.ajax({
type: "GET",
url: "upsidenew.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
if(data) {
$("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
}
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
upsidenew.php
$parent = //collect from other query
date_default_timezone_set('Asia/Dhaka');
$timestamp = date("M j, y; g:i a", time() - 2592000);
$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
$response = array();
while ($row = mysqli_fetch_array($u)) {
$response['from_id'] = $row['from_id'];
$response['parent_id'] = $row['parent_id'];
$response['to_id'] = $row['to_id'];
$response['sub'] = $row['sub'];
$response['detail'] = $row['detail'];
$response['img'] = $row['img'];
$response['time'] = $row['created'];
?><script><?php echo '(Content-Type: application/json)';?></script><?php
echo json_encode($response);
exit;
}
Add your ajax request dataType as "dataType: 'json'"
$.ajax({
type: "GET",
url: "upsidenew.php",
async: true,
cache: false,
timeout:50000,
dataType: 'json'
success: function(data){
if(data) {
$("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
}
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
if you don't set the datatype of your ajax call explicity to json you need to parse the result with:
jsondata = $.parseJSON(data);
alert(jsondata.detail);
as shown in
http://api.jquery.com/jquery.ajax/
If you're returning JSON, you shouldn't output anything other than echo json_encode($response). This line:
?><script><?php echo '(Content-Type: application/json)';?></script><?php
should be:
header('Content-type: application/json');

Prepending and overwriting a class with AJAX response in PHP

I am working on a site that has like button attached to posts made by users. I want whenever a user likes a post, the like count of that post should be replaced with current one but it is affecting the whole post.
This is code for the Like button
echo "<span class = 'likecount'>". $likes . "</span><button class='mlike pacedown'
value='".$post_id."' name = 'like' type='submit'><span class = 'buttons'>Like</span>
<span class='glyphicon glyphicon-heart'></span></button>";
And this the AJAX that gets fired whenever the button is clicked:
$(".mlike").click(function () {
$(".murconform").submit(function(e){
return false;
});
var post_id = $(this).val();
var user_id = $(".user_id").text();
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
alert ("User ID is " + user_id + " Post ID is " + post_id);
$('.likecount').html( msg );
});
});
And this is the echo result from likes.php after update the database:
echo "<span class = 'likecount'>". $count . "</span>";
The database side is working just fine.
welll your are replacing the html inside the span with a <span class = 'likecount'> again.
why don't you just echo $count from you ajax called page and only this will be replaced in success function..
try this
in you likes.php file
echo $count; //just return the count
no changes in ajax ..
//same
request.done(function( msg ) {
alert ("User ID is " + user_id + " Post ID is " + post_id);
$('.likecount').html( msg );
});
that should do the trick..
you can also change you datatype to JSON and send json as response in your php ..
updated
$(".murconform").submit(function(e){
return false;
});
$(".mlike").click(function () {
var $this=$(this);
var post_id = $(this).val();
var user_id = $(".user_id").text();
var request = $.ajax({
url: "likes.php",
type: "POST",
data: { post : post_id , user : user_id },
dataType: "html"
});
request.done(function( msg ) {
alert ("User ID is " + user_id + " Post ID is " + post_id);
$this.prev('.likecount').html( msg );
});
});

Using Ajax to change title of topic in a forum javascript/jQuery

$(function(){
var regex= /^\/t\d-/;
var a = $('.post')[0];
var b = $(a).find('.profile-icons')[0];
var c = $(b).find('.i_icon_edit')[0];
var testTitle = /^\[COMPLETED\]/i;
var d = $('.page-title').find('a')[0].innerText;
if(regex.test(window.location.pathname) && c && !testTitle.test(d)){
var ahref = c.parentNode.href.replace('http://'+window.location.hostname,'');
var complete = document.createElement('li');
complete.id="completed";
complete.setAttribute('onclick','markComplete("'+ahref+'")');
complete.innerHTML="Mark Complete";
b.appendChild(complete);
}
});
function markComplete(yhref){
$.post(yhref,function(data){
var val = $(data).find('input[name="subject"]').val();
$(data).find('input[name="subject"]').val('[COMPLETED]'+val);
$(data).find('input[name="edit_reason"]').val('User Marked Question as Completed');
$(data).find('form[name="post"]').submit();
}).done(function(){
window.location.reload();
});
}
The actual code works, just not the function markComplete I stink at Ajax as I've havent had time to teach myself any of this yet. I just need to change the title of the topic in a forum, then reload the page as to save Ajax request. The reloading works just not the Ajax. I've read the documentation at jQuery.com just not fully understanding it yet. Can anyone help me with finishing the code or any suggestions to the Ajax?
Ajax and "reload the page" should not be used in the same sentence.
With that in the clear, the easiest will be to create a pseudo-REST API via a new PHP "page" (and I'm guessing you're using PHP as you have mentined a "forum") and then to direct the data at that "page" which will "save" it.
The ajax call (from the page where the form is):
$('#form_name').submit(function(event) {
var $form = $( this ),
form_field_name1 = $form.find( "input[name='form_field_name1']" ).val(),
form_field_name2 = $form.find( "input[name='form_field_name2']" ).val();
$.ajax({
url: 'http://yourserver.com/api.php',
type: 'POST',
data: { "form_field_name1": form_field_name1, "form_field_name2" : form_field_name1 },
beforeSend: function () {
$("#output").html("Saving, please wait....");
},
success: function(data, textStatus, jqXHR) {
console.log('/API response received:', data);
var result = new Boolean(data);
if (result) {
$("#output").html("Saved.");
} else {
$("#output").html("Not saved.");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error(textStatus, errorThrown);
$("#output").html("ERROR when saving data: " + errorThrown);
}
});
event.preventDefault(); // important, so that the page doesn't reload
});
The api.php page (in short):
$form_field_name1 = $_POST['form_field_name1'];
$form_field_name2 = $_POST['form_field_name2'];
mysql_connect("localhost", "user", "pass");
mysql_select_db("db_name");
$query= "INSERT INTO `table_name` (`field_name1`,`field_name2`) VALUES ('" . $form_field_name1 . "','" . $form_field_name2 . "')";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
return $result;
Further reading: a guide for a proper PHP REST API: http://coreymaynard.com/blog/creating-a-restful-api-with-php/

Categories