JQuery AJAX call gives success, but response undefined - jquery-ajaxq

I have a rudimentary page from which I am calling a PHP service--using an AJAX call--to get an RSS feed and display it in a DIV tag.
I have a PHP page that returns the RSS feed as a JSON array. I have confirmed that the service works, as I can run it from the browser and get appropriate output.
But when I run it from the AJAX call, I get success, but undefined response. I have tried putting a callback function, but no joy. I'm sure the solution is pretty simple.
Here is the PHP page (TestService.php)
<?php
header('Content-Type: application/json');
$url = $_REQUEST['sUrl'];
$year = $_REQUEST['getYear'];
$rss = simplexml_load_file($url);
$outlist = array();
//echo json_encode($outlist);
$i = 0;
foreach ($rss->channel->item as $item) {
$i = $i + 1;
$yr = date('Y', strtotime($item->pubDate));
if ($yr == $year && $i < 5) {
$outlist[] = array('title' => $item->title,
'pubDate' => $item->pubDate,
'description' => $item->description);
}
}
//$serializedList = serialized($outlist);
$encodedList = json_encode($outlist);
echo $encodedList;
?>
Here is the HTML (TestPage.html):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery RSS Demo</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
//set the initial URL call
var sNewsUrl = "http://rss.cnn.com/rss/cnn_topstories.rss?xml";
var today = new Date();
var curYear = today.getFullYear();
for (var yr = curYear; yr >= 2017; yr--) {
$('#SelectYear').append("<option>" + yr + "</option>");
}
$('#news').html();
$('#news').append("<li>" + sNewsUrl + "</li>");
$.ajax({
type: "POST",
url: "TestService.php",
contentType: "application/json; charset=utf-8",
data: "{ 'sUrl': '" + sNewsUrl + "', 'getYear': '" +
curYear + "' }",
dataType: "json",
success: function (response) {
var jsonData = JSON.parse(response.d);
$('#news').empty();
if (jsonData.length <= 0)
$('#divNews').hide();
else {
$('#divNews').show();
for (var i = 0; i < jsonData.length; i++) {
if (i < 3)
$('#news').append("<li>" +
jsonData[i].pubDate +
" <a href='" + jsonData[i].link
+ "' target='_blank'>" +
jsonData[i].title + "</a>" + "
</li>");
}
}
},
error: function (xhr, status, error) {
//debugger;
alert("Result: " + status + " " + error + " " +
xhr.status + " " + xhr.statusText)
}
});
});
<div id="divNews">
News:<br />
<ul id="news"></ul>
</div>
</body>
</html>

Related

How to fetch socket.on function in frontend? The Event is triggered and processed. I'm using socket.io, NodeJS server, and Redis.io

