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

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.

Related

PHP - Old session variable on previous page (IE works fine!)

I have a session variable $_SESSION['name']. I set in a php file which is called with ajax inside a keyup event. It works well. Until a user uses the previous page button.
When a user uses this button (or mouse button), the last set session variable value is basically not set. It will return to an older set value (the one before the last one). I wonder how/why and what I can do about it.
I've read quite a lot stackoverflow (and other) solutions, but nothing so far seems to work.
HTML:
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
// blablabal more code
}
});
});
</script>
example.php:
$_SESSION['name'] = 'test';
Please note I'm starting the session on all of my pages with session_start(); and please note that I also tried to regenerate my session id with any hope that would do the trick.
You cannot achieve this you have to reload your page to see the changes.
although here is a suggestion to do this what you want to achieve.
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
$("[name='name']").val('Your response');
}
});
});
By doing this you can achieve what you are looking for. also if you load the page it will get the value from session

Show/hide div with jQuery and AJAX not working properly

I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)

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.

Retrieve PHP Variable via jQuery

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);

How can I add the content of a page in a div with Ajax?

I have a list in my site, and when I click each of the list items, I want the div next to them to reload with ajax, so as not to reload the whole page.
Here is my javascript
parameters = "category_id="+categoryId;
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
The ajaxFunction() function is the regular $.ajax() jQuery function, with "POST". In the "changeCategory.php" I call with include another php file.
The problem is that the whole page is reloaded instead of only the div. I want to use this ajax function I have, cause I want to send data to my php file.
Does anyone know what should I do to reload only the div?
Thanks in advance
Try this
$(document).ready(function(){
var parameters = {category_id:categoryId};
$.ajax({
url:'changeCategory.php',
type:'post',
data:parameters,
dataType:'html',
success:function(result){
$("#mydiv").html(result);
},
error:function(){
alert('Error in loading [itemid]...');
}
});
});
Also verify that when in your click event this line is written or not return false; This is required.
Try using load to load the div with the url contents -
$("#mydiv").load("changeCategory.php", {category_id: "category_id_value"} );
You can pass data to the url.
The POST method is used if data is provided as an object; otherwise, GET is assumed.
you could send a query to that PHP so it "understands" that it needs to output only the div, like this:
in your javascript:
//add the query here
parameters = "category_id="+categoryId + "&type=divonly";
var result = ajaxFunction("changeCategory.php", parameters);
$("#mydiv").html(result);
in your "changeCategory.php":
//add a query check:
$type = "";
if (isset($_POST['type'])) {
$type = $_POST['type'];
}
//then, depending on the type, output only the div:
if($type === "divonly"){
//output the div only;
} else {
//your normal page
}
$(document).ready(function() {
$.ajax({
url: "right.php",
type: "POST",
data: {},
cache: false,
success: function (response) {
$('#right_description').html(response);
}
});
});
The whole page is reloaded that means there may be an error in your javascript code
check it again
or try this one
function name_of_your_function(id)
{
var html = $.ajax({
type: "GET",
url: "ajax_main_sectors.php",
data: "sec="+id,
async: false
}).responseText;
document.getElementById("your div id").innerHTML=html;
}
you can use get method or post method....

Categories