jQuery page show the data got from json_encode in php - php

I want to show data in jQuery while the data got from php in json_encode function.
There are three file in all.
json.html
<html>
<head>
</head>
<body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
test.js
$(document).ready(function(){
$.getJSON("json.php",function(json){
alert(json.a);
console.log(json.a);
});
});
$(document).ready(function(){
function getA(){
$.getJSON("json.php",function(json){
echo json.$a;
})
}
}
json.php
<?php
header('Content-type:application/json');
$a=3;
echo json_encode($a);
?>
when I run the code,It shows as follows:
test.js:4SyntaxError: Unexpected identifier 'json'
Thanks to what you said, the former problem was solved.But something unbelieviable happens.
I have changed test.js as follows:
$(document).ready(function(){
$.getJSON("json.php",function(json){
document.write(json.a1.length);
document.write(json.a.length);
});
});
json.php
<?php
// header('Content-type:application/json');
$a = array('a1' =>aaaaa ,'b2'=>bb ,'c3'=>cc);
echo json_encode($a);
?>
This time,browser tells me 'a' is not an object ,but 'a1' is a object.Why did the elements not array passed to js?

if you want to get the output in your test.js then you should modify your code in json.php as follows
<?php
$data array('a' => 3);
echo json_encode($data);
json_encode($data) will output a {"a":3} which is a javascript object that which allow you to use your code in test.js
$.ajax({
method: "POST",
url: "json.php",
success: function(data) {
alert(json.a);// will alert 3
console.log(json.a);// will print 3
}
});

Replace echo json.$a; in test.js to alert(json.a);

echo is a PHP command and not JavaScript. See the example:
$(document).ready(function(){
$.getJSON("https://viacep.com.br/ws/89208540/json/",function(json){
console.log(json.localidade);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
</body>
</html>

In your json.php file use array to assign your value e.g,
<?php
$a=array('a'=>3);
echo json_encode($a);
?>

Related

jQuery Json response printing html tags

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.

How to pass php variables to jquery AJAX?

I have started learning jquery AJAX. I have run into a problem, and was wondering if you guys could help me. I am trying to pass a php variable back to jquery, but it displays as [object Object]. I will be posting my code below.
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function() {
$("p").text($.get("return.php"));
});
});
</script>
</head>
<body>
<p>This is a test!</p>
<button>Click Here</button>
</body>
</html>
return.php:
<?php
$message = "Another test!";
echo $message;
?>
So what is it that I need to do to pass php variable $message into the paragraph using jquery ajax?
I know I could simply do if I changed index.html to index.php, but then if $message later changes, I have to reload the page. I am trying to learn how to make dynamic content without having to reload the page.
Thanks ahead of time for any help you provide! :-)
You'll have to wait until the data is returned before you can use it:
$(document).ready(function(){
$("button").click(function() {
$.get("return.php", function(data) {
$("p").text(data);
});
});
});
Add a callback to get.
$.get("return.php", function(data) {
$("p").text(data);
});
You can use callback function in .get function.
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
});
});
});
Here you can pass the datatype as well in which form you want the response from server.
Suppose you want to return anyother datatype(i.e. json)from server, just use datatype with it like this :
$(document).ready(function(){
$("button").click(function() {
$.get("return.php",function(data){
$("p").text(data);
},"json");
});
});
For more detail,refer : http://api.jquery.com/jQuery.get/

jquery and strings from php code

I have a problem how to pass for example $example=1; variable to this jquery like a value in bracket where is 20, 40, 60.....:
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(20);
$("#pb2").progressBar(40);
$("#pb3").progressBar(60);
$("#pb4").progressBar(70);
$("#pb5").progressBar(100);
$("#pb6").progressBar(100);
});
</script>
The main problem is that I want to example string have value from database, so that's why I need to make it outside of script.
If this code is in your .php page...
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $pb1 ;?>);
$("#pb2").progressBar(<?php echo $pb2 ;?>);
$("#pb3").progressBar(<?php echo $pb3 ;?>);
$("#pb4").progressBar(<?php echo $pb4 ;?>);
$("#pb5").progressBar(<?php echo $pb5 ;?>);
$("#pb6").progressBar(<?php echo $pb6 ;?>);
});
</script>
Where $pb1,$pb2,$pb3,$pb4,$pb5,$pb6 are Integers ..
This is simple:
<?php
//Insert your code to generate the values to $example
$example = ...
?>
// and here is your JS with php code inside it
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $example; ?>);
$("#pb2").progressBar(<?php echo $example1; ?>);
$("#pb3").progressBar(<?php echo $example2; ?>);
$("#pb4").progressBar(<?php echo $example3; ?>);
$("#pb5").progressBar(<?php echo $example4; ?>);
$("#pb6").progressBar(<?php echo $example5; ?>);
});
</script>
I hope it helps! Good Luck!
If you meant to pass php variable to client to dynamically replace numbers in jquery you can use like code in below
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo example; ?>);
});
</script>
First off, having it in your database does not mean you cannot do so in the script. There are in fact several ways to do that. You could have your javascript file be php that generates javascript instead of html, or perhaps easier: you could use inline javscript. However, if you do want to keep the two separated it is still possible:
[..]
<script type='text/javascript'>var percentageDone = <?php echo intval($example) ?>;</script>
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(percentageDone);
});
</script>
[..]

How to merge php-mysql data with jquery to fade data

I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.

error missing ; before statement in jquery when sending serialized xml through jquery

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

Categories