Server is crashing - javascript

I am running a longpolling script to grab data from the database. It was working fine until moving my script to an MVC.
I have viewed the chrome developer tool and it's showing nothing in there, but the page just carries on loading, and when I go to refresh it won't load, I have to shut down my xampp server or close my browser... Here's my script:
class SystemController extends Controller
{
public function lastbid()
{
set_time_limit(0);
// main loop
while (true) {
//get the product info
$getbidresult = ProductModel::bidprice(Request::get('item'));
// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = Request::get('timestamp');
// get timestamp of when file has been changed the last time
$lastbid = isset($getbidresult->timestamp) ? $getbidresult->timestamp : 0;
// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $lastbid > $last_ajax_call) {
// put last bid info into an array
$result = array(
'bidamount' => isset($getbidresult->amount) ? System::escape($getbidresult->amount): 0,
'timestamp' => System::escape($lastbid)
);
// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;
// leave this loop step
break;
} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep(10);
continue;
}
}
}
}
This is how I am grabbing the data with JS.
function getContent(timestamp)
{
var queryString = {
'timestamp': timestamp
};
$.ajax(
{
type: 'GET',
url: '<?php echo Config::get('URL'); ?>system/lastbid?item=<?php echo System::escape($recentitem->id); ?>',
data: queryString,
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#bidprice-<?php echo System::escape($recentitem->id); ?>').html(obj.bidamount);
getContent(obj.timestamp);
}
});
}
$(function()
{
getContent();
});
$(document).ready(function() {
});
I've looked in apache logs with no avail unless I am looking in the wrong place. Does anything in the code look out of place, It doesn't to my knowledge but I may be overlooking something.
I have the script in a foreach, so I can initiate the div, for each product.
Edit, viewed apache and mysql logs and it showing nothing. Could it be a memory leak?

I think I have fixed it with the help of someone from an external website. It was to do with the sleep()
I have fixed it using:
session_write_close();
I will do more testing to see how it hold up before reporting back. With the reason why etc.

Related

Loading php file when execute and pass variable through Ajax

