jquery ajax request seems to hang after a few requests - php

I have several objects on my page that I iterate through and make an ajax request to request the status either on or off. They are lights controlled by homeseer automation software.
Using firebug I can see all the being made and the responses coming back. when I press a light, I check the status of all lights, in case the status for the lights has changed. After about the third click, I can see all the requests being made but no response coming back.
Jquery passes the url to a PHP script which makes the call and returns the data to jquery this gets around cross domain security.
I can open up another tab and copy the url post statement into the address and the page displays the response.
Am I not closing something when I have finished with my request/ why after the third click are requests made but no response back???
here is my code
function X10Check(){
//This Ajax checks the current on/off status of the passed X10 code
$('div.lightchk').each(function(i, obj) {
$x10Device = $(this).data("x10");
var element = $(this);
var data = "url=http://192.168.0.34:81/tenHsServer/tenHsServer.aspx?t=ab&f=DeviceStatus&d=" + $x10Device ;
$.ajax({
url:"urlencode.php",
data: data,
type: "POST",
success: function(data)
{
myd = $('<span />').html(data).find("#Result").text();
var Nmyd = myd.charAt(3);
if (Nmyd ==':')Nmyd = myd.charAt(4);
if (Nmyd == '2'){element.removeClass('off').addClass('on')}else{element.removeClass('on').addClass('off')};
},
error: function (request, status, error)
{
// alert(request.responseText);
}
});
});
};
it makes a php call here is the php call using the php script allows me to get around cross domain security issues.
<?php
//set POST variables
$url = $_POST['url'];
unset($_POST['url']);
$fields_string = "";
//url-ify the data for the POST
foreach($_POST as $key=>$value) {
$fields_string .= $key.'='.urlencode($value).'&';
}
rtrim($fields_string,"&");
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
$url .= '&';
$url .= $fields_string;
curl_setopt($ch,CURLOPT_URL,$url);
//execute post
$string = curl_exec($ch);
curl_exec($ch);
curl_close($ch);
?>

Related

How can i store ajax data on a php variable and reuse it?

After sending data using ajax how to store those on PHP variable? I created a dump file where I can see that variable is sent but can't see them when I echo them? how can I see them? I send get data through URL and post data through XMLHttpRequest(); The data return nicely but why it's not storing on PHP variable?
<?php
//dumping code to see received data
$output = "Post Variables\n";
$output .= print_r($_POST, true);
$output .= "\nGet Variables\n";
$output .= print_r($_GET, true);
$output .= "\nBody Content\n";
$output .= print_r(file_get_contents('php://input') ?: "empty", true);
file_put_contents("dump.txt", $output);
// End
if(isset($_GET['a'])) {
die('This is post data: ' . htmlspecialchars($_GET['a']));
}
if(isset($_POST['b'])) {
die('This is post data: ' . htmlspecialchars($_POST['b']));
}
echo "This is get variable: " .$a;
echo "This is post variable: " .$b;
?>
<html>
<head>
<script>
//sending ajax request to change table name on onclick event
function clickMe(j){
// Create our XMLHttpRequest object
var req = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var dayName = document.getElementById("btn"+j).value;
var SVAR = "b="+dayName;
var url = "tempo.php?a="+dayName;
req.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
let data_return = req.responseText;
document.getElementById("status1").innerHTML = data_return;
}
}
// Send the data to PHP now... and wait for response to update the status div
req.send(SVAR);
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<button id="btn1" value="saturday" onclick="clickMe(1)">btn1</button>
<button id="btn2" value="sunday" onclick="clickMe(2)">btn2</button>
<br><br>
<div id="status1"></div>
</body>
</html>
The way you use XMLHttpRequest is not right. You should use 2 differents pages : the caller (index.php) and the asynchrone script (tempo.php)
To correct your current caller page : index.php :
• Use an url without any parameter :
url="tempo.php"
• Send your two parameters together :
req.send("a="+dayName+"&b="+dayName);
To debug the asynchrone page : tempo.php, just add a fake get_parameter at the top of tempo.php:
a = a_possible_value_for_a
and then call tempo.php in your browser directly (without your ajax-page)
Request sent from HTML File.
Sending process one :
$(document).on("click","#btn1",function(){
var data = $(this).val();
/* ajax request sent start */
$.ajax({
method:"post",
url:"phpFileName.php",
data:{backendPostName:data},
dataType:"json",
success:function(response){
/* Logic implemented here */
}
});
/* ajax request sent end*/
});
Sending process two according to your html structure :
function clickMe(data){
var data = $(this).val();
/* ajax request sent start */
$.ajax({
method:"post",
url:"phpFileName.php",
data:{backendPostName:data},
dataType:"json",
success:function(response) {
/* Logic Implementation here */
}
});
/* ajax request sent end*/
}
When you want to receive this sending data inside php file.
First check this name found or not through php "isset()" function
Example below :
php file :
<?php
if(isset($_POST['backendPostName'])){
$customName = $_POST['backendPostName'];
/*
store or other logic implement here .
if you wants to echo html then echo "success"; or your choice
if you wants to return json data then return json_encode(["result"=>1]);
*/
/* For HTML Return */
echo "<h1>Success</h1";
/*For Json return */
echo json_encode(["result"=>1]);
}
?>