*FrontEnd
As you can see in the code. I'm trying to make a Chat Application. The Message I'm sending is triggered and my Event is being Processed. But the problem is I'm not able to catch message from receiver side. I'm a stage Beginner developer and making application via youtube tutorials. Thankyou...
<script>
$(function (){
let $chatInput = $(".chat-input");
let $chatInputToolbar = $(".chat-input-toolbar");
let $chatBody = $(".chat-body");
let $messageWrapper = $("#messageWrapper");
let user_id = "{{ auth()->user()->id }}";
let ip_address = 'http://127.0.0.1';
let socket_port = '8005';
let socket = io(ip_address + ':' + socket_port);
let friendId = "{{ $friendInfo->id }}";
socket.on('connect', function() {
socket.emit('user_connected', user_id);
});
socket.on('updateUserStatus', (data) => {
let $userStatusIcon = $('.user-status-icon ');
$userStatusIcon.removeClass('text-success');
$userStatusIcon.attr('title', 'Away');
$.each(data, function (key, val) {
if (val !== null && val !== 0) {
let $userIcon = $(".user-icon-"+key);
$userIcon.addClass('text-success');
$userIcon.attr('title','Online');
}
});
});
$chatInput.keypress(function (e) {
let message = $(this).html(); //text
if (e.which === 13 && !e.shiftKey) {
$chatInput.html("");
sendMessage(message);
return false;
}
});
function sendMessage(message) {
let url = "{{ route('message.send-message') }}";
let form = $(this);
let formData = new FormData();
let token = "{{ csrf_token() }}";
formData.append('message', message);
formData.append('_token', token);
formData.append('receiver_id', friendId);
appendMessageToSender(message);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'JSON',
success: function (response) {
if (response.success) {
console.log(response.data);
}
}
});
}
function appendMessageToSender(message) {
let name = '{{ $myInfo->name }}';
let image = '{!! makeImageFromName($myInfo->name) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500"
title="'+getCurrentDateTime()+'">\n' +
getCurrentTime()+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' +
message +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-item-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
function appendMessageToReceiver(message) {
let name = '{{ $friendInfo->name }}';
let image = '{!! makeImageFromName($friendInfo->name) !!}';
let userInfo = '<div class="col-md-12 user-info">\n' +
'<div class="chat-image">\n' + image +
'</div>\n' +
'\n' +
'<div class="chat-name font-weight-bold">\n' +
name +
'<span class="small time text-gray-500"
title="'+dateFormat(message.created_at)+'">\n' +
timeFormat(message.created_at)+'</span>\n' +
'</div>\n' +
'</div>\n';
let messageContent = '<div class="col-md-12 message-content">\n' +
'<div class="message-text">\n' + message.content +
'</div>\n' +
'</div>';
let newMessage = '<div class="row message align-items-center mb-2">'
+userInfo + messageContent +
'</div>';
$messageWrapper.append(newMessage);
}
{
appendMessageToReceiver(message);
});
I think I'm missing something in the socket.on function:
socket.on("private-channel:App\Events\PrivateMessageEvent", function (message)
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message)
{
appendMessageToReceiver(message);
});
});
BackEnd Server
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http, {
cors: {
origin: "*",
}
});
var Redis = require('ioredis');
var redis = new Redis();
var users = [];
http.listen(8005, function() {
console.log('Listening to port 8005');
});
redis.subscribe('private-channel', function() {
console.log('subscribed to private channel');
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
console.log(message);
if (channel == 'private-channel') {
let data = message.data.data;
let receiver_id = data.receiver_id;
let event = message.event;
io.to('${users[receiver_id]}').emit(channel + ':' + event, data);
}
});
io.on('connection', function (socket) {
socket.on("user_connected", function (user_id) {
users[user_id] = socket.id;
io.emit('updateUserStatus', users);
console.log("user connected "+ user_id);
});
socket.on('disconnect', function() {
var i = users.indexOf(socket.id);
users.splice(i, 1, 0);
io.emit('updateUserStatus', users);
console.log('users');
});
});
PrivateMessageEvent
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class PrivateMessageEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
Public $data;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('private-channel');
}
.env
Here's is my .env file.
APP_NAME=chat_application
APP_ENV=local
//App_key
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=chat_application
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=redis
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=database
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}
"
I've noticed one issue in the event emitting in your server side code, here is the code which emits the socket events
io.to('${users[receiver_id]}').emit(channel + ':' + event, data);
So, you trying to use string interpolation and above syntax is incorrect. Basically, this is just a string '${users[receiver_id]}'. This need to be changed to `${users[receiver_id]}`, and below is the updated code
io.to(`${users[receiver_id]}`).emit(channel + ':' + event, data);
So, when using string interpolation you need to use back ticks instead of single quotes.
And another point is make sure, your channel + ':' + event in io.to('${users[receiver_id]}').emit(channel + ':' + event, data); is same as the client event in your client side code - "private-channel:App\\Events\\PrivateMessageEvent",
socket.on("private-channel:App\\Events\\PrivateMessageEvent", function (message) {
appendMessageToReceiver(message);
});

How do I retrieve the URL of a file hosted on Parse-Server through Javascript?

