$.ajax post loads html code from current page instead of requested php - javascript

im new to javascript, but have to use it for an ajax load of a .php
This is my ajax.js
$(document).ready(function(){
var url = $(location).attr('href');
var uA = navigator.userAgent;
$.ajax({
type: "POST",
url: "neo4j.php",
data: {"url": url, "userAgent": uA}
});
alert(url);
});
It should post the datas to neo4j.php.
My Start.php looks like
<head><title>Start</title></head>
<?php
include("db.php");
$sql = "SELECT * FROM category_paths LIMIT 10";
$pattern = mysql_query($sql);
while($row = mysql_fetch_object($pattern)){
if ($row->descendant_id == 1) {
echo "<a href='http://localhost/2play/Start.php'>$row->descendant_id</a><br>";
}else {
echo "<a href='http://localhost/2play/Section.php/?sec=$row->descendant_id'>$row->descendant_id</a><br>";
}
}
?>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script></footer>
Here my code works.
But if I click on a link to section.php
<head><title>Section</title></head>
<?php
include("db.php");
echo "<a href='http://localhost/2play/Start.php'>1</a><br>";
if(isset($_GET["sec"])) {
$sec = $_GET["sec"];
}
$sql = "SELECT * FROM category_paths WHERE ancestor_id = $sec AND length = 1";
$pattern = mysql_query($sql);
while($row = mysql_fetch_object($pattern)){
echo "<a href='http://localhost/2play/Game.php/?game=$row->descendant_id'>$row->descendant_id</a><br>";
}
?>
<div id="js">test</div>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</footer>
My ajax.js dont load the js code, instead it load the html-code of the current page. Copy from loaded section.php with firebug:
<html>
<head>
<title>Section</title>
</head>
<body>
1
<br>
123
<br>
124
<br>
125
<br>
156
<br>
197
<br>
<footer>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="ajax.js" type="text/javascript">
<--Here the script should be loaded, but it relaods the raw non-php code from section.php-->
<head><title>Section</title></head>
<a href='http://localhost/2play/Start.php'>1</a><br>
<footer><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</footer>
<--End-->
</script>
</footer>
</body>
</html>
What I already found out:
If I manually add some get-vars to the Start.php url like
http://localhost/Start.php?foo=bar
the script wont work and do some failure as above.
SOLVED
Ok I found my mistake, and cant believe it.
It is because i had an slash in the link before I set the get-vars http://localhost/2play/Section.php**/**?sec=$row->descendant_id'> . After deleting it, the problem disappeared.

You should nod declare variable inside $.ajax. Try something like this
$(document).ready(function(){
var data1 = "foo",
data2 = "bar";
$.ajax({
type: "POST",
url: "foobar.php",
data: {"data1": data1, "data2": data2}
});
alert(data1);
});
More about AJAX can follow the link

Ok I found my mistake, and cant believe it. It is because i had a slash in the link before I set the get-vars
http://localhost/2play/Section.php**/**?sec=$row->descendant_id'>
After deleting it, the problems disappeared.

Related

Refresh a div with PHP variable using Jquery

I would like to refresh a div every second with a PHP variable using Jquery.
I have a simple PHP file with a variable date:
<?php
$date = date('d/m/Y H:i:s');
?>
I have a HTML file with the following code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
function request() {
$.ajax({
url: "date.php",
dataType: "text",
cache: false,
success: function(data) {
var json = $.parseJSON(data);
$('#result').html(json.date);
}
});
}
setTimeout(request, 1000);
});
</script>
</head>
<body>
<div id="result">
</div>
</body>
</html>
But the result is a blank page. I can not make it work. I would like your help.
I would like to refresh every second a PHP variable using Jquery.
You need to print date variable:
<?php
$date = date('d/m/Y H:i:s');
echo $date;
?>

jQuery ajax response not displaying when returning to current page

I'm attempting to post some data back to the same page through ajax. In the example below the $name variable is not being updated in my page once the button is clicked. However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (i.e. <div>Matthew</div>) - the page just isn't being updated with this response. Any ideas for how to fix this would be greatly appreciated.
The code I have is:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name = "No name!";
}
else{
$name = $_POST["name"];
}
}
?>
<script>
$(document).ready(function(){
$("button").click(function(){
var mydata = {name: "Matthew"};
$.ajax({
type: 'POST',
data: mydata,
success: function(data){
console.log(data);
}
});
});
});
</script>
<button>Send an HTTP POST request to a page and get the result back</button>
<div id="name">
<?php echo $name;?>
</div>
</body>
</html>
It is because <?php echo $name;?> does not run again when doing the ajax call. You have to replace the content of the div in the success function like this:
success: function(data){
$("div").html(data);
}

Share config in php with javascript + ajax (json) in usage