PHP cURL request body is undefined in node.js

I've tried all the examples on these SO posts:
How do I send a POST request with PHP?
PHP cURL Post request not working
Always my request.body is undefined yet in the request itself I see "_hasBody":true
The current code for my php post file:
function httpPost($url,$data){
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$response=curl_exec($curl);
curl_close($curl);
return $response;
}
$fields = array(
'name' => 'ben'
, 'foo' => 'bar'
);
echo httpPost("http://localhost:8002", $fields);
Then my node.js listening server code is:
var test=require('http').createServer(function(q,a){//question,answer
console.log(q.body);
console.log(JSON.stringify(q).indexOf('ben'));
a.end(JSON.stringify(q));
});
test.listen(8002,function(e,r){console.log("listening");});
As you can see, in the node.js server I search the request for my name but the console says
undefined//no body
-1//could not find your name in the request
then I hand over the request back to the response and print it to the page so I can see the whole data.
logically it would seem that I am doing the cURL part right as its copied code, so I would say I might be doing something wrong to access the vars
My question is how do I see the request body or where the vars?
To handle a POST request, you have to do the following:
var qs = require('querystring');
var http = require('http');
var test = http.createServer(function(req, res) {
//Handle POST Request
if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var POST = qs.parse(body);
console.log(body); // 'name=ben&foo=bar'
console.log(POST); // { name: 'ben', foo: 'bar' }
if(POST.name == 'ben')
console.log("I'm ben"); //Do whatever you want.
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.statusCode = 200;
res.end(JSON.stringify(POST)); //your response
});
}
});
test.listen(8002, function(e, r) {
console.log("listening");
});
cURL response:
{"name":"ben","foo":"bar"}

Constantly Check TwitchTV Viewer Count via REST API

So basically what I want to do is to pull in the viewer count in real time for a stream that is currently live. I have a check to see if the stream is live or not. How do you go about pinging the API constantly to get the updated value so that I can send the updated value to the document in this case it would ultimately update a the $viewers variable that I've setup. If it makes a difference the application I'm making is using the CodeIgniter framework. Below is the code that I currently have to make the call. Right now I have to reload the page inorder to get the actual value and it's using cURL to make the API call.
class Streaming {
var $base_url = "https://api.twitch.tv/kraken/";
var $client_id = 'client_id_here';
public function load_stream_stats($channel) {
$curl = curl_init();
curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $this->base_url . 'streams/'. $channel .'?client_id=' . $this->client_id
)
);
$result = curl_exec($curl);
//makes sure that the cURL was excuted if not it generates the error stating that it didn't succeed.
if(!curl_exec($curl)){
die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
} else {
//cURL Response worked
if(!empty($channel)) {
$return = json_decode($result);
if($return->stream == null) {
return;
// stream is offline no need to do anything
} else {
$stream_details = array('viewers' => $return->stream->viewers);
// $return->stream->viewers gives a number e.g. 1052
return $stream_details;
}
}
}
curl_close($curl);
}
}
The questioon in hand is how do I ping the TwitchtV API to get the updated viewer count from the REST API?
Working ajax is here. In the site_url/auto_update/broadcast/username I have a json value which contains the viewer count pulled from the API, so that I can auto update it. So encode the viewer count from the api and encode it into json then you can pull all the values.
<script type="text/javascript">
var viewers = <?= $viewers ?>;
var username = "<?= $username ?>";
var site_url = "<?= base_url() ?>";
var poll_interval = 3000;
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#viewers').append(viewers);
setInterval(function(){
$.ajax({
url: site_url + "auto_update/broadcast/" + username,
type: "GET",
dataType: "json",
cache: false,
success: function(data) {
if (data == null) return;
var update_viewers = data['viewers'];
console.log(update_viewers);
$('#viewers').html(update_viewers);
}
});
}, poll_interval);
});
</script>
The AJAX calls the function that contains the newly updated viewer count, and then encodes it into json. I call this function every 3 seconds. If the client ID is appended then you don't get rate limited. Hope this helps someone out.
If you have any questions let me know and i'll try to help out the best I can!

Posting data with curl - actually refreshing to the next page

