I'm doing GeoRef application. This is my index.php:
<!doctype html>
<html lang="es">
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://www.ign.gob.ar/argenmap/argenmap.jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
url: 'getcoord.php',
dataType: 'json',
error: function(){
alert("ERROR");
},
success: function(res) {
var ico;
ico='Icon.png';
var marcador;
$('#mapa').argenmap();
$('#mapa').centro(-34.597907,-58.385557)
$('#mapa').zoom(4);
$('#mapa').capaBase('satellite');
for(var i=0;i<res.length;i++)
{
marcador=[{lat: res[i].latitud, lng:res[i].longitud,icono:ico}];
$('#mapa').argenmap().agregarMarcadores(marcador);
}
} });});
</script>
</head>
</html>
And this is my getcoord.php file:
<?php
include("config.php");
require("db.inc");
$sql = "SELECT * FROM datos_mapa";
$res = buscar($sql);
$arry=array();
foreach ($res as $r)
{
$arr = array('longitud' => $r['longitud'],'latitud' => $r['latitud']);
array_push($arry,$arr);
}
echo json_encode($arry);
?>
My problem is that, when I run getcoord.php using json_encode($arry), I see the information I want but, it doesn´t return to index.php. I´ve tried:
Using json in dataType. Gives me a Json Object but with Object in each field instead of latitude and longitude.
Using jsonp in dataType. Results an error.
Using text in dataType. I get the information I want, but as a string not as an Object.
Replacing echo json_encode($arry) with:
a) json_encode($arry);
b) print_r(json_encode($arry));
c) echo $_GET['receive'].'('.json_encode($arry).');';
But getting the same error.
Why I´m not getting the information in the format I want?
I was trying this code at work where apache is configured and didn´t work (keeps getting error when using dataType: 'json'). In my personal computer, using xampp, it works. So I think the code is right. Is there anything else I should configure?
Related
When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.
I'm using a digital signage player that allows me to use HTML and javascript to display things , in my case I'm building a menu board with a list of products and prices. I've already created a php system to create entries for products and prices and those values are stored in a MySQL database. What I would like to do is have a PHP script output the mysql data in JSON format, then have a cross domain ajax request for the products and prices to display on the menu board. Unfortunately the menu board cannot support PHP so I have to improvise and get the data through JSON. I've been pulling my hair the past couple of hours trying to figure this out but I can't seem to get it. Any help would be appreciated.
EDIT 1
I have a php script and html file but can't seem to have the data show. Here are the files below
showjson.html
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
url:"http://localhost/blakewilson/api.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
$("#userdata tbody").html("");
$.getJSON(url,function(data){
$.each(data.members, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.postID+"</td>"
+"<td>"+user.postProduct+"</td>"
+"<td>"+user.postPrice+"</td>"
+"</tr>" ;
$(tblRow).appendTo("#userdata tbody");
},
error:function(){
alert("Error");
}
});
</script>
api.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("dn_name") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo $_GET['callback']."(".json_encode($arr).");"; // 09/01/12 corrected the statement
?>
EDIT 2
This code give me an alert with success so I know it works.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery PHP Json Response</title>
<style type="text/css">
</style>
</head>
<body>
<div id="msg"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
url:"http://localhost/blakewilson/api.php",
dataType: 'jsonp',
success:function(json){
alert("Success");
},
error:function(){
alert("Error");
}
});
</script>
</body>
</html>
I'm trying to get a few values like postID, postProduct, and postPrice from JSON, but I can't seem to figure it out. I'm very new to jQuery/AJAX etc.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery PHP Json Response</title>
<style type="text/css">
</style>
</head>
<body>
<div id="msg"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
url:"http://localhost/blakewilson/api.php",
dataType: 'jsonp',
success:function(json){
// loop through the productg here
$.each(json.members,function(i,dat){
$("#msg").append(
'<div class="members">'+
'<h1>'+dat.postID+'</h1>'+
'<p>Firstname : <em>'+dat.postProduct+'</em>'+
'<p>SurName : <em>'+dat.postPrice+'</em></p>'+
'<hr>'+
'</div>'
);
});
},
error:function(){
alert("Error");
}
});
</script>
</body>
</html>
EDIT 3
What I'm basically trying to do is take this project: http://tournasdimitrios1.wordpress.com/2011/11/04/how-to-generate-json-with-php-from-mysql-and-parse-it-with-jquery/ and make it work cross domain. That is all I need.
EDIT 4
This is the output of the api.php file. It's throwing an error "Notice: Undefined Index"
Notice: Undefined index: callback in E:\xampp\htdocs\blakewilson\api.php on line 13
([{"postID":"8","postProduct":"Synthetic Oil Change","postDollar":"29","postCents":"95","postDate":"2014-08-12 12:11:00"},{"postID":"9","postProduct":"Tire Rotation","postDollar":"16","postCents":"95","postDate":"2014-08-12 12:11:10"},{"postID":"10","postProduct":"Rotate and Balance","postDollar":"39","postCents":"95","postDate":"2014-08-12 12:11:21"},{"postID":"11","postProduct":"4-Wheel Alignment","postDollar":"79","postCents":"95","postDate":"2014-08-12 12:11:35"},{"postID":"12","postProduct":"Cooling System Service","postDollar":"129","postCents":"95","postDate":"2014-08-12 12:11:51"},{"postID":"13","postProduct":"Transmission Flush","postDollar":"189","postCents":"95","postDate":"2014-08-12 12:12:07"},{"postID":"14","postProduct":"AC Performance Service","postDollar":"69","postCents":"95","postDate":"2014-08-12 12:12:19"}]);
the Below link works well for me, you can try
http://jquery-howto.blogspot.in/2013/09/jquery-cross-domain-ajax-request.html
Not sure whats in the
echo $_GET['callback']."(".json_encode($arr).");";
But you might try removing it all down to
echo json_encode($arr);
If you need to send 2 pieces of data back, just build that into another array. Such as:
echo json_encode(array('message' => $_GET['callback'], 'data' => $arr));
I can't seem to get the 123.php return information to use in the html document where I use jQuery-AJAX-thing (to change the content of div named div1).
Im pretty new to JavaScript, PHP and html; but tried some tutorials now and can't seem to make em fit my needs so would really appriciate some help.
Here is my 123.html that should use AJAX-jQuery thing to call my 123.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "/123.php",
data:{id:"3", name:"John Doe"},
success:function(response){
alert('ok-'+data+'-'+respText+'-'+xhr);
$("#div1").html(respText);
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
</script>
</head>
<body>
along with the 123.php
<?php
$my_id = trim($_REQUEST['id']);
$my_name = trim($_REQUEST['name']);
$file = '123.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append to the file
$current .= 'time:' . time() . ',id:' . $my_id . ',name:' . $my_name . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
echo 'received following: id: ' . $my_id . ' and name: ' . $my_name;
?>
The 123.txt was just to see if the php file responded, and it does, but only when I pass
/123.php?id=7&name=Jane%20Doe
Elsewhere using the 'post' method, no response (gets errors from the JavaScript)
So I guess it's the structure of AJAX/jQuery;
for the attempt listed above, I get the error in JavaScript-console "Uncaught error: reference not defined"
and when I use the following 123.html instead (replacing the other 123.html)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").post("/123.php",{id:"3",name:"John Doe"},function(data,status){alert("Data: " + data + "\nStatus: " + status);});
});
});
</script>
</head>
<body>
<div id="div1">Text that should be changed</div>
<button>Press me, I'm a button</button>
</body>
</html>
I get "Uncaught TypeError: Undefined is not a function", I tried to look it up and some people wrote that it could be solved inserting
(function ($) {
$(document);
}(jQuery));
However it did not (inserted it in the very top, just below the script-start-tag )
I can't seem to figure what I'm doing wrong, and I really appriciate any help and directions as for where to look.
Thanks in advance
Your php is not returning JSON or XML therefore you cannot get data. Replace this
success:function(response){
alert('ok-'+data+'-'+respText+'-'+xhr);
$("#div1").html(respText);
},
with this
success:function(response){
alert('ok-'+response);
$("#div1").html(response);
},
I can send a query to mysql database with following code:
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
My questions is, Is there any way to send a query with just a click on some text.
Let's example: there are a text name Reply. I want if i click this Reply text then mysql database field value (field name: Reply, type: int) will be increase by 1.
Sorry I DON'T KNOW ABOUT JAVASCRIPT/AJAX:(
FINAL UPDATER CODE TO #DEVELOPER:
<html>
<head>
<title>Untitled Document</title>
</head>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
<body>
echo "<a href='#' id='mylink'>Reply</a>";
</body>
</html>
Php page:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
?>
You should have this link or button to be clicked wired to an ajax call using jQuery
http://api.jquery.com/jQuery.ajax/
It should call a php page, which contains the query you're looking to run. You can pass in arguments with the ajax call as well, so that your $message and $replyno are set properly before executing.
<script>
$("#mylink").click(function() {
$data = $("#myform").serialize();
$.ajax({
url: "postquery.php",
data: $data
}).done(function() {
$(this).addClass("done");
});
});
</script>
then your php page would look something like this:
<?php
...
$message = mysql_real_escape_string($_REQUEST['message']);
$replyno = mysql_real_escape_string($_REQUEST['replyno']);
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
....
?>
Excaping your incoming strings using "mysql_real_escape_string" is always important to prevent SQL Injection attacks on your database.
Your HTML should look something like this:
<html>
...
<input type="textarea"></input>
Reply
...
</html>
This will cause the previously stated jquery statement to trigger when "Reply" is clicked.
Here is with your updated code. I corrected the link ID and also removed the form serialization data since your test code does not appear to need it. I also added the reference to the jQuery library:
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
</head>
<body>
<a href='#' id='mylink'>Reply</a>
</body>
</html>
The problems you're likely seeing are because of your query, not the front end code. Try adding some debug code like this:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
if(!$sql)
{
echo mysql_error();
}
?>
Or try checking your servers error logs.
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
You have to use jquery and ajax like this:-
<script type="text/javascript">
$j(document).ready(function() {
$j('#reply').click(function(){
jQuery.ajax({
url: "test.php", //Your url detail
type: 'POST' ,
data: ,
success: function(response){
}
});
});
});
</script>
In the file "updat_post.php" write:
If(isset($_GET['visit_post']))
$pdo->query('update posts set counter = counter+1');
In your js/jquery file on document ready write:
$('#mybutton').click(function() {
$.post('update_post.php', {visit_post: true});
});
I am getting this error on var data =<?php echo serialize($msg);?>; line of the code below. console also raises data not defined error. I f put quotes around data, then this error goes but 1st error stays.
EDITED
//Raw xml
$result = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($result);
return $xml;
}
?>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
</head>
<body>
<script type="text/javascript"> <?php $msg = searchResults('windows');?>;
var data ="<?php echo serialize($msg);?>";
</script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "script.php",
type: "POST",
data: data,
success: function(){
alert("success");
}
});
return false;
});
</script>
</body>
</html>
I tried to see but couldn't figure out any problem
this is script.php
<?php
var_dump($_POST);
?>
this is xml from twitter
var data =O:16:"SimpleXMLElement":5:{s:2:"id";s:43:"tag:search.twitter.com,2005:search/#DIYSe_D";s:4:"link";a:4:{i:0;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"text/html";s:4:"href";s:45:"http://search.twitter.com/search?q=%23DIYSe_D";s:3:"rel";s:9:"alternate";}}i:1;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:20:"application/atom+xml";s:4:"href";s:58:"http://search.twitter.com/search.atom?q=%23DIYSe_D&rpp=100";s:3:"rel";s:4:"self";}}i:2;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:37:"application/opensearchdescription+xml";s:4:"href";s:40:"http://search.twitter.com/opensearch.xml";s:3:"rel";s:6:"search";}}i:3;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:20:"application/atom+xml";s:4:"href";s:84:"http://search.twitter.com/search.atom?q=%23DIYSe_D&rpp=100&since_id=7856019371724800";s:3:"rel";s:7:"refresh";}}}s:5:"title";s:25:"#DIYSe_D - Twitter Search";s:7:"updated";s:20:"2010-11-24T21:53:28Z";s:5:"entry";a:3:{i:0;O:16:"SimpleXMLElement":7:{s:2:"id";s:44:"tag:search.twitter.com,2005:7552404006371328";s:9:"published";s:20:"2010-11-24T21:53:28Z";s:4:"link";a:2:{i:0;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"text/html";s:4:"href";s:50:"http://twitter.com/_smir/statuses/7552404006371328";s:3:"rel";s:9:"alternate";}}i:1;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"image/png";s:4:"href";s:67:"http://s.twimg.com/a/1289849896/images/default_profile_5_normal.png";s:3:"rel";s:5:"image";}}}s:5:"title";s:59:"#DIYse_D DELIVERAB: twitter messages 2_inc 1, 19th OCT 2010";s:7:"content";s:248:"<a href="http://search.twitter.com/search?q=%23DIYse_D"
onclick="pageTracker._setCustomVar(2, 'result_type', 'recent', 3);pageTracker._trackPageview('/intra/hashtag/#DIYse_D');"><b>#DIYse_D</b></a> DELIVERAB: twitter messages 2_inc 1, 19th OCT 2010";s:7:"updated";s:20:"2010-11-24T21:53:28Z";s:6:"author";O:16:"SimpleXMLElement":2:{s:4:"name";s:13:"_smir (Smeer)";s:3:"uri";s:24:"http://twitter.com/_smir";}}i:1;O:16:"SimpleXMLElement":7:{s:2:"id";s:44:"tag:search.twitter.com,2005:7551711354822656";s:9:"published";s:20:"2010-11-24T21:50:42Z";s:4:"link";a:2:{i:0;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"text/html";s:4:"href";s:58:"http://twitter.com/Babar_Shahzad/statuses/7551711354822656";s:3:"rel";s:9:"alternate";}}i:1;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"image/png";s:4:"href";s:103:"http://a1.twimg.com/profile_images/1090185625/29465_391454998679_533808679_3864564_6071800_n_normal.jpg";s:3:"rel";s:5:"image";}}}s:5:"title";s:58:"#DIYse_D DELIVERAB: twitter messages 2_inc2, 24th OCT 2010";s:7:"content";s:247:"<b>#DIYse_D</b> DELIVERAB: twitter messages 2_inc2, 24th OCT
2010";s:7:"updated";s:20:"2010-11-24T21:50:42Z";s:6:"author";O:16:"SimpleXMLElement":2:{s:4:"name";s:32:"Babar_Shahzad (Babar Shahzad Ch)";s:3:"uri";s:32:"http://twitter.com/Babar_Shahzad";}}i:2;O:16:"SimpleXMLElement":7:{s:2:"id";s:44:"tag:search.twitter.com,2005:7550668919283712";s:9:"published";s:20:"2010-11-24T21:46:34Z";s:4:"link";a:2:{i:0;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"text/html";s:4:"href";s:58:"http://twitter.com/Babar_Shahzad/statuses/7550668919283712";s:3:"rel";s:9:"alternate";}}i:1;O:16:"SimpleXMLElement":1:{s:11:"#attributes";a:3:{s:4:"type";s:9:"image/png";s:4:"href";s:103:"http://a1.twimg.com/profile_images/1090185625/29465_391454998679_533808679_3864564_6071800_n_normal.jpg";s:3:"rel";s:5:"image";}}}s:5:"title";s:53:"#DIYse_D DELIVERAB: twitter messages 1, 9th OCT 2010";s:7:"content";s:242:"<b>#DIYse_D</b> DELIVERAB: twitter messages 1, 9th OCT 2010";s:7:"updated";s:20:"2010-11-24T21:46:34Z";s:6:"author";O:16:"SimpleXMLElement":2:{s:4:"name";s:32:"Babar_Shahzad (Babar Shahzad Ch)";s:3:"uri";s:32:"http://twitter.com/Babar_Shahzad";}}}};
This is my json equivalent code for same but its not working. I put it here because many if not all people are referring me add json to this code i.e OP, actually what I was wanting here but OP to send xml to php as json did not work for me earlier'
*This code raises no console errors, but failure alert is ouput * curl is sending results, I have tested that in a test php block just before ajax in HTML.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<?php
function searchResults($q) {
$host = "http://search.twitter.com/search.atom?q=" . urlencode( $q ) . "&rpp=100";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//Raw xml
$result = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($result);
return json_encode($xml);
}
?>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
</head>
<body>
<script type="text/javascript"> var msg_top = <?php echo searchResults('windows');?>;
</script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "script.php",
type: "POST",
dataType: "json",
data: msg_top,
success: function(msg){
alert("success");
}
});
alert("failure");
});
</script>
</body>
</html>
Try
var data="<?php echo json_encode(serialize($msg));?>";
EDIT: I'm sorry, the json_encode() function automatically adds the quotes to strings, so the code should look like:
var data=<?php echo json_encode(serialize($msg));?>;
And there's some redundant semicolon (;) after the first ?>, you should remove it.
serialize does not output JavaScript.
Try json_encode instead.
You're emitting Javascript code that contains the raw return value of PHP's serialize method.
This return value is not valid Javascript syntax, so you're getting a syntax error.
You need to wrap it in a string, and hope and pray that it never includes quotes or newlines.
Also, you probably want to pass the data variable to $.ajax, not the literal string "data".
<?php $msg = searchResults('windows');?>; Why is ; here? (the last one)
Edit:
Is something that i dont understand here
<script type="text/javascript"> <?php $msg = searchResults('windows');?>;
var data =<?php echo serialize($msg);?>;
</script>
Why do you call <?php $msg = searchResults('windows');?>; inside <script>...</script> and why is there a ; after