Ajax result show undefined - javascript

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');

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' ?>" />

favorite button ajax

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>

PHP headers always give error Undefined Index even using $_SERVER global

I am performing an ajax request cross domain. I have been trying to use functions that return the headers in an array only to find that I get Undefined Index even though I can return their values in my ajax request and print them the screen.
I have found some posts on SO that said I should be using $_SERVER globals. So I switched to that method only to get the same results.
Here is my jQuery:
setTimeout(function() {
jQuery.ajax({
url: 'http://something.com',
type:"POST",
dataType:"json",
crossDomain:true,
contentType:"application/json",
data: jsonData,
processData:false,
cache:false,
beforeSend: function( xhr ) {
xhr.setRequestHeader("Authorization",api_key[index]);
xhr.setRequestHeader("Action","PUSH");
},
success: function(data) {
alert(data.action);
alert(data.platform + ' : ' + data.message + ' : ' + data.app_name );
if(data.message == 'success')
{
jQuery('#hollmanPNs_send_push div#hollmanPNs_progressbar' + index).progressbar("value",100);
//add message to the paragraph for app name
jQuery('#hollmanPNs_send_push p#hollmanPNs_paragraph' + index).append(': Complete');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert( 'We had an error: ' + textStatus + errorThrown );
}
}).fail(function() {
alert( 'We had a failed AJAX call.');
});//end ajax
}, index * 5000);//end timeout function
And here is what I am using for PHP:
if($_SERVER['HTTP_ACTION'] != '')
{
//Do Something
}
I have tried switching to:
xhr.setRequestHeader("X-Action","PUSH");
and
$_SERVER['HTTP_X_ACTION']
with the same results. Only I was not able to return them to my ajax request.
I am using PHP 5.3.3.
I am also using this function which I change depending on the different headers I am trying at the time:
header('Access-Control-Allow-Headers: Action, Authorization, Content-Type');
You'll want to get the headers a different way like so:
$headers = getallheaders();
if(array_key_exists('Action', $headers) && $headers['Action'] != '')
{
//Do Something
}

jQuery's JSON Request

I'm trying to send an AJAX request to a php file, and I want the php file to respond with a JSON object, however the AJAX function is continually failing when declare that I specifically want JSON returned. Any help will greatly be appreciated.
this is my ajax function
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'json',
success: function(msg){
//var content = data.substr(0, data.indexOf('<'));
populateMessages(msg);
},
error: function(){
alert("ERROR");
}
});
}
and this is the relevant code for the php file
$message_links[] = array();
.....
while($run_message = mysql_fetch_array($message_query)){
$from_id = $run_message['from_id'];
$message = $run_message['message'];
$user_query = mysql_query("SELECT user_name FROM accounts WHERE id=$from_id");
$run_user = mysql_fetch_array($user_query);
$from_username = $run_user['user_name'];
$message_links[] = array("Hash" => "{$hash}", "From" => "{$from_username}", "Message" => "{$message}");
// is that not valid json notation???
}
}
echo json_encode( $message_links, JSON_FORCE_OBJECT);
//$arr = array("a" => "1", "b" => "2");
//echo json_encode($arr);
UPDATE:
Well, I ended up switching the dataType request to 'html' and I am now able to actually access these values via JSON, however, I would still like to know why the php file was not returning correct JSON notation. Any insight would be awesome, cheers.
function getMessages(){
$.ajax({
type: 'POST',
url: 'viewInbox',
dataType: 'html',
success:function(msg){
var content = msg.substr(0, msg.indexOf('<'));
msg = JSON.parse(content);
populateMessages(msg);
},
error: function(xhr, textStatus, errorThrown) {
alert(errorThrown);
alert(textStatus);
alert(xhr);
}
});
}
function populateMessages(data){
var out = '';
var json;
for (var i in data){
var my_string = JSON.stringify(data[i],null,0);
json = JSON.parse(my_string);
alert(json.Hash);
out += i + ': ' + my_string + '\n';
}
alert(out);
}
You need to set the header as json type before your echo in PHP:
header('Content-Type: application/json');

Use result of AJAX call for FullCalendarEvents?

I currently have this in my event drop:
$.ajax({
type: "POST",
url: "CalendarServices.aspx/UpdateDrop",
data: 'id=' + event.realid + '&start=' + $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd') + '&resource=' + event.resource,
success: function(data) {
$('#calendar').fullCalendar('refetchEvents');
},
error: function() {
$('#calendar').fullCalendar('refetchEvents');
}
});
This is effectively 2 ajax calls. I could easily return events in my first ajax call and populate the calendar with them. Is there some way I could do that?
Thanks
This is what I used and it worked:
eventDrop: function(event,dayDelta,minuteDelta,allDay) {
var id = event.id.toString();
var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd");
url = 'updateevent.php';
alert (url);
$.ajax({
type: "POST",
url: url,
data: {id:id, startDate:start},
success: function(){
$('#calendar').fullCalendar( 'refetchEvents' );
alert( "Success!" );
},
error: function(){
$('#calendar').fullCalendar( 'refetchEvents' );
alert( "Failed!" );
}
});
and this is my updateevent.php
<?php
//..... connection up top
$r = mysql_connect($host, $user, $pass);
$r2 = mysql_select_db($db);
$id = $_POST['id'];
$startDate = $_POST['startDate'];
mysql_query("UPDATE ecc_events SET startDate= '$startDate' WHERE id= '$id' LIMIT 1; ");
?>

Categories