I'm trying to send post data between pages with Post. Not a form - like I may be passing validation error between pages or something (using it in several places).
The cURL is executing fine, but it's just tacking on the new page at the bottom. How can I execute a cURL Post and load the following page?
So my goal is to send data between pages. I do not want to use GET or cookies as I do not want to rely on the user, and I'd prefer not to use $_SESSION as it is not so much directly about a session as sending private data between pages.
Thanks
$ch = curl_init($some_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'myvar=something');
curl_exec($ch);
curl_close($ch);
I doubt the code has any relevance, as it's about performing a task not code syntax (there may be one in this example but you'll have to trust me it's not the code that's buggy as it's retrieving fine).
You could separate your $_SESSION superglobal into arrays describing both the current user/session and any errors that your form has created. For instance,
$_SESSION = array(
'user' => array(), // user data goes here
'errors' => array() // validation data goes here
);
if (!$_POST['myvar'] == 'something') {
$_SESSION['errors']['myvar'] = 'You must specify a value for <code>myvar</code>';
}
You would then be able to output errors on subsequent pages using a call something like this:
if (isset($_SESSION['errors'])) {
foreach($_SESSION['errors'] as $error) {
echo '<li>' . $error . '</li>';
}
}
Why are you using cURL? Why not just use AJAX:
$(function() {
// Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',
data: 'var1=value1&var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});
Using ajax for exec
$(function() {
/
data: 'var1=value1&/ Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});

PHP Post to ASP Form, return XML results to PHP page.

The setup of what i have to work with and what i need is as below:
I have been provided with an ASP form (on another domain) which upon submission outputs search results in an XML format.
I am developing a PHP website (on my companies domain)
From this PHP website i need to be able to query the said ASP form and get the XML results posted back to the PHP page (on my companies domain)
The variable "Client=*" must be sent to the ASP form, for it to work.
What i have tried so far...
jQuery.ajax to try and do a normal post request using this code:
$.ajax({
url: "http://www.example.com/xml/aspfile.asp",
crossDomain: true,
cache: false,
dataType: ($.browser.msie) ? "text" : "xml",
data: { Client: "clientname" etc },
type: 'post',
xhrFields: {
withCredentials: true
},
error: function(){
alert("error");
},
success: function(data){
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
} });
Note:
I have tried alot of different iterations of the above code from basic ajax requests to more complex ones like the above.
The above code returns the following error, which is an error i have come across quite a bit.
XML Parsing Error: no element found Location: moz-nullprincipal:{14ce834e-ef24-43f8-b338-7202241298a5} Line Number 1, Column 1:^
What i need
Ideally some code that works ... failing that ideas or suggestions on how i can get this to work.
Many thanks in advance to all those that post answers for your time.
Edit: As requested here is how the XML looks
<quicksearchresults>
<heading>
<title1>River Cruises</title1>
<title2>Quick Search</title2>
<cruise_nos>732</cruise_nos>
<earliest_date>01/08/11</earliest_date>
<latest_date>01/09/11</latest_date>
<river>Anywhere</river>
<linename>Any</linename>
</heading>
<rivercruiselist>
<holdate>28/08/11</holdate>
<linename>The River Cruise Line</linename>
<shipname>Esmerelda</shipname>
<shiplink>url</shiplink>
<cruisename>Cruise+The+Danube+to+Vienna+%26+Budapest</cruisename>
<cruiselink>url</cruiselink>
<river>Danube</river>
<ratingicon>Images/BudgetIcon.png</ratingicon>
<flyfrom>Linz</flyfrom>
<flyback>linz</flyback>
<cruisenights>7</cruisenights>
<vacationdays>10</vacationdays>
<lowprice>0</lowprice>
<highprice>0</highprice>
<flights>including Coach</flights>
<soldout>Yes</soldout>
<enquiryformlink>url</enquiryformlink>
<enquiryformimage>Images/TravelEButton.png</enquiryformimage>
</rivercruiselist>
</quicksearchresults>
Use your PHP server as a proxy: you make a AJAX request to your own PHP page which uses curl to get the XML from the external source and returns it you, so you can parse it.
var xml;
if (typeof data == "string") {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
This part is not necessary, you can use jQuery selectors to parse the XML. From the looks of it your request isn't returning any results. What does alert(xml) produce?
AFAIK you cannot do a cross-domain POST, you can do cross-domain GET with some JSONP hacks though.
Your example XML does not appear to be valid as the first <quicksearchresults> node is never closed.
Here's an example, you'll have to excuse my broken PHP, as I haven't used it in a while.
// post the contents of the form to our PHP proxy
$.post("myproxy.php", $("#myform").serialize, function(data) {
// do something with returned xml here.
},"xml");
Proxy example (myproxy.php):
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.remotedomain.com/api.php");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'client*' => 'something',
));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>

Categories