I cant find answer to my problem...the truth is im new to jQuery and JSON.
On login page i want to display top customers and top tracks, when page loads.
Iv displyed them via echo from php, but i want to create JSON object and send it to login ...loop there and display it in unordered list.
Can you guys help me with creating JSON and displaying it in jquery.
Here's my code:
jQuery:
/* Function to load top Customers */
function loadCustomers() {
/* Create data string to call functions in php*/
var dataString ="function1=loadCustomers&function2=loadTracks";
$.ajax({
type:"GET",
url: "login.php",
data: dataString,
dataType: "json",
success: function(data) {
$("#error").show();
$("#errormsg").html(data.FirstName);
//how can i display Json data in unordered list ? #customerList
},
error: function() {
$("#error").show();
$("#errormsg").text("cant display data");
}
});
}
PHP :
}else if ($_SERVER["REQUEST_METHOD"] == "GET") {
//JSON customers array
$customers = array();
if ($_GET["function1"] == "loadCustomers") {
try {
$customerStmt = $conn->prepare("Select customer.FirstName, customer.LastName, customer.City, sum(invoice.Total) from invoice INNER JOIN customer on invoice.CustomerId = customer.CustomerId group by invoice.CustomerId order by sum(invoice.total) DESC LIMIT 5");
$customerStmt->execute();
$customerRows = $customerStmt->fetchAll();
//how to create JSON data to send it
header("Content-type: application/json");
echo json_encode($customerRows);
}catch (PDOException $e) {
$e->getMessage();
}
}
Well, from the code it looks like you are responding with multiple customers, but in jQuery you are accessing the data directly without accessing the array. So it should look like this
$.ajax({
type:"GET",
url: "login.php",
data: dataString,
dataType: "json",
success: function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#customerList" );
},
error: function() {
$("#error").show();
$("#errormsg").text("cant display data");
}
});
The problem was i couldn't recive JSON data from PHP.
After hours of googling and trying diffrent solutions i finally found an error..
When you read from database you have to set it to utf-8 charset.
I was fixing this problem in code with utf8_encode function...
You have to set it in new definition of PDO object :
$conn= new PDO("mysql:host=$server;dbname=$database;charset=utf8", $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
After this change im sending JSON data .
Related
So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.
So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.
I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }
I have a form my conditions are,
form.php, where I am inserting data using form,
display.php where I am showing data in table form using pagination and
validation.js where I am validating form data as well as I have following function
$('#pagiCount a').click(function(){
$.get($(this).attr('href'), function(response) {
console.log(response);
$( "#result" ).html(response);
});
return false;
//alert($(this).attr('href'));
});
Now I want to show that form from form.php on same display.php after pagination table.
How I can do that ?
New Suggeston :
Whenever you display the data in the ajax.php , just create a session array variable and update that value in the session array variable. So when ever you display the value in the ajax.php , get the data from the session array variable and display it.
Code : ajax.php
while($result=mysql_fetch_array($query)){
$_SESSION['compare_array'][]=$result;
}
echo "<table>";
foreach($_SESSION['compare_array'] as $key => $result)
{
echo '<tr><td>'.$result['brand'].'</td>'.'<td width="150" height="10">'.$result['model'].'</td>'; echo '<td>'.$result['clr'].'</td>'.'<td>'.$result['sim'].'</td>'.'<td>'.$result['os'].'</td>'.'</td></tr>';
}
echo "</table>";
OLD Suggestion :
You can use $.ajax with datatype : json. so you can return the data array in json encoded format so you can return both pagination result data and the form html data in array.
echo json_encode("pagination_response" => "put pagination html here", "form_data_response" => "put form html here ");
$('#pagiCount a').click(function(){
$.get($(this).attr('href'), function(response) {
console.log(response);
$( "#result" ).html(response);
});
return false;
//alert($(this).attr('href'));
});
$.ajax({
type: "POST", // post or get
url: 'your_url',
data: "data_href="+ $(this).attr('href'),
dataType: "json",
success: function(response)
{
if(result.status =="success")
{
$( "#result" ).html(response.pagination_response);
$( "#result_form_html" ).html(response.form_data_response);
}
});
I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.