Okay, I asked a question earlier but I've run into a whole new problem. I have a PHP array in a PHP script server side. I am trying to write a Client side Ajax script to repoll the PHP script for new data and update the statistics displayed on the page.
Heres the Ajax that im sure im not doing right:
setInterval(function(getLatestInfo)
{
$.ajax({
type: 'POST',
url: 'script.php',
data: 'id=data',
dataType: 'json',
cache: false,
success: function(getLatestInfo){
$.getJSON(script.php, function(getLatestInfo){
var result_array = JSON.parse(result);
});
$('#bit_rate').html(result_array[4]);
$('#listeners').html(result_array[5]);
$('#current_song').html(result_array[9]);
});
});
}, 10000);//time in milliseconds
And here is the PHP:
<?php
Function getLatestInfo() {
$SERVER = 'http://chillstep.info:1984';
$STATS_FILE = '/status.xsl?mount=/test.mp3';
$LASTFM_API= '00000000000000000';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$SERVER.$STATS_FILE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($ch);
curl_close($ch);
$dp = array();
$search_for = "<td\s[^>]*class=\"streamdata\">(.*)<\/td>";
$search_td = array('<td class="streamdata">','</td>');
if(preg_match_all("/$search_for/siU",$output,$matches)) {
foreach($matches[0] as $match) {
$to_push = str_replace($search_td,'',$match);
$to_push = trim($to_push);
array_push($dp,$to_push);
}
}
$x = explode(" - ",$dp[9]);
echo json_encode($dp);
}
?>
In short, I need this ajax script to update and pull the PHP variable $dp, which is an array, parse it out, and create HTML usable string variables. And repeat the process every 10 seconds.
Don't use setInterval in this instance. In the success callback call the original function again. Also you are calling getJSON in the success callback of the ajax call - this is duplicating calls.
For example
function getlatest()
{
$.ajax({
//rest of ajax param
success : function(results){
var resultarray = $.parseJSON(results);
$('#bit_rate').html(result_array[4]);
$('#listeners').html(result_array[5]);
$('#current_song').html(result_array[9]);
getlatest();
}
});
}
Related
I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
I have a problem with the communication between AJAX and PHP. I've already tried all these pieces of code from related questions and answers but nothing worked. This code should recieve a JSON string from a PHP file on the same server and display the values in the HTML area.
$(document).ready(function(){
setInterval(ajaxcall, 1000);
});
function ajaxcall(){
var data = $('#signup_form').serialize();
$.ajax({
type: "GET",
url: "test.php",
data: data,
dataType: 'json',
success: function (data) {
window.console.log("Success");
document.getElementById("count").innerHTML = $('#time').html(data.time);
},error: function alert(){"error";}
});}
When I execute the script in my browser (with debug mode) then nothing happens. I assume this implies a problem with the 'success' method.
Here is a part of my PHP code (for testing):
for($i = 0; $i < 50; $i++){
sleep(1);
return_json($argv[1]);
}
//return all values for html/javascript
function return_json($a){
$json = array('time' => $a);
echo json_encode($json);
}
I hope some of you can help me :)
Is the function ajaxcall() really being called? Try to add a console.log call at its begining, eg
function ajaxcall(){
var data = $('#signup_form').serialize();
console.log(' form data = %o', data)
//...
There is another possible issue the function error: function alert(){"error";} does nothing visible. If your server script is returning an error you will see nothing in this case.
Change it to something like
error: function(){ alert("error"); }
You should add the content type to your response header:
//this line
header('Content-type: application/json');
for($i = 0; $i < 50; $i++){
sleep(1);
return_json($argv[1]);
}
//return all values for html/javascript
function return_json($a){
$json = array('time' => $a);
echo json_encode($json);
}
Further reading and a more detailed explanation here: jQuery $.ajax request of dataType json will not retrieve data from PHP script
I'm trying to make a simple ajax call:
When the user selects and option, some info about that option will be
echoed into a div (this is dynamic)
Here's my code for the ajax call
ajax.js
$(document).ready(function()
{
//Add Event
//Currently Broadcasting #Zone
$('#beacon0').on('change', function ()
{
var Selected = $(this).find("option:selected");
var SelectedText = Selected.text();
var SelectedEncoded = encodeURIComponent(SelectedText);
$.ajax
({
url: 'ajax-addevent.php',
data: 'n_beacon='+ SelectedEncoded,
dataType: 'JSON',
success: function(returnClass)
{
var resultajax = jQuery.parseJSON(returnClass)
console.log(resultajax);
},
error: function(xhr, status, error)
{
var errors = JSON.parse(xhr.responseText);
console.log("failed");
console.log (errors);
}
});
});
});
SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.
ajax-addevent.php
<?php
include("classes/event.class.php");
$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
$EventTitle = $row["n_title"];
$EventLink = $row["n_link"];
$EventDate = $row["n_date"];
}
$arr = array( "EventTitle" => $EventTitle,
"EventLink" => $EventLink,
"EventDate" => $EventDate );
header("content-type:application/json");
$json_arr = json_encode($arr);
return $json_arr;
?>
My problem is that the ajax call fails and gives me this as result:
What's wrong why my ajax call? Can you help?
EDIT Update Code:
You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.
Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.
Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).
I am currently using jquery to get JSON data via ajax from a codeigniter backend / mySQL database, which works fine. The problem I'm having is that, along with the data that gets returned to the jquery function, I also need to run a PHP loop for some data in another table. Currently what I'm doing is waiting for an ajax success from the first function, then making another ajax call to the second function - but I know there is a way to do it with just one function, I'm just not sure how. Here are the two database queries:
function get_selected_member($member = null){
if($member != NULL){
$this->db->where('id', $member); //conditions
}
$query = $this->db->get('members'); //db name
if($query->result()){
$member_result = $query->row();
return $member_result;
}
}
AND
function get_all_groups(){
$query = $this->db->get('groups');
$result = $query->result();
return $result;
}
and then in the javascript function, what I'm doing is saying:
var post_url = "/index.php/control_form/get_selected_member/" + selected_member_id;
$('#chosen_member').empty();
$.ajax({
type: "POST",
url: post_url,
success: function(member)
{
//Add all the member data and...
var post_url2 = "/index.php/control_form/get_all_groups/";
$.ajax({
type: "POST",
url: post_url2,
success: function(group)
{
//Create a dropdown of all the groups
}
});
}
});
In PHP you can combine both in one then echo it to ajax as json variable. So in php you will need a change like following
function get_member_with_group($member = null){
$data['member'] = $this->get_selected_member($member);
$data['group'] = $this->get_all_groups();
echo json_encode($data);
}
Then in javascript something like below..
var post_url = "/index.php/control_form/get_member_with_group/" + selected_member_id;
$('#chosen_member').empty();
$.getJSON(post_url, function(response){
var member = response.member;
//do with member
var group = response.group;
// do with group
});
Hope this will help you :)
I have a PHP script that loads XML content dynamically:
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($nice)
->show(array('name','Price'))
->query();
echo $result
This will work fine when it is loaded. But I am trying to use an ajax/jquery script to send the value $nice to the PHP script; and to ultimately send the result back from the dynamically created XML file. I've been trying to figure this out for hours
Here is the ajax Script
function sendValues() {
$("$nice")
$.ajax({
url: "/myphp.php",
data: {str}
cache: false
});
}
Has anybody done something similar to this concept?
Why not pass it as a GET param like so...
jQuery
function sendValues(something) {
$.ajax({
url: "/myphp.php?nice=" + something,
cache: false,
dataType: 'xml',
success: function(xml) {
// Work with the XML
}
});
}
PHP
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($_GET['nice'])
->show(array('name','Price'))
->query();
// You said it is XML?
header('Content-Type: text/xml');
echo $result;