I have a script that calls dat from my table and returns it in JSON format. How do I echo out the var nps and data as php variable.
My script:
$.ajax({
type: "POST",
url: "../charts/1-2-4-reports_nps.php?TAG=<?php echo $_SESSION['SectionVar'];?>&From=<?php echo $_SESSION['StartDate'];?>&To=<?php echo $_SESSION['EndDate'];?>",
cache: false,
success: function(data){
var nps = data[0].name;
console.log(nps);
var data = data['data'];
console.log(data);
$("#div1").append($("<div/>", { id: "div2", text: nps }));
}
});
My Json returns:
[{"name":"nps","data":[35]}]
Something like $nps = data['nps'] and echo the result of $nps.
I think initially you were confused about the contexts your code is running in. var nps = data['nps']; is JavaScript. It runs in the browser, and it runs after the page is loaded.
$nps by contrast is a PHP variable, and PHP runs on the server, and it runs before the page is loaded. In fact it is the PHP which creates the HTML, CSS, Script etc which is then downloaded to the browser. After that is downloaded, the JavaScript executes separately.
There is no direct connection between the two languages, other than you can use PHP to generate JavaScript (just like you use it to generate HTML).
Once you understand that, then you realise that to display your nps variable further down the page, you need to use JavaScript to manipulate the web page and insert the data.
The first issue to resolve with that is that the data being returned from the server is coming back as a string that looks like JSON, but not an actual JSON object. You can add
dataType: "json"
to your ajax options, and that tells jQuery to treat the returned data as an object instead of a string.
The next problem is that data is an array, containing a single object, and you were trying to read it like it was just a plain object.
So you get data out of it, and, as you requested, display each value in a new div which gets inserted into an existing div, you can do the following :
function success(data)
{
var nps = data[0].name;
var dt = data[0].data[0];
$("#div1").append($("<div/>", { id: "div2", text: nps }));
$("#div3").append($("<div/>", { id: "div4", text: dt }));
}
You can see a working example (with simulation of the ajax call, but using the correct data structure) here: https://jsfiddle.net/yukot05x/5/
Related
I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing
i am a new php developers i was trying to create a simple system where i use php to extract database from mysql and use json in jquery mobile.
So here is the situation,
I've created a custom .php json (to extract data from mysql) on my website and i've successfully upload it onto my website eg: www.example.com/mysqljson.php
This is my code extracting mysql data `
header('content-type:application/json');
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('mydb');
$select = mysql_query('SELECT * FROM sample');
$rows=array();
while($row=mysql_fetch_array($select))
{
$rows[] = array('id'=>$row['id'], 'id'=>$row['id'], 'username'=>$row['username'], 'mobileno'=>$row['mobileno'], 'gangsa'=>$row['gangsa'], 'total'=>$row['total']);
}
echo json_encode($rows);`
Which in returns gives me the following json # http://i.imgur.com/d4HIxAA.png?1
Everything seems fine, but when i try to use the json url for extraction on jquery mobile it doesn't return any value.
i extract the json by using the following code;
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
jsonCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
},
error: function(e) {
console.log(e.message);
}
});
}
The json.id # #current_temp and json.id.username # #current_sum dint return any result on my jquery mobile page.
I suspected i didn't extracted the json url correctly, but im not sure, could anyone help me identify the problem?
Thank you.
jsonp expects a callback function to be defined in the json being retrieved - for ecample see here.
Your data print screen is actually plain old fashioned json, not jsonp.
So I see 2 options:
change the php data to render jsonp (this assumes you have control over data source).
change your jquery request to expect plain old fastioned json (this assumes client and server are on same domain, otherwise CORS error happen), e.g,,
$.get(forecastURL)
.then(function(json) {
console.log(json);
$("#current_temp").html(json.id);
$("#current_summ").html(json.id.username);
})
.fail(function(e) {
console.log(e.message);
});
First of all, you don't have to use jsonp to retrieve JSON. You could just do a simple Ajax Call. jQuery convert automatically your json string to a json object if your HTTP response contains the good Content-Type. And you did this good in your PHP call.
I think your problem comes from your json data analysis in your javascript success callback. The json generated is an array containing some user objects. In your code you don't work on one item of the array but you directly call .id or .username on the array. So javascript give you undefined values.
Here is an example displaying the data for the first item (index 0) of your json array. You have after that to choose for your own purpose how to treat your array objects but it's an example:
function loadWheather(){
var forecastURL = "http://example.com/mysqljson.php";
$.ajax({
url: forecastURL,
success: function(json) {
console.log(json);
// See, I use [0] to get the first item of the array.
$("#current_temp").html(json[0].id);
$("#current_summ").html(json[0].username);
},
error: function(e) {
console.log(e.message);
}
});
}
Basically I have two sliders on my page, whenever their value is adjusted they reference a script which returns a JSON array holding values about products which meet the new criteria.
In my success callback I want to call my PHP class which renders my view to the screen ( I am aware that I could probably achieve this effect in Javascript, but I already have a PHP class built which handles all of the required logic, so it would be simpler if there was a shortcut.
My AJAX method looks like this:
function update_results(values)
{
var json = JSON.stringify(values);
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?cache=" + (new Date().getTime()),
data: { query : json },
cache: false,
success: function(data) {
// Remove the old data from the document
$('tr').remove();
// Build the new table rows using the returned data array
$('table').append("<?php Table t = new Table(data); ?>");
}
});
}
Calling my Table constructor builds everything I need just by passing the JSON array I recieve back from my AJAX call, however nothing is being rendered to the screen at the moment - is there any way of doing this?
PHP runs on the server...JavaScript on the client... "<?php Table t = new Table(data); ?>"
does not magically work with the Ajax call. The server should be returning the table when you make the Ajax call.
I'm just a beginner and I want to show data from my database (MySQL) and display it in a line chart using JQPLOT. I have a PHP file that takes the data from the database and converts it into a JSON array which, as I understand, is what JQPLOT needs to display it properly.
The problem I'm having is that I've never used AJAX before.
The JQPLOT website gives me this code:
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:"json",
success: function(data) {
ret = data;
}
});
return ret;
};
// The url for our json data
var jsonurl = "./jsondata.txt";
var plot2 = $.jqplot('chart2', jsonurl,{
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I don't understand the second half of this code, but I want to know how I can incorporate my PHP file (that contains the json array) into this code and display a line chart. Or maybe if anyone has a simpler code where I can implement the PHP file and still able to show the line chart? Im just very new at this, please help.
The first part loads the data and the second part displays the data.
Now to explain further if you have downloaded jQPlot you will see there is one file called as jSonData.txt which contains an array, in the second part you use that array to display the chart.
You can do it differently, say in your PHP code you load the data from your database(MYSQL) and send it back as JSON, just pass this JSON retrieved to the jQPlot
the above code in that case will look like this:
var plot2 = $.jqplot('chart2', myJsonDataRetrievedFromDB,{
Could someone point me in the right direction here?
Basically, I've got this jQuery code snippet:
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
// Lagre til SQL
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: filename,
dataType: 'Text',
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
});
This is being run when I click a certain button. So it's actually within a click handler.
If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok.
But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data.
Does this seem correct so far?
Cause my php file looks like this:
<?php
require("dbconnect2.php");
$uploadstring = $_POST['filename'];
$sessionid = $_SESSION['id'];
echo ($sessionid);
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty.
Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here?
Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?
You're trying to send just the filename, but you're retrieving a named form field in your PHP code. So you need to send a named form field:
Change your ajax call like this:
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: {filename: filename}, // <= Change #1 (give jQuery a simple object)
dataType: 'text', // <= Change #2 ('text', not 'Text')
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
Your PHP script will now receive a POST varible called filename whose value comes from your filename Javascript variable. (You can also use $.post to do this, but it's just a wrapper for ajax anyway...)
Passing a simple object into the ajax call is the easiest way to send fields to the server. jQuery will take the object and create the URL-encoded form data (doing all of the escaping for you) by using the object's keys and field names. So for instance, if you give it this object:
data: {a: 1, b: "testing one two three", c: 3}
...it sends this URL-encoded data:
a=1&b=testing+one+two+three&c=3
(Note how it encodes it for us.) More in the ajax docs (but beware, at present what the docs say about array handling is wrong; see this bug report for details).