My code so far:
<script type="text/javascript">
var username = sessionStorage.getItem('username', username);
var password = sessionStorage.getItem('password', password);
var Image = Parse.Object.extend("Image");
var query = new Parse.Query(Image);
query.equalTo("username", username);
query.descending("createdAt");
query.find({
success: function(results) {
alert("Successfully retrieved " + results.length + " images.");
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i];
var url = (object.get("image").url);
var createdAt = (object.get("createdAt"));
var image = object.get("image");
alert(url + object.id + createdAt + username + image);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
All variables return the expected values except "image" which returns [Object object] and url which returns function url(){ return this._url;}
in order to get the file URL you need to do the following :
var image = object.get("image"); // here you have ParseFile
var imageUrl = image.url(); // now you have the file URL

converting countdown seconds to hours

I have a countdown timer to hide the div then shows another div. i have done this by seconds well , but i want to convert the seconds to minutes and hours.
how can i do this?
pre thanks to anyone answers my question ...
this is my code:
var countDown = 9000;
var i = setInterval(function () {
var b1 = document.getElementById('box1');
var b2 = document.getElementById('box2');
if(countDown === 1) {
if(b1['style'].display == 'none') {
b1['style'].display = 'block';
b2['style'].display = 'none';
} else {
b1['style'].display = 'none';
b2['style'].display = 'block';
}
clearInterval(i);
}
countDown--;
b1.innerHTML = countDown;
}, 1000);
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<div id="box1">9000</div>
<div style="display:none" id="box2">div2</div>
</body>
</html>
Example : https://jsfiddle.net/306qtxot/4/
You can use this Jquery:
var countDown = 9000;
var i = setInterval(function () {
var b1 = document.getElementById('box1');
var b2 = document.getElementById('box2');
if(countDown === 1) {
if(b1['style'].display == 'none') {
b1['style'].display = 'block';
b2['style'].display = 'none';
} else {
b1['style'].display = 'none';
b2['style'].display = 'block';
}
clearInterval(i);
}
countDown--;
//This section convert "seconds" to hour And minute And second
var hour=Math.floor(countDown/3600);
var min=Math.floor(countDown%3600/60);
var sec=Math.floor(countDown%3600%60);
//Format : hh:mm:ss
b1.innerHTML = (hour=hour<10?"0"+hour:hour) + " : " + (min=min<10?"0"+min:min) + " : " + (sec=sec<10?"0"+sec:sec);
}, 1000);

formData.append() not working - checked in Chrome,Mozilla, IE

Am using Jquery FormData for the first time, but seems am missing something. In the JS - postAjax method, when new FormData() is called, it just skips the remaining lines and goes to the end of the function without any errors. What am I doing wrong here?
template.js //script files in this order
<script src="js/jquery-2.1.0.js"></script>
<script src="js/jquery.form.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/bootstrapValidator.js"></script>
<script src="js/hemoncCBCFunctions.js"></script>
<script src="js/validations.js"></script>
JSP
<form name ="newSectionSubmitForm" id="newSectionSubmitForm" class="form-horizontal" role="form" method="post" ENCTYPE="multipart/form-data">
<table>
<tr>
<td>
<input type="file" id='imageFile0' name='imageFile0' class="form-control" />
</td>
</tr>
</table>
<form>
JS
function submitNewSection(targetUrl, form) {
postAjaxData(null, 'content', targetUrl, form, null, null);
}
function postAjaxData(initiatingElement, targetElement, targetUrl, form,
additionalParamMap, successCallback) {
var $targetElement = $('#' + targetElement);
var serializedFormData;
serializedFormData = $('#' + form).serialize();
for ( var j in additionalParamMap) {
serializedFormData += "&" + j + "=" + additionalParamMap[j];
}
alert('serialized form data ' + serializedFormData);
var formData = new FormData(serializedFormData);//**exits the function no errors**
formData.append("file", $('#imageFile0').files[0]);
alert('serialized form data ' + formData);
$.ajax({
type : "POST",
cache : false,
data : formData,
url : targetUrl,
success : function(data) {
processRedirect(data);
$targetElement.html(data);
$targetElement.show();
if (successCallback != null) {
successCallback(data);
}
},
error : function(xhr, httpRequest, textStatus, errorThrown) {
var errorId = xhr.getResponseHeader("errorId");
var errorMsg = xhr.getResponseHeader("errorMessage");
if (errorId != null && errorId != undefined) {
$("#page_error").html(
"An unexpected error has occurred. Error Id: "
+ errorId);
} else {
$("#page_error").html("An unexpected error has occurred.");
}
},
});
Controller File (however the code does not reach here)
#RequestMapping(value = "/submitNewSection.html")
public String submitNewSection( MultipartHttpServletRequest req, HttpServletRequest request, Model model) {
Iterator<String> itr = req.getFileNames();
MultipartFile mpf = req.getFile(itr.next());
System.out.println("file name " + mpf.getOriginalFilename() +" uploaded!");
}
Thanks so much.

Why is Google login returning “immediate_failed” even when user logged somewhere else?

I am aware of similar questions but still have the problem:
"immediate_failed" - Could not automatially log in the user
Google login callback always shows "immediate_failed"
Google plus signin "immediate_failed" error
I also understand that the sign in callback is called initially even without request to check if the user is logged somewhere else. The “immediate_failed” is also returned correctly when the user is logged out within the browser from other Google services. However, when the user is in fact logged in Gmail in another Tab, I still receive the same failure in javascript.
This is the plain Google login code example. What could be wrong?. Some information:
Credentials:
Redirect URIs http://localhost:8000/beta/oauth2callback
Javascript Origins http://localhost:8000
Relevant Code (Javascript only sign in, copied and only slightly modified from: https://developers.google.com/+/web/signin/add-button)
Button declaration:
<div class="g-signin" data-callback="loginFinished"
data-clientid="268583......"
data-scope="profile email"
data-cookiepolicy="single_host_origin"
>
Callback:
var loginFinished = function(authResult) {
console.log(authResult)
if (authResult['code']) {
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// ..
'}</code></pre>';
toggleDiv('signin-button');
} else {
document.getElementById('oauth2-results').innerHTML =
'Error';
}
};
Full code (served locally by Apache on :8000/test0/signin_demo_basic.htm)
<html>
<head>
<title>Google+ Sign-in button demo</title>
<style type="text/css">
html, body { margin: 0; padding:0;}
#signin-button {
padding: 5px;
}
#oauth2-results pre { margin: 0; padding:0;}
.hide { display: none;}
.show { display: block;}
</style>
<script type="text/javascript">
var loginFinished = function(authResult) {
console.log(authResult)
if (authResult['code']) {
var el = document.getElementById('oauth2-results');
var label = '';
toggleDiv('oauth2-results');
if (authResult['status']['signed_in']) {
label = 'User granted access:';
gapi.auth.setToken(authResult);
} else {
label = 'Access denied: ' + authResult['error'];
}
el.innerHTML =
label + '<pre class="prettyprint"><code>' +
// JSON.stringify doesn't work in IE8.
'{<br />' +
' "id_token" : "' + authResult['id_token'] +'",<br />' +
' "access_token" : "' + authResult['access_token'] + '",<br />' +
' "state" : "' + authResult['state'] + '",<br />' +
' "expires_in" : "' + authResult['expires_in'] + '",<br />' +
' "error" : "' + authResult['error'] + '",<br />' +
' "error_description" : "' + authResult['error_description'] + '",<br />' +
' "authUser" : "' + authResult['authuser'] + '",<br />' +
' "status" : {"' + '<br />' +
' "google_logged_in" : "' + authResult['status']['google_logged_in'] + '",<br />' +
' "method" : "' + authResult['status']['method'] + '",<br />' +
' "signed_in" : "' + authResult['status']['signed_in'] + '"<br />' +
' }<br />' +
'}</code></pre>';
toggleDiv('signin-button');
} else {
document.getElementById('oauth2-results').innerHTML =
'Error';
}
};
function toggleDiv(id) {
var div = document.getElementById(id);
if (div.getAttribute('class') == 'hide') {
div.setAttribute('class', 'show');
} else {
div.setAttribute('class', 'hide');
}
}
</script>
<script src="https://plus.google.com/js/client:platform.js" type="text/javascript"></script>
</head>
<body>
<div id="signin-button" class="show">
<div class="g-signin" data-callback="loginFinished"
data-clientid="268583......"
data-scope="profile email"
data-cookiepolicy="single_host_origin"
>
</div>
</div>
<div id="oauth2-results" class="hide"></div>
<div>Reload the example or open in a new window</div>
</body>
</html>
After painfully checking my code and looking for answers I found out that in my Firefox the option to accept third party cookies was disabled. To solve the problem, in Firefox go to Options > Privacy and set "accept third party cookies" to visited. Please inform yourself about what accepting third party cookies implies.
For anybody who has a problem only on IE, set the immediate key within window.gapi.auth.authorize to false and try it out.