Ajax : How/ Is it possible to parse a '.html(response)' - php

so am making this chat, and am trying to add functionalities.
SO far, I have here is what i achieved.
I have a function that displays messages.
function displayMessages()
{
$.post('core/chat.php?action=read',function(response)
{
$('.message_display').html(response);
});
}
this function is called every second
setInterval(function(){displayMessages();},1000);
the content of the 'reponse' is generated in php.
foreach($messages as $chat_msg)
{
echo '<span style="color:#'.$chat_msg['color'].';">['.$chat_msg['user_name'].']:'.$chat_msg['txt'].' </span><br>';
}
so i build a function that play sound : playsound(file).
I initially wanted to attach it to the function displayMessages()...
function displayMessages()
{
$.post('core/chat.php?action=read',function(response)
{
$('.message_display').html(response);
});
playSound ("send_message");
}
...but of course, that plays the sound at each refresh, having a new message or not.
So,to fix it, i thought of adding on the php sidee, a code that triggers the sounds if a new message was posted: "ex:
echo $playsoundtrigger="playsound";
but then i have no clue, on what to do next.
how can i parse response, so the ajax break down the html on 1 side and the $playsoundtrigger on the other?
something along the line i would have approach like this if it was php:
parse_str("reponse+$triger=true");
if ($triger){
playsound();
}
I look for a parse function in ajax, but all reference i could find was to parse json...
any solution?
or hint on a logic to address my problem?
Note: I looked, and find that ajax, could tell me if the content has changed, based on his side, but I do not want to go this way, as I would like in the long run, to adapt the sounds on the message :)
thank you

