Retrieve PHP Variable via jQuery - php

I know this questions has been asked in various forms, but I've been unable to find a response that squares with what I'm trying to accomplish. Total amateur, so any additional pointers are appreciated.
The Task:
Use a form on page1 to post data to PHP file, which then searches the MySQL table for rows corresponding to the $_POST[]. Then, the PHP file echoes the result as JSON_encode($variable). From there, the PHP file redirects the user back to page1, which (in theory) has a JQuery script that calls the $variable from the PHP file and create html with the data.
The Code:
PHP
<?php
ob_start();
session_start();
session_save_path('path');
mysql_connect("", "", "")or die(); mysql_select_db("db")or die();
$pname = $_POST['country'];
$result = mysql_query("SELECT * FROM project WHERE name = '$pname'");
$array = mysql_fetch_row($result);
echo json_encode($array);
header("page1.html");
?>
html/jquery/ajax
<script type="text/javascript">// <![CDATA[
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'page.php',
data: '',
dataType: 'json',
cache: false,
success: function(result) {
$('#content1').html(data);
},
});
});
// ]]></script>
<div id="content1"></div>
The php script works and echoes the JSON encoded variable, but nothing on #content1...
I have a feeling either my code is wrong, or the data is lost while posting to the PHP file and then redirecting.

You're trying to append the variable data to the content but the variable is called result. Try this:
<script type="text/javascript">// <![CDATA[
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'page.php',
data: '',
dataType: 'json',
cache: false,
success: function(result) {
$('#content1').html(result);//<- this used to be $('#content1').html(data);
},
});
});
// ]]></script>
<div id="content1"></div>
Additionally, as many have pointed out you are simply outputting the json at the moment - there is nothing in place to generate the table.

Change $('#content1').html(data) to $('#content1').html(result);

Related

Fetching JSON data from a php file with jQuery's $.ajax( ) function does not work

I am trying to understand the magic of the .ajax() function with jQuery. I am having a hard time getting what I want to be done. I basically want a div with content that refreshes every x time (about every 10 seconds). Mainly, this will output the latest posts that have been posted to a table in my database. Pretty much I am using this example to get an idea of how I can achieve my goal, but unfortunately I am not getting what I want.
I am trying to set my file so that when the refresh button is clicked, the div refreshes and brings up the latest posts.
On one side we have the index.php file:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Test page</title>
</head>
<body>
<h1>Welcome to the form</h1>
<h2>We are going to try to process this with AJAX</h2>
<h3>I hope it works!</h3>
<div id="content"></div>
<button id="refresh>Refresh!</button>
<script type="text/javascript">
$('#refresh').on('click', function(){
$.ajax({
type: "POST",
url: "process.php",
data: ,
error: function(data){
$('#content').text('Update unsuccessful!').
slideDown('slow');
console.log(data);
},
success: function(data){
$('#content').text('Update completed!');
console.log(data);
//somewhere over here use the $.getJSON() function
},
complete: function(data){
setTimeout(function(){
$('#content').slideUp('slow');
}, 3000);
}
});
});
</script>
</body>
</html>
And on the other hand, we have the process.php file that queries the results from the database:
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "root";
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sth = $db->query("SELECT * FROM posts");
$sth->setFetchMode(PDO::FETCH_ASSOC);
echo json_encode($sth);
Do you have any idea of how to accomplish this?
To structure my results, I want to use something like this inside the success part of my jQuery code:
$('#outputdiv').html(
//html code here fetching the JSON data to appear within custom divs (so I can apply css styles to them)
);
Also, do you know how can I automatize the div to bring new results using the same &.ajax() function every x time? I have read the documentation throughly and followed many examples, but I still cant get what I want!
Thanks in advance!
Cheers!
Edits:
-Fixed the echo json_encode, the "process.php", erased the data: line, and put the passing (data) into the success: error: and complete: areas and still doesnt work
first url should be string type so it would look like this
url: "process.php",
then in process.php file echo your result like this
echo json_encode($sth);
and in your error, success functions add an parameter like this
error: function(data){
//your code
},
success: function(data){
//your code
}
also your variable form_data is not needed according to your code. so remove this line
data: form_data,
Your success function must take data argument.
And i recommend you to read about $.getJSON shortcut for this case.
3 things...
url: process.php should be url: "process.php"
form_data isn't really defined anywhere
success: function(){ should be success: function (data) {
Well I think you need PDO fetch after setFetchMode. Also Its better to use send JSON Response headers in Ajax request
$data = array();
while ($row = $sth->fetch()) {
$data[] = $row;
}
header('Content-type: application/json');
echo json_encode($data);

Take html and variable with AJAX

I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});

Pass GET variable from URL to .js, and from the .js to .php

