Loading php file when execute and pass variable through Ajax - javascript

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

Related

How to bring a json result into PHP

I have some results from a fetch.php using json and I successfully brought all results to my bootstrap modal HTML screen.
When the Modal is being shown, I would like to run a MYSQL query using a value coming from the same json I used for the modal, however I can't put this value into a PHP variable to run the SQL query.
How can I get this?
I am trying to bring the same value I input into the HTML textbox (modal), but it is not working. I also tried to use the value from json '$('#PCR').val(data.PCRNo);)', but nothing happen.
This is the script to collect information from database using fetch.php file:
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
</script>
This is the PHP code
<?php
//trying to get the value I have included on #PCR (textbox) which has ID='PCR' and name ='PCR' **
$PCR= $_POST['PCR'];
//running now the code to check if the database has the value and return the desired response to be shown **
$sql1 = mysqli_query($dbConnected,"SELECT * FROM change_management.tPCN");
while ($row1 = mysqli_fetch_array($sql1)) {
if ($row1['PCRNo']==$PCR){
echo $row1['PCNNo'];
echo "<br/>";
}else{
}
}
?>
I would like include value from this val(data.PCRNo) json return into the $PCR variable, so the MYSQL query is going to work
There are a number of quite basic logical issues with your code which are preventing it from working.
1) data: { pcr_number: pcr_number}- the name pcr_number doesn't match the value PCR which the server is searching for using $_POST['PCR'];. The names must match up. When making an AJAX request, the name you gave to the form field in the HTML does not matter (unless you use .serialize()) because you are specifying new names in the data parameter.
2) Your SQL query doesn't make sense. You seem to be wanting to read a single row relating to a PCR number, yet your query makes no usage of the input PCR value to try and restrict the results to that row. You need to use a SQL WHERE clause to get it to select only the row with that ID, otherwise you'll fetch all the rows and won't know which one is correct. (Fetching them all and then using an if in a PHP loop to check the correct one is very inefficient.) I wrote you a version which uses the WHERE clause properly, and passes the PCR value to the query securely using prepared statements and parameters (to project against SQL injection attacks).
3) Your output from the PHP also makes no sense. You've told jQuery (via dataType: "json" to expect a JSON response, and then your code inside the "success" function is based on the assumption you'll receive a single object containing all the fields from the table. But echo $row1['PCNNo']; echo "<br/>"; only outputs one field, and it outputs it with HTML next to it. This is not JSON, it's not even close to being JSON. You need to output the whole row, and then use json_encode() function to turn the object into a JSON string which jQuery can parse when it receives it.
Here's a version of the code containing all the above changes:
JavaScript:
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
$.ajax({
url: 'fetch.php',
method: 'post',
data: { pcr: $(this).attr('id'); },
dataType: "json",
success: function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
PHP:
<?php
$PCR = $_POST['pcr'];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt->bind_param('s', $PCR);
$stmt->execute();
$result = $stmt->get_result();
//an "if" here will cause a single row to be read
if ($row = $result->fetch_assoc()) {
$output = $row;
}
else
{
$output = new StdClass();
}
$stmt->free_result();
$stmt->close();
//output the result
echo json_encode($output);
?>
N.B. I would potentially suggest studying some tutorials on this kind of subject, since this is a fairly standard use case for AJAX/JSON, and you should be able to find samples which would improve your understanding of all the different parts.
P.S. Currently the PHP code above will return an empty object if there is no matching row in the database. However, this is probably an error condition (and will cause your JavaScript code to crash due to trying to read nonexistent properties), so you should consider how you want to handle such an error and what response to return (e.g. 400, or 404, and a suitable message).
You need to first return json from php by using json_encode.
Inside this loop
while ($row1 = mysqli_fetch_array($sql1)) {
$data = array('PCRNo' => 'itsvalue', 'PCC' => 'itsvalue', 'Creation_Date' => 'itsvalue')
}
print json_encode($data)
store all the data in an associative array and then convert it into json using json_encode and return the json.
Use json data in you ajax file
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
var data = JSON.parse(data);
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
Below is the changed script to store different values in $PCR variable
<script>
$(document).ready(function(){
var i = 1;
$('#table').on('click', '.fetch_data', function(){
if(i == 1) {
var pcr_number = $(this).attr('id');
} else {
var pcr_number = $('#PCR').val();
}
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
i++;
}
});
});
});
</script>

Receiving data in Ajax for a Div