I'm sorry but I'm having a hard time setting up something simple but that doesn't work for me. I'm trying to put a code that counts the number of clicks on a phone number ( the last 4 hidden digits that appear ) then record this data in my DB. I set up the JAVASCRIPT at the bottom of my PHP page where I will listen if there is a click ( Addeventlistener.... ) on the phone number.
I understood that we can not execute PHP code in a JS script, OK, so I execute an Ajax code to send to a PHP file the values to insert in a new entry to my DB. Except that during the execution the functions that open a connection to the DB are not recognized while in the same way I use others functions in the same PHP file that selects and returns me data from the DB.
Is the difference that they are two different types of request SELECT and INSERT or it is because I send the data through Ajax that the PHP files that load the function of DB connection are not loaded?
AJAX Script
<script>
var phoneclick = document.querySelector(".data-phone");
var baseUrl = "public_html/oc-content/themes/delta/"
phoneclick.addEventListener("click", function() {
var item_id = 8111;
var ajaxPhoneClick = 1;
$.ajax({
url: '<?php echo osc_current_web_theme_url('model/sql_projet.php'); ?>',
type: "GET",
data: {
id: '1111'
},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP FIle
$itemId = $_GET['id'];
$conn = DBConnectionClass::newInstance();
$data = $conn->getDb();
$comm = new DBCommandClass($data);
$db_prefix = DB_TABLE_PREFIX;
$query = "INSERT INTO {$db_prefix}t_item_stats (item_id,phone_clicks) VALUES ($itemId,1) ";
$result = $comm->query($query);
The error i get is this Fatal error: Uncaught Error: Class 'DBConnectionClass' not found in /Applications/XAMPP/
I want to know the reason why this error is throwing and what should i do to bypass this

Working with NXT API using Ajax PHP and Javascript

So I am trying to create my own BlockChain website using NXT API. They have listed the possible operations you can make on their website but there is no source code at all. After hours searching I found this project on github, It's the NXT API implemented in Node.js and also he explains how to use it in the browser I managed to make it work on my website but many functions of his API are not updated and didn't work for me. So I had to do it from scratch based on the php example from NXT page.
I am going to explain how I am trying to run that php function from my HTML page
Following the answer of calling a PHP function with AJAX, I created a PHP file called getGuaranteedBalance.php like this:
<?php
header('Content-Type: application/json');
$aResult = array();
if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
if( !isset($aResult['error']) ) {
switch($_POST['functionname']) {
case 'get_guaranteed_balance':
if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
$aResult['error'] = 'Error in arguments!';
}
else {
$server= $_POST['arguments'][0];
$accno= $_POST['arguments'][1];
$number_of_confirmations= $_POST['arguments'][2];
$command = "nxt?requestType=getGuaranteedBalance&account=$accno&numberOfConfirmations=$number_of_confirmations";
$data = file_get_contents($server . $command);
// example results: {"guaranteedBalance":2700000}
$obj = json_decode($data);
$guaranteed_balance = $obj->{'guaranteedBalance'}; // nxt cents
$guaranteed_balance = floatval($guaranteed_balance) / 100.0; // nxt
$aResult['result'] = $guaranteed_balance;
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
?>
And this is how I call it using AJAX from my HTML page:
<script language="javascript">
jQuery.ajax({
type: "POST",
url: 'Functions/getGuaranteedBalance.php',
dataType: 'json',
data: {functionname: 'get_guaranteed_balance', arguments: ["http://localhost:6876", "2488827424806206243", 50]},
success: function (obj, textstatus) {
console.log("Hii "+obj.result.toString());
if( !('error' in obj) ) {
console.log("Hiiiiiiiii"+obj.result.toString());
} else {
console.log(obj.error);
}
}
});
</script>
On the console, the only message I get is: XHR finished loading: POST "http://localhost:6876/getGuaranteedBalance.php" jquery.min.js:4 actually it should return the balance value which is 974400000000.
I have tried everything changing the parameter to data instead of variables obj or adding alerts everywhere but nothing worked. When I access from browser doing the request manually the request works which means the problem is in the code...
REQUEST:
http://localhost:6876/nxt?requestType=getGuaranteedBalance&account=2488827424806206243&numberOfConfirmations=60
It would be really helpful if someone has a better Idea of implementing this API or if you know one already implemented please share it.

Ajax call to submit text into database don't work

I have a page where users can put comments below photos, everything works fine in php, comments go to the database and displayed below the photo.
Now I'm trying to make it work with ajax but I have some troubles.
I have an javascript document with this:
$(document).ready(function(){
$("#btnSubmit").on("click", function(e){
var update = $("#activitymessage").val()
$.ajax({
method: "POST",
url: "./ajax/save_comment.php",
//data: { update: update}, - first version, not correct
data: { activitymessage: update},
datatype: 'json'
})
.done(function(response) {
console.log("ajax done");
console.log (response.message);
var ht = "<li>" + update + "</li>";
$("#listupdates").append(ht);
});
e.preventDefault();
});
});
The php page (save_comment.php) where I tell what to do with the input text:
<?php
spl_autoload_register(function ($class) {
include_once("../classes/" . $class . ".class.php");
});
$activity = new Comment();
if (!empty($_POST['activitymessage'])) {
$activity->Text = $_POST['activitymessage'];
try {
//$activity->idPost = $_GET['nr'];
//$activity->idUser = $_SESSION['user_id'];
// with this it works, but not yet correct
$activity->idPost = 66;
$activity->idUser = 3;
$activity->SavePost();
$response['status'] = 'succes';
$response['message'] = 'Update succesvol';
} catch (Exception $e) {
$error = $e->getMessage();
$response['status'] = "error";
$response['message'] = $feedback;
}
header('Content-type: application/json');
echo json_encode($response);
}
There is also the file Comment.class.php with the 'Comment' class and the function SavePost(). This works without ajax, so I assume the function is correct.
What works
the comment (var update) is printed on the screen into the list.
The console says : "ajax done"
What don't work
The input text don't insert into the database (and disappears when page refresh)
The console says: "undefined" (there must be something wrong with the 'response I use in this function)
I hope you guys can help me out. Thanx
update
I changed the: data: { activitymessage: update} line in the js file, and set manually values for the $activity->idPost = 66; $activity->idUser = 3; And everything works !
Only one thing I want to get fixed
the values of the $_GET['nr'] and $_SESSION['user_id'] are now set manually. Is this possible to get these automatic?
The $_GET['nr'] is the id of the page were the photo is and the comments. In this way I can make a query that returns all comments for this page.
The $_SESSION['user_id'] is the id of the user,so I can echo the username and profile photo.
You are sending data with the key being update not activitymessage
Change data to:
data: { activitymessage: update}
Or change $_POST['activitymessage'] to $_POST['update']
Also you have no $_GET['nr'] in url used for ajax. Nothing shown would help us sort that out but you would need the url to look more like:
url: "./ajax/save_comment.php?nr=" + nrSourceValue,
Not sure why you need to use $_GET['nr'] and don't use $_POST for that also and and nr property to data object being sent

send array over ajax

I have a xml file containing information i want to store or update in database. my server redirects me to previous page if in 30 seconds script doesn't finish executing (changed max execution time, didn't help)
I want to split the file into multiple arrays and send them over ajax to be processed in more instances thus trying to shorten the execution time.
the file contains 38k rows and in 30 seconds i can add 6700 new objects in db or update 3800 existing ones.
so is there a way to do this? i'm very new to ajax so i don't even know where to start looking for a solution.
EDIT1:
<?php
$time = microtime(TRUE);
$xml = simplexml_load_string(file_get_contents($feed));
$json = json_encode($xml);
$array = json_decode($json,TRUE);
$array= $array['Row'];
set_time_limit(0);
ini_set('memory_limit','4000M');
//echo ini_get('max_execution_time');
//die();
$new = 0;
$existent = 0;
foreach($array as $produs)
{
$prod = Products::model()->findbyattributes(array('cod'=>$produs['ProductId']));
if(!$prod)
{
$prod = new Products;
$prod->cod = $produs['ProductId'];
$prod->price = $produs['PriceSRP'];
$prod->name = $produs['Name'];
$prod->furnizor= 'ABCData';
$prod->brand = $produs['HierarchyNameLevel1'];
//$prod->stock = $produs['Available'];
if($produs['Available'] == "+")
$prod->stock = 'Da';
else
{$prod->stock = 'Nu';}
$prod->category = $prod->getCategory($produs['MinorGroup'], 'ABC');
if(!$prod->category)
continue;
if(!$prod->save())
{
echo '<pre>';
var_dump($prod->geterrors());
echo '</pre>';
}
else{$new++;}
}
elseif($prod)
{
$prod->brand = $produs['HierarchyNameLevel1'];
$prod->price = $produs['PriceSRP'];
$prod->last_edit = date('Y-m-d H:i:s');
if($produs['Available'] == "+")
$prod->stock = 'Da';
else
{$prod->stock = 'Nu';}
if(!$prod->save())
{
echo '<pre>';
var_dump($prod->geterrors());
echo '</pre>';
}
else {$existent++;}
}
}
echo 'adaugat '.$new.' si updatat '.$existent.' produse in ';
print (microtime(TRUE)-$time). ' secunde!';
?>
it appears i may have been unclear in my initial post.
so this is my existing code. the $feed file has 38k items in it that i need to process and add or update existing db entries.
if i run the full 38k file after 30 sec the browser performs a history.back() called by the apache server. i would have liked to process the file from crond and process for example 1 entry every second but that is imposible since i have no access to crond on that specific server. i've tried to split up the file manually and it works perfectly fine for ~6700 new entries or 3500 - 4000 existing ones (since it has to find them, load them, update them and save )
so my initial problem, and what i was asking if it is posible to do it over ajax so the server won't stop the script from executing if its longer them 30 seconds(as in i don't even know if the server will interpret the ajax as a new request and existing script won't wait for it to respond).
I would save the xml file in a temp folder, then do an ajax get that runs the file from a specific off-set for (e.g.) 100 records:
function processScript(offset) {
$.ajax({
type: "POST",
url: "some.php",
data: { offset:offset },
dataType:'json',
success: function(data) {
var o = parseJSON(data);
if(o.offset > 0) {
processScript(o.offset);
}
}
})
}
processScript(0);
In some.php you would want to return a json object with a property 'offset' containing the next block of elements you want to process. When the xml file is complete, set offset to 0.
The above code is enough to get you started. You will also want to do some sort of error cheching in the success function, as well as give a progress notification to the user (e.g. "3,600 of 38,000 lines process"?).
array = $('.def-mask :checkbox:checked').serialize();
$.ajax({
url: 'ajax/battle.php',
type: 'post',
data: { playerReady: 1, attack: attack, defence: array },
success: function(data) {
alert(data);
}
});
More info

How to return json value from php page to html page by ajax and how to show result on html page

I m validating email id in php and ajax, and want to return value from php page to html in JSON format.
I want to keep that return value in php variable for the further use.
I'm doing these all in codeigniter, and I want to show .gif image while my AJAX is processing. (Pre loader image)
AJAX/Javascript/jQuery:
function checkEmail(value_email_mobile) {
if (value_email_mobile !== '') {
//alert('te');
$.ajax({
type: "POST",
url: url_check_user_avail_status,
data: "value_email_mobile=" + value_email_mobile,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
// $('#stat').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
PHP/Controller:
<?php
function check_email_or_mobile($param)
{
$ci = CI();
$value = $param['email_or_mobile'];
$query = "SELECT user_email , mobile FROM tb_users WHERE user_email = '$value' or mobile = '$value'";
$query = $ci->db->query($query);
if ($query->num_rows() > 0)
{
if (is_numeric($value))
{
return $res = "This mobile number is not registerd";
}
else
{
return $res = "This Email id is not registerd";
}
}
}
This is just to give you an example on how it will work.
First off, (obviously) there must the a preloader image ready inside the document. This must be hidden initially.
Second, before triggering the AJAX request, show the loading animated GIF.
Third, after the request if successful. Hide the image again inside your success: block inside the $.ajax().
Consider this example: Sample Output
PHP:
function check_email_or_mobile($param) {
// your functions, processes, blah blah
// lets say your processes and functions takes time
// lets emulate the processing by using sleep :)
sleep(3); // THIS IS JUST AN EXAMPLE! If your processing really takes time
$data['message'] = 'Process finished!';
// with regarding to storing, use sessions $_SESSION for further use
$_SESSION['your_data'] = $data_that_you_got;
echo json_encode($data); // use this function
exit;
}
// just a simple trigger for that post request (only used in this example)
// you really dont need this since you will access it thru your url
// domain/controller/method
if(isset($_POST['request'])) {
check_email_or_mobile(1);
}
HTML/jQuery/AJAX:
<!-- your animated loading image -->
<img src="http://i600.photobucket.com/albums/tt82/ugmhemhe/preloader.gif" id="loader" style="display: none;" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <script type="text/javascript" src="jquery.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
// before the request, show the GIF
$('#loader').show();
$.ajax({
url: document.URL, // JUST A SAMPLE (url_check_user_avail_status)
type: 'POST',
data: {request: true},
dataType: 'JSON',
// data: "value_email_mobile=" + value_email_mobile,
success: function(response) {
// After a succesful response, hide the GIF
$('#loader').fadeOut();
alert(response.message);
}
});
});
</script>
My assumption is, since this is just a simple email checking, this wont really take a chunk of time. The other way is to fake the loading process.
success: function(response) {
// After a succesful response, hide the GIF
// Fake the loading time, lets say 3 seconds
setInterval(function(){
$('#loader').fadeOut();
alert(response.message);
}, 3000);
}
Let us know what part of your code is not working?
1) Check if the request flow is hitting the function checkEmail? PHP has inbuilt JSON converting utility json_encode. You could start using that.
2) If you want to store this on the server for further use, you could think about usage like
a) Storing it in Database (If really needed based on your requirements. Note: This is always expensive)
b) Session - If you would want this info to be available for all the other users too.
c) Or keep it in the memory like any of the caching mechanisms like memcache etc
3) For displaying the busy display,
// Before the below ajax call, show the busy display
$.ajax({
});
// After the ajax call, hide the busy display.
You could do this using JavaScript / JQuery on your choice.
I remember using
JSON.parse(data)
to convert JSON ino a javascript object.
Jquery has its own JSON parser btw. Something like $.JSONParse(data)

Categories