Is this piece of jquery ajax code correct? - javascript

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

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

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>

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

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Ajax.stop function with json request issue

I am trying to read from a database some data but without waiting for the page to load, so I created an ajax post that starts sending data when page is ready, now after ajax completes I need to read the values from another file. The problem is that after the ajax completes, json that is reading the data is running indefinite.
JQUERY
<?php $url = $_GET['url']; ?>
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0(document).ready(function () {
var domain = '<?php echo $url; ?>';
$.ajax({
type: 'POST',
url: 'lib/ajax.php',
data: {
action: 'get_all_seo_details', // function that collects data
domain: domain // the domain that is being send to the function in order to get data
},
success: function (data) {
// doesn't need to echo anything only to insert the data, which it done properly
}
});
// Below is the second part of the script that starts when ajax stops
$(document).ajaxStop(function () {
$.getJSON('lib/get-details.php', function(data) {
var twitter_followers = data.twitter_followers;
$('#twitter-followers').html(twitter_followers);
});
// data is being read correctly but it loops repeatedly in the console without finishing
});
});
PHP - get-details.php, reading the data from database after getting inserted with ajax
if (!isset($_SESSION)) {
sec_start();
}
global $db;
$domain = isset($_SESSION['domain']) ? $_SESSION['domain'] : '';
if ($domain == '') {
$domain = $db->query("SELECT * FROM seo_data");
} else {
$domain = $db->query("SELECT * FROM seo_data WHERE domain = '$domain'");
}
$domain_now = $domain->fetch_assoc();
$twitter_followers = (int) $domain_now['twitter_followers'];
echo json_encode(array('twitter_followers' => $twitter_followers));
I'm not sure but when the first AJAX request stops
$(document).ajaxStop(function (){....
starts a new one with
$.getJSON('lib/get-details.php', function(data) { ...
When this second one ends, maybe
$(document).ajaxStop(function (){....
is called again which starts again the 2nd request and so on

Categories