Hi I currently have a JS file being called to populate my html page with dynamic data. My JS file calls a PHP file to fetch stuff from my sqldb and my PHP file echos json_encode the stuff it got from the sqldb, which in turn is used to populate the html page.
My problem is that depending on what's in the url ie ?user=Bob, I want my js file to call the php file to search for Bob. Right now it searches for current user if ?user=xxxx is not specified. It seems the $GET['user'] is always null, thus it's not being passed because I suspect the JS file working as a middleman. Here are my code snippets:
My URL:
www.website.com/index.php?user=Bob
My HTML Code
<script type="text/javascript" src="js/get-data.js"></script>
My JavaScript
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
dataType: 'json',
success: function(response){
var name = response[0];
var location = response[1];
$('#name').html(name);
$('#location').val(location);
}
});
});
My PHP Code
$id;
if (isset($_GET["user"]))
{
$id = $_GET["user"];
}
else
{
$id = $_SESSION['loggedInUser'];
}
$query = "SELECT * FROM Persons WHERE User = '$user'";
if($result = mysqli_query($sqlconnection,$query))
{
$row = mysqli_fetch_row($result);
echo json_encode($row);
}
You need to specify the data attribute in your ajax call.
$.ajax({
type: 'GET',
data: $("#myForm").serialize(), //for example. You can change this to something relevant.
/*rest of the code*/
});
What this will do is prepare a GET request with the proper data, for example, http://path/to/backend/?key1=value1&key2=value2
I believe you want to do something like this
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
EDIT:
Thanks #Brad and #Ashwin Musjija for pointing out. I was focusing on answer too quickly that I overlook the possible non persistent XSS attack.

send data to a new window and use there [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Jquery post, response in new window
i have a table html in a page called results.php that looks like
GenID
ENSMUSG00000098791
ENSMUSG00000023441
ENSMUSG00000047431
results.php have this function
<script>
function contenidoCelda()
{
var table= $('#tabla_results');
cells = $('td');
for (var i=0,len=cells.length; i<len; i++)
{
cells[i].onclick = function()
{
var formData2 = new FormData(document.getElementById("formulario"));
formData2.append("gen_id",(this.innerHTML));
$.ajax({
type: "POST",
url: "test.php",
data: formData2,
cache: false,
processData: false,
contentType: false,
success: function(data)
{
alert(data);
window.open('test.php', '_blank');
}
});
}
}
}
</script>
i whant to use the data i send in the file test.php, not to return this to results.php, use in test.php, to generate the content dinamycally.
this is test.php
<?php
$data = $_POST['gen_id'];
system("mkdir $data");
echo "Hola";
echo $data;
echo '<xmp>';var_dump($data);echo '</xmp>';
?>
<html>
<link href="css/ui-lightness/jquery-ui-1.9.1.custom.css" rel="stylesheet">
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.1.custom.js"></script>
<body>
<form>
<p id = "testing"> Test page </p>
<?php if($data == "ENSMUSG00000047751") {echo "Good";} else {echo "Bad";} ?>
</form>
</body>
so here in test.php, it must show Good, if i click that genid in the table
but it show Bad, and returns Good to results.php
the test where i create a dir, whit the genid i click works fine
what i must do?
In your $.ajax call, try setting:
$.ajax({
type: "POST",
url: "test.php",
data: "testing123",
cache: false,
processData: false,
contentType: false,
});
And see if dir test123 is created, and echoed back.
If not, then the problem is in these two lines, specifically with your definition of var formData2:
var formData2 = new FormData($('#formulario')[0]);
formData2.append("gen_id",(this.innerHTML));
Check for typing errors, such as the comma in place of the semi-colon:
var table = document.getElementById('tabla_results'), <-- THIS IS A COMMA. TYPO?
cells = table.getElementsByTagName('td');
Also, you have a mix of jQuery and javascript. Why not standardize on jQuery? For example, the two lines above would be written like this in jQuery:
var table = $('#tabla_results');
cells = $('td');
Much less typing, yes?
Also, I'm sure you have, but are you sure you've included a link to the jQuery library? Such as:
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
I think the problem is with the way you define formData2:
var formData2 = new FormData($('#formulario')[0]);
Resulting in formData2 not actually being FormData.
Try switching it to:
var formData2 = new FormData(document.getElementById("formulario"));
This should solve the data problem.
Edit: About the edit to your question, if you want to post the results to another page, there really is no need to use ajax. Just use javascript on form submit to add the additional field with the ID (if you cannot add it like a hidden field...) and use a normal form submit.

pass jquery value to php variable

Am a noob so hope you can help!
I've got the following jquery code:
$("#single-home-container").html(post_id);
It then displays the value I want within the HTML on the page:
<div id="single-home-container"></div>
What I would like is to pass the value into a PHP variable to I can use the info in a MySQL query.
How do I do so? It's in WordPress so no separate files
Thanks
You can use jQuery.post() or jQuery.ajax().
Here some examples:
<script>
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
</script>
<script>
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
</script>
You'd need to use ajax. Something like this:
JQuery:
$('.locationID').click(function(){
var post_id = $(this).attr('rel'),
$container = $("#single-home-container");
old_html = $container.html();
$container.html('loading...');
$.ajax({
url : '/path/to/php/file.php',
data:{"post_id":post_id},
type: 'post',
dataType: 'json',
success: function(data){
$container.html(data.postBody);
},
error: function(data){
// possibly notify the user of the error
$container.html(old_html);
}
});
});
That assumes you have a field in your posts table called postBody
PHP
<?php
header('Content-type: application/json');
// $query_result = do mysql query with $_POST['post_id']
echo json_encode($query_result);
exit();
?>
That assumes that you want all the fields and you're returning all the fields, including postBody - and of course you have PHP 5.2.6+ or whatever version they added json_encode().

Categories