So this one problem has taken me on a wild goose chase for a week or so now and I am really hoping that the problem will finally be able to be solved tonight. I'm not at all experienced with Ajax or JS so I really struggle here and am still learning. Here is what I hope to achieve...
I have a basic PHP messaging system in messages.php showing all messages between two users within a DIV which automatically adds a scroll bar when you receive more messages. Here is my DIV which does this:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// PHP MESSAGE SCRIPT
</div>
</div>
When you send a reply, it uses this Ajax script to send that data to be processed on system/reply_system.php if it notices you are talking to an automated account, it will also send the data to system/sars_system.php to be processed, this works fine for adding, and sending back messages...
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
The nice gent who helped me with this script has informed me that I need to receive data back from system/sars_system.php and system/reply_system.php which basically look like this:
<?
require 'db.php';
$message = $_POST['message'];
$conversation_id = $_POST['conversation_id'];
$sarssystem = $_POST['sarssystem'];
$user_id = $_POST['user_id'];
$usr_message = str_replace("'","\\'",$message);
mysqli_query($conn,"INSERT INTO ap_messages (message_id, message, sender_id, time_sent, time_read, conversation_id)
VALUES ('','$usr_message','$user_id', NOW(), NOW(), '$conversation_id')");
mysqli_query($conn, "UPDATE ap_conversations SET time = NOW() WHERE conversation_id = '$conversation_id'");
echo json_encode('success');
?>
But I am having a real big problem trying to figure out how to do that or what data I even need to send back or how I go about coding that in to the current script? If this all works, the final aim is to automatically initiate sending the scroll bar to the very bottom of the page every time this Ajax script runs?
The ajax looks right because it is ready to receive data. In the php you can set the data to whatever you need, it could be the results of the database call. Here's a small example of sending some data back to the ajax script.
$data = array(
'status' => 'ok',
'message' => 'Customer account saved',
);
return json_encode($data);
If you know how to get whatever data you need on the server you can encode it and return it to the client.
The success method will run on the ajax object. It is passed the data and you can reference and manipulate/use it. Your code looks like it is already prepared for this:
success: function(data) { // <-- this is the data in json format from the server
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.

Is this piece of jquery ajax code correct?

I am making a simple web chat application using ajax,php,javascript and mysql.
What I am trying to do here is to avoid fetching the whole database after an interval of 1 sec(which is normally done in basic chat application ) but rather I want to fetch and display(by appending) also those chats which have been newly entered into the database by any user.
To implement this ,First when the user first opens the chat screen the whole database is loaded in the chat window(not shown in this code snippet),and then I am using the variable msgid to fetch the latest value of MSg_ID (which is the auto-increment primary key in my chat table) through an ajax request to the page 'Msg.php' which returns the required value of msg_id.
Now using this value of msgid and comparing it with the max value of Msg_ID every second in the database through the ajax request to the page 'Chat3.php'.
If the Max value of Msg_ID has changed the required rows are returned . After this I m updating the value of 'msgid' using the same earlier ajax request to the page 'Msg.php'
The pages Msg.php and Chat3.php are working perfectly ,as I have tested them thoroughly.
My question here is what is the problem in my code , why is not working?
Can we use an ajax request inside a ajax call back function or not?
What else can be a probable source of error?
Any input will be valuable :)
If you have any problem in understanding the code,leave a comment.
'#yyy' and '#zzz' are random div elements which i am using to test the data value of ajax callback function.
I can even post the rest of the code if it helps.
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
$('#yyy').html(data);//this displays the correct value
var msgid=data;
}
});
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid},
success: function(data) {
if(data!='bad'){
//$('#messages').prepend(data);
$('#zzz').html(data);//does not display any value although Chat3.php is returning the correct value.
//below ajax request to update the value of msgid
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
var msgid=data;
$('#zzz').html(data); //not displaying anything although above one is was displaying
}
});
}
}
});
}, 1000);
});
</script>
Here is my Msg.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept){
$query= "SELECT Msg_ID,Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
$messages =array();
while($message=mysql_fetch_assoc($run)){
$messages[] =array('msgid'=>$message['Msg_ID'],
'sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
$dept=$_GET['dept'];
$messages = get_msg($dept);
$x=count($messages);
if($x){
foreach($messages as $message) {
if($x==count($messages)){
echo $message['msgid'];
}
$x--;
}
}
?>
Here is my Chat3.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept,$msgid){
$query1= "SELECT MAX(Msg_ID) as msg_id FROM chat" ;
$run1=mysql_query($query1);
$row = mysql_fetch_assoc($run1);
$result =$row['msg_id'];
$messages =array();
if($result>$msgid)
{
$query= "SELECT Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' AND Msg_ID>'$msgid' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
while($message=mysql_fetch_assoc($run)){
$messages[] =array('sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
else
{
return $messages;
}
}
$dept=$_GET['dept'];
$msgid=$_GET['msgid'];
$messages = get_msg($dept,$msgid);
if(count($messages)){
foreach($messages as $message) {
echo '<strong>'.$message['sender'].' Sent</strong><br>';
echo $message['message'].' <i><small><div align="right">'.$message['time_stamp'].'</i></small></div>';
}
}
else {
echo 'bad';
}
?>
The problem is the msgid
In your first AJAX Request you are setting the variable var msgid=data; which is in local scope.
I think you are trying to access that variable in the second AJAX request while sending the datas
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid}, // Trying to access the local variable of previous ajax request
EDIT:
Try removing the var from var msgid=data; in your first AJAX request. Removing var will make the variable GLOBAL, Although its not good to pollute the global scope, but you can definitely try out this for the time being

Server is crashing

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.

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

Categories