How to GET javascript data in PHP file without page reload - javascript

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!

$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});

You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices

I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

Related

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

redirect page using ajax & jquery (php)

i want to redirect from page a to page profile and in between there is a post session on them. in this case let's say the data is variable $name in string. so far my code is like this on page a
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
//the ajax script
$.ajax({
type: 'POST',
url: 'b.php',
data: 'result='+$name,
success: function() {
window.location.href = "profile.php"; // replace
}
});
});
and on page b the code is:
<?php echo $_POST['result']?>
the outcome should be the value from result in which determined on page a.
but so there is an error message saying unidentified index. so where am i doing wrong?
Could it be, that your data parameter is wrong?
I have my ajax calls as folowing:
jQuery.ajax({
type: "POST",
url: "b.php",
data: {
result: $name
},
success: function() {
window.location.href = "profile.php"; // replace
}
});
It is a new request after the redirect. In order to access the result you need to sotre it in som kind of session or pass it again.
You can pass it like this, then it will be in $_GET
success: function(data) {
window.location.href = "profile.php?result="+data; // replace
}

json import breaks down but from same server source

I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

mysql query executed even though fields are empty

I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>

Categories