AJAX is posting to different PHP pages at the same time - javascript

I have a page user.php which is a template for different users pages (e.g. user.php?id=5). I run an AJAX script to monitor the database for new messages posted during a conversation with each user.
My problem is that when I post a message to user.php?id=5 it also appears on user.php?id=1 etc.
How do I ensure the real-time message is only sent to the correct user?
Script in user.php:
var refreshId = setInterval(function () {
$.ajax({
url: 'another_file.php',
data: { 'action': '<?php echo $lastID; ?>' },
dataType: 'json',
type: 'post',
success: function (data) {
var avatar = '<img src="images/avatars/' + data[1].avatar + '"/>';
if (compare_id != data[0].cr_id) {
$('#responses').prepend("<div class='row'><div class='col-xs-12'><div class='post_container_left_small' style='float:left;'><div class='reply_avatar'><div id='add_button_small'>" + avatar + "</div></div><div class='reply_text'><h3><span class='post_time'>now</h3>" + data[0].reply + "</div></div></div></div>");
}
compare_id = data[0].cr_id;
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}, 7500);
The php class function it calls:
public static function getLast($lastID) {
$lastID = (int)$lastID;
$result = mysql_query("SELECT * FROM mc_conversation_reply ORDER BY cr_id DESC LIMIT 1");
$userC = new UserTools();
while($row = mysql_fetch_array($result)) {
//echo json_encode($row);
$userRObj = $userC->get($row['user_id_fk']);
//echo json_encode($userRObj);
echo json_encode(array($row,$userRObj));
}
}

The whole idea is that the user.php is a common "view" (of the mvc model) for users on your app and that by using query parameters you must fetch information for just that user. You have chosen to use AJAX (wich is js and runs only under the view layer of your app, in this case, the user's browser) and therefore you need to have some js code listening to some action in order to have two things done: Have php controller layer update the query parameter id and after that run the ajax request again to fetch the database data and update the html fields.

Related

How to get data in PHP from AJAX jQuery request

So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.

Joomla & JS; Sending data from form to Controller

I am having trouble with a form I created and trying to redirect the data someplace else by a JavaScript method that I call whenever the submit button is clicked.
The first thing that is happening, is that the form is created and filled in, then the user will click on the HTML generated button with this action in it:
onclick="javascript:saveEssayScore(<?php echo $key . "," . $pid; ?>);"
Secondly the script file is read and performed. The code is below:
<script type="text/javascript" language="javascript">
document.body.className = document.body.className.replace("modal", "");
function saveEssayScore(key, pid){
var user_id = document.getElementById("user-"+key).value;
console.log("user " + user_id);
var grade = document.getElementById("grade-"+key).value;
console.log("grade " + grade);
var teacher_answer = document.getElementById("feedback-"+key).value;
console.log("teacher_answer " + teacher_answer);
var question_id = document.getElementById("question-"+key).value;
console.log("question_id " + question_id);
var quiz_id = document.getElementById("quiz-"+key).value;
console.log("quiz_id " + quiz_id);
var req = new Request.HTML({
method: 'post',
url: "<?php echo JURI::base();?>index.php?option=com_guru&controller=guruAuthor&task=saveFeedback&tmpl=component&format=raw",
data: { 'pid' : pid, 'user_id' : user_id, 'grade' : grade, 'teacher_answer' : teacher_answer, 'question_id' : question_id, 'quiz_id' : quiz_id},
onSuccess: function(response, responseElements, responseHTML){
alert('yeyy');
}
}).send();
}
Now in the URL, it is read to run the method (task) saveFeedback() in the controller guruAuthor which is in the component com_guru.
The problem I am having is, how do I read the data that I just send through the HTML request? I am trying stuff like $user_id = JRequest::getVar("user_id"); But whenever I'm trying to echo or dump, it is returned to me but empty. Not the values that I am dumping in JavaScript console.log(user_id);
JRequest is deprecated
Use JInput instead. Read - Retrieving request data using JInput
In your mentioned code - if the controller function is being called, try this code-
$jinput = JFactory::getApplication()->input;
$user_id = $jinput->get('user_id', '', 'INT');
I hope this helps.

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

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

PHP/ajax - prevent user from submitting a url with get variables except in ajax call

Hi I have a jquery function that uses an ajax call to send information to a php page. It sends this information using the get method. My concern for this is that what if a user goes directly to the php page and enters some get variables in the url. Whilst sensitive data is not being processed by the php script, I still want just the ajax call to be able to interact with the script and not a user (via entering the url in their browser). How can this be done?
js code
$.ajax({
type: "GET",
url: "/add.php",
data: 'id=' + itemid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("desc").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
php code
$output = array();
$output[0] = $itemname . " " . $_GET['id'];
$output[1] = $itemdescription;
$output[2] = $itemprice;
echo json_encode($output);
exit();
Unfortunatley I cannot use the POST method, as this clashes with some code.
Most ajax frameworks (like jQuery) are sending the HTTP_X_REQUESTED_WITH header. Here is already described how to retrieve it's value.
I think it's really not recommended to secure your script using header values because you can manipulate the request headers (e.g. curl). Which method you use, GET, POST, PUT or DELETE doesn't matter, your server side api must be secured. If you want to prevent repeated calls to that url, take a look at captcha services or add uids to urls that are only valid once.
For POST or GET request, if you are doing insert in your database you HAVE TO
- securize your form
- securize posted data
Plus, you should consider prefering using array of key/values
$output = array(
'id' => $_GET['id'],
'name' => $itemname,
'description' => $itemdescription,
'price' => $itemprice
);
echo json_encode($output);
js
$.ajax({
type: "GET",
url: "/add.php",
data: 'id=' + itemid,
dataType: "json",
success: function ( item ) {
document.getElementById("name").innerHTML = item.name + " " + item.id;
document.getElementById("desc").innerHTML = item.description;
document.getElementById("price").innerHTML = item.price;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
To securize your ajax query, you must escape html entities, sql injection.
To securize the form, you could generate a token for your each form, and encode data before sending them to the server, the client won't be able to read what kind of data you're sending to the server.
On the server side, you could decode before your insert.

Categories