Polling your server on every second!!! Hm... you are essentially DDOS ing your own server. I think web sockets are what you need. But don’t know much about it.
As for your answer, you could actually use json, then build the nodes from browser.
Eg:
$data = [];
foreach ($messages as $chat_msg) {
$data[] = [
'color' => $chat_msg['color'],
'user_name' => $chat_msg['user_name'],
'txt' => $chat_msg['txt']
];
}
echo json_encode([
'trigger' => 1
'data' => $data
]);
and in your js
function displayMessages()
{
$.post(
'core/chat.php?action=read',
{},
function(res) {
var html = '';
res.data.foreach(function(msg) {
html += '<span style="color:#' + msg.color + ';">[' + msg.user_name + ']:' + msg.txt + '</span><br>';
}
$('.message_display').html(html);
if(res.trigger) {
playSound ("send_message");
}
},
'json'
);
}

Related

php array with json data in array Element

I tried to ask this question yesterday but my question was of bad quality.
I have a wordpress Site that I have integrated with react. I am sending a post request from a react form to the wp api.
The request from react Looks Like this.
axios.post('/wp-admin/admin-ajax.php', new URLSearchParams({
action: 'report',
report: JSON.stringify(props.data),
nonce : document.getElementById("my-react-app").getAttribute("data_id")
}), config)
.then(response => console.log(response))
.catch((err) => {
let message = typeof err.response !== "undefined" ? err.response.data.message : err.message;
console.log("error", message);
});
}
I am Able to receive the request on the server but I cannot target the json string of data in php.
$data
{"success":true,"data":{"action":"report","report":"{\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}}","nonce":"f2331f42d4"}}
I have Tried ($data is an Array)
function report() {
global $wpdb;
$data = $_POST;
$test_One = json_decode($data['report']->firstName; //Response Nothing. Not even Null
$Test_two = json_decode($data['report']); //Response (The Json String)--- {\\\"firstName\\\":\\\"rrt\\\",\\\"lastName\\\":\\\"trtr\\\",\\\"phone\\\":\\\"rt\\\",\\\"email\\\":\\\"rtrt\\\",\\\"placedata\\\":{\\\"Street\\\":\\\"tr\\\",\\\"City\\\":\\\"tr\\\",\\\"State\\\":\\\"tr\\\",\\\"zip\\\":\\\"tr\\\"},\\\"dateData\\\":{\\\"Start\\\":\\\"00:21\\\",\\\"End\\\":\\\"00:12\\\",\\\"Date\\\":\\\"2022-08-31\\\"},\\\"foodData\\\":{\\\"Food\\\":\\\"df\\\"},\\\"peopleData\\\":{\\\"People\\\":\\\"32\\\"}
//The above examples have all been placed in print_r
echo "<xmp>";
(Test 3) print_r(json_decode($data['report'])['lastName']); // Response --- {
echo "</xmp>";
}
I am new to PHP and have looked at many Answers On Here. Have yet to find a similar Issue. That tells me it's probably not much of an issue, yet I cant seem to figure it out. Any Help Would be Appreciated. Thank you!
try this solution
function report() {
global $wpdb;
$data = $_POST;
$test_One = json_decode($data);
$test_One = $test_One->data->report->first_name;
echo $test_One;
}

Php - how to encode an array as json and send it back

Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost.
So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows:
$arrayResult = array();
foreach ($result as $item) {
array_push($arrayResult, array("type" => $item['type'],
"count" => $item['count'])
);
}
echo json_encode($arrayResult);
My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. As in, no data shown at all.
var arrayResult = null;
$.get("../php/displayGraph.php",
function (data) {
arrayResult = (data);
var result = JSON.parse(arrayResult);
$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
The result of this is:
[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]
I am honestly at a loss in terms of what I even need to do to make it work. And here I thought java was bad with json.
Try like this,
$.get("../php/displayGraph.php",
function (data) {
$.each(data, function (i,item){
console.log(item.type + " === " +item.count);
}
/*arrayResult = (data);
var result = JSON.parse(arrayResult);*/
//$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
Not sure why, but the following works
$.get("../php/displayGraph.php",
function (data) {
var result = JSON.parse(data);
$("#results").html(data);
console.log(result[1][0].count);
}
);
Certainly is a 2D array the way my php makes it, but i did not think this would be how to do as all the other tutorials i saw never had it like this.

Realtime Ouput while PHP Function is Executing

My problem is that I need a PHP script to continously provide ouput at certein points of it's execution. I have workng AJAX to fetch the html but it only echos once the script is complete. Here is an example:
<?php
class test {
function test() {
echo '1';
sleep(20);
echo '2'
sleep(5);
}
}
I need some way to have the echo's actually displayed in the browser even though the function is still continuing. I have tried using global variables and session variables to no avail.
Thanks for the help!
I've seen many questions where people are trying to do this type of thing, but as far as I know it really isn't possible to do it the way you're trying to do it using only PHP and AJAX. In order for this to work using just AJAX rather than websockets or some other approach, you can break your script into separate pieces at the points where it needs to provide output, and provide the output as responses to separate AJAX requests. Here is a basic example of what I mean. The script on your page can start the process and makes repeated calls to step through the process until it's complete.
<button id="begin_process">Start</button>
<script type="text/javascript">
function step(step_number) {
$.get('test.php', {'step_number': step_number}, function(response){
console.log(response.message);
if (response.next_step) {
step(response.next_step);
}
}, 'json');
}
$(document).ready(function(){
$('#begin_process').click(function(){
console.log('go!');
step(1);
});
});
</script>
test.php:
<?php
class Test {
function step($step_number) {
switch ($step_number) {
case 1:
return array('next_step' => 2, 'message' => 'step 1 complete');
case 2:
sleep(20);
return array('next_step' => 3, 'message' => 'step 2 complete');
case 3:
sleep(5);
return array('message' => 'finished');
}
}
}
$test = new Test();
echo json_encode($test->step($_GET['step_number']));

jQuery ajax call errors with sendToValue is not defined, what is wrong with this jquery code ?

I'm kind of new to jquery/ajax calls, I have this code below to pull from php page json values.
$(function(){
$('#search').keyup(function() {
sendValue($(this).val);
});
});
function sendValue(str)
{
$.post(
"back/search.php",
{ sendToValue: str },
function(data) {
if(!data.empty){
//Put the result in the suggest div
$("#suggest").html(data.returnedFromValue);
}
},"json"
);
}
and here is the search.php file
$values = $database->get_by_name($_POST['sendToValue']);
if( !$values ) {
echo json_encode(array("returnedFromValue" => "ERROR"));
}
else
{
foreach($values as $value) {
echo json_encode(array("returnedFromValue" => $value));
}
}
The problem that that the value doesn't appear in the suggest div, the only output there is "error", when I check the ajax request in firebug under post section it gives me the message that sendToValue is not defined any ideas? Thanks!
The first thing that leaps out at me (there may be other problems, but this is the one I noticed first) is that you're missing the parentheses after val in the call to sendValue:
sendValue($(this).val);
should be:
sendValue($(this).val());
Currently, you're passing the val method itself into the sendValue function, rather than the result of calling that method.
$(this).valprobably needs to be $(this).val()
When programming JavaScript Firebug and console.log()are your friends.

Reverse Ajax implementation using php

I am looking to implement reverse ajax in my application which is using PHP and jquery. I have googled a bit about it and found XAJA but that seems to be a paid application. Is there an open source application available for the same or has someone implemented it?
Some pointers or hints would be very helpful.
Thanks in advance.
I know of two types of reverse AJAX:
1- Polling
2- Pushing
I think polling is rather easier to implement, you just have your javascript make a regular request to the server every time interval, and when the server have some data for it it will respond. Its like a ping and some call it heartbeat, but its the very obvious solution for this problem. However it may easily overload the server.
EDIT Simple polling Example code:
Server-Side:
<?php
//pong.php php isn't my main thing but tried my best!
$obj = new WhatsNew();
$out = "";
if ($obj->getGotNew()){
$types = new array();
foreach ($obj->newStuff() as $type)
{
$new = array('type' => $type);
$types[] = $new;
}
$out = json_encode($types);
}
else{
$out = json_encode(array('nothingNew' => true));
}
Client-Side:
function ping(){
$.ajax(
{
url : "pong.php",
success : function (data){
data = JSON.parse(data),
if (data['nothingNew'])
return;
for(var i in data){
var type = data[i]['type'];
if (type && incomingDataHandlers[type]){
incomingDataHandlers[type]();
}
}
});
}
incomingDataHandlers = {
comments: function () {
$.ajax({
url: "getComments.php",
method: "GET",
data: getNewCommentRequsetData() // pass data to the server;
success : function (data){
//do something with your new comments
}
});
},
message: function (){
$.ajax({
url: "getMessages.php",
method: "GET",
data: getNewMessageRequestData() // pass data to the server;
success : function (data){
//do something with your new messages
}
});
}
}
$(docment).ready(function () {
setInterval(ping, 1000);
})
You are looking for what they call "long poll" - I did a "long poll php" and I got this thread on stack overflow:
How do I implement basic "Long Polling"?
you could websockets in conjuction with "flash" websockets because almost all browser have flash on board(average around 96%? => http://www.statowl.com/flash.php) => https://github.com/gimite/web-socket-js. You could use this together with http://code.google.com/p/phpwebsocket/. Still I am wondering if the performance is going to be any good. If it all possible I would use node.js to do reverse ajax. http://socket.io is a really cool project to do this!
Have you checked APE ?
Its a push based real-time data streaming technology over a single low volume ajax connection. The concept is useful, you may be able to replicate the same thing with your server-side implementation

Categories