I am trying to share a config.inc.php in php with javascript. It works, but not with ajax... there is always the "error-function" called. Is there any way to share the config file with an working ajax?
I am using it in an apache cordova project, with bootstrap and jQuery.
Here is a part of my index.html file:
<html>
<head>
<title></title>
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="lib/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="lib/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="config.inc.php"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
console.log(config_url);
jQuery.ajax({
url: config_url,
type: "POST",
dataType: "json",
data: "param=no",
success: function(html){
doSomething();
});
}, error: function(e){
alert(e); //always an alert :/
}
});
});
</script>
</head>
<body></body>
</html>
Here is my config.inc.php:
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
$config["db"]["host"] = "localhost";
$config["db"]["database"] = "myDatabase";
$config["db"]["username"] = "root";
$config["db"]["password"] = "";
$config["db"]["port"] = null;
$config["db"]["socket"] = null;
?>
var config_url = <?php echo json_encode($config["url"]); ?>; //if i remove this line, ajax will work and call the "success part".
And finally the last file "fetchdata.php" for database connection:
<?php
// Allow access via php
header('Access-Control-Allow-Origin: *');
// Load configuration
require 'config.inc.php';
global $config;
$sqlconn = mysqli_connect($config["db"]["host"], $config["db"]["username"],
$config["db"]["password"], $config["db"]["database"], $config["db"]["port"],
$config["db"]["socket"]) or die(mysqli_error());
$dataquery = mysqli_query($sqlconn, "SELECT * FROM table_profil");
$arr = array();
while($row = mysqli_fetch_object($dataquery)) {
array_push($arr, array("key" => $row->key, "value" => $row->value));
}
print_r(json_encode($arr));
?>
I used XAMPP for testing. The output is
var config_url =
"http://192.168.1.Y/fetchdata.php";[{"key":"size","value":"150"},{"key":"color","value":"green"}]
Without the ''var [...] .php";'' output, it will work... But I liked to share the config.
you used javascript var in php without <script> tag? How come? use
<script>
var config_url = '<?php echo json_encode($config["url"]); ?>';
</script>
instead of
var config_url = <?php echo json_encode($config["url"]); ?>;
with that way you can pass config_url with javascript but your ajax will not work .. cause ajax not work through servers so you can't use "http://192.168.1.Y/fetchdata.php" in your ajax url .. in your ajax url just use url:'fetchdata.php', and check you link to its path
Thanks mohamed-yousef and Michael, I solved it with a part of your answers. You shown me the error and gave me hints for the solution :).
Ted wrotes the solution in Shared JSON data for php and Javascript/Ajax . I use a "GET"-Param for supporting javascript. Because my "fetchdata.php" won't have any javascript, I use it without the param => no javascript output if not needed.
My index.php includes the config with a "js" parameter; looks like ...
<script type="text/javascript" src="config.inc.php?js"></script>
... and my "config.inc.php" looks like
<?php
global $config;
$config["url"] = "http://192.168.1.Y/fetchdata.php";
....
if (isset($_GET["js"])) {
echo
'
var config = [];
config["url"] = "' . $config["url"] . '";
';
}
?>
No changes in "fetchdata.php".
This solution is working for me. Thanks everybody!

AJAX cannot print elements onclick

I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].

How do I pass a variable from one php file to a javascript file?

I am currently trying to make a site where I put in info in on my html side, it send the info to the php file and grabs info from another site depending on what you put in on the html side.
To make this more clear this is how it works:
You put in your username in the html site(where the javascript code
is).
Then it sends your username to the php file.
The php file gets the information, puts it in a link and request it.
It grabs information from this request (highscores page).
This is where it stops.
I don't know how to return the information to my javascript file.
This is my code:
html/javascript page:
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<script>
function test() {
var username = "Exzib";
window.location.href = "grabinfo.php?username=" + username;
}
</script>
</body>
</html>
This is my php file: (grabinfo.php)
<html>
<head>
</head>
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
echo $formatxp;
}
?>
<body>
</body>
</html>
So how do I proceed to send the $formatxp to my javascript?
Thanks
So what you do is execute:
window.location.href = "grabinfo.php?username=" + username;
This causes the browser to navigate to grabinfo.php and display the information that you want. Except that you don't want the information to be displayed, you want to retrieve it into a JavaScript variable, right?
To do so, don't set window.location.href. Instead call your script using AJAX. You'll find plenty of tutorials on AJAX out there. This will allow you to capture the output of your PHP script.
Change the following line
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
to
$formatxp = str_replace(array('$',',','.',' '),'',$xp);
And to pass the variable to Javascript you can do something like this.
<script type="text/javascript">
var $formatxp = '<?php echo $formatxp; ?>';
</script>
Write a script tag and set the variable equal to your PHP variable.
<script>
var thing = '<? echo $formatxp; ?>';
</script>
This is going to be easy as you already include jQuery. (Using ajax)
Look
<html>
<head>
<script type="text/javascript" src="./aloticcalc_files/jquery.min.js"></script>
</head>
<body>
<label>Type your username:<input id="username" type="text"></label>
<input id="submit-button" type="button" value="Get my highscores!">
<p id="response"></p>
<script>
//When user clicks "submit-button" button
$("#submit-button").on('click', function() {
var username = $("#username").val();
//We request our php with the username
$.get("grabinfo.php?username=" + username, function(xpValue) {
//When we receive the response from php then we add it to a "p" tag
$("#response").text("LOL your xp is: "+xpValue+". NOOOOOOOB!!");
});
});
</script>
</body>
</html>
And that's it!
More info at http://api.jquery.com/on/
And http://api.jquery.com/get/
http://api.jquery.com/text/
http://api.jquery.com/val
And well the whole jQuery API documentation http://api.jquery.com
EDIT:
OH. You have to change grabinfo.php. It should only have this:
<?php
$username = $_GET['username'];
include_once('simple_html_dom.php');
if(isset($_GET['name'])) {
$html = file_get_html('https://alotic.com/hs/?name='.$username);
$xp = $html->find('td', 10);
$formatxp = $result=str_replace(array('$',',','.',' '),'',$xp);
if(empty($formatxp)) {
echo "ERROR: Invalid could not find xp with username {$username}";
}
else {
echo $formatxp;
}
}
else {
echo "ERROR: Invalid arguments";
}

Categories