0

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
DCJones
  • 3,121
  • 5
  • 31
  • 53
  • post the json data . try json_decode() . – Prafulla Kumar Sahu Jul 10 '17 at 08:20
  • do you mean the ones in the success? – Edwin Jul 10 '17 at 08:22
  • 2
    you can not do that this way, php is a server-side language while javascript is a client-side – hassan Jul 10 '17 at 08:22
  • @Edwin yes the ones in the success. – DCJones Jul 10 '17 at 08:23
  • if you need that value in PHP code, you can have hidden field and set value on success, and access it – Jigar Shah Jul 10 '17 at 08:23
  • @hassan already said it, you cannot do that. The only way I am thinking to be possible is to send another ajax call with the success, but I wonder why would you need to do that if the first was an ajax call... – Edwin Jul 10 '17 at 08:24
  • @Edwin in my browser console I can see the data I need but how do I use that as a php variable I canuse later on in the scripts? – DCJones Jul 10 '17 at 08:26
  • I assume you are aware that if this server is exposed on the internet it will be pwned easily. – symcbean Jul 10 '17 at 08:27
  • @symcbean yes. thanks for your reply. thats take care of. – DCJones Jul 10 '17 at 08:28
  • try to understand how this works, maybe start with this https://stackoverflow.com/a/23740549/1595977 – Edwin Jul 10 '17 at 08:28
  • in your example "nps" and "data" are coming _from_ the server. So I assume they are already variables available on the server in PHP during this ajax request, otherwise they could not be present in the `data` object which is what is returned by the server to the ajax call, when it completes. So it's unclear what you're asking. You have now got the variables in Javascript. Do you need to send the values (or updates values) back to the server at a later time? If so, you just need another ajax call to send them back again from the browser. – ADyson Jul 10 '17 at 11:26
  • @ADyson Hi and many thanks for your reply. I have var nps = data['nps']; which contains the data but later in the script, if I echo $nps, $nps does not contain data. I know I am doing this wrong, but how do I access the variables? – DCJones Jul 10 '17 at 19:02
  • You seem to have got very 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` is _PHP_ and it 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 connection_ between the two languages, other than you can use PHP to generate JavaScript (just like you use it to generate HTML). – ADyson Jul 10 '17 at 19:36
  • Therefore saying "later in the script" makes no sense because the code is not executing sequentially in the way you think it is. – ADyson Jul 10 '17 at 19:36
  • @ADyson Hi, I do understand what your saying so can I ask a question. How can I display the content of var nps? – DCJones Jul 10 '17 at 19:40
  • Where do you want to display it? inside some existing HTML element? Or a new one? – ADyson Jul 10 '17 at 20:21
  • @ADyson Hi, a new one if possible. Maybe inside a DIV using an id! – DCJones Jul 10 '17 at 20:24
  • what kind of element? Another div, a span, a textbox, what? – ADyson Jul 10 '17 at 20:25
  • @ADyson another div, which I can create – DCJones Jul 10 '17 at 20:26
  • ok so let's say in the page you have an existing div like this: `
    `. Inside your "success" function you can write `$("#div1").append($("
    ", new { id: "div2", text: nps }));`. This is a jQuery-syntax for doing it. It says "insert into div1 (without destroying what's already there) a new div with id as "div2" and text content as the value of the 'nps' variable".
    – ADyson Jul 10 '17 at 20:29
  • @ADyson hi, I am getting the following error: TypeError: ({id:"div2", text:(void 0)}) is not a constructor. My JSON is: [{"name":"Nps","data":[35]}] – DCJones Jul 10 '17 at 20:41
  • right so there's no such item as `data["nps"]` then? looks like it should be `var nps = data["name"];`. And sorry my code should be `$("#div1").append($("
    ", { id: "div2", text: nps }));` - sorry got a bit mixed up with C# syntax in there as well!
    – ADyson Jul 11 '17 at 07:01
  • Hi. again many thanks for all your time. I am not getting any errors but the div is not displaying any content. This is what I have: The Json result[{"name":"nps","data":[35]}] then is the script: success: function(data){ var nps = data['nps']; var data = data['data']; $("#div1").append($("
    ", { id: "div2", text: nps })); } div id="div1">
    – DCJones Jul 11 '17 at 07:23
  • just noticed that your JSON data is an array. So it will need to be `var nps = data[0].name;` Because name is a property of the first (and as it happens, only) object in the "result" array. – ADyson Jul 11 '17 at 15:24
  • @ADyson Hi, I appreciate all the time you have given trying to solve my issue but after trying it with "var nps = data[0].name;" it does not work. I have inserted a "console.log(nps)" into the script and it's empty which if I am right tells me that the data is not getting passed. Like yourself, I have spent so much time trying to get this to work I don't know where to look next. As a last shot at it, do you have any other ideas? Again, I have checked that the JSON contains the data and it does. – DCJones Jul 11 '17 at 16:00
  • @ADyson The script now looks like: success: function(data){ var nps = data[0].name; console.log(nps); var data = data['data']; console.log(data); $("#div1").append($("
    ", { id: "div2", text: nps })); }
    – DCJones Jul 11 '17 at 16:00
  • @ADyson I have edited the original code to how it is now. See above. – DCJones Jul 11 '17 at 16:03
  • and it works, or not? – ADyson Jul 11 '17 at 16:04
  • @ADyson No, I am sorry it does not. – DCJones Jul 11 '17 at 16:04
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/148918/discussion-between-dcjones-and-adyson). – DCJones Jul 11 '17 at 16:05
  • In principle it should work, based just on that snippet. Here's a simulation (replacing the ajax call, which I can't reproduce, with a dummy call to a function). Press the "Run" button to watch it in action: https://jsfiddle.net/yukot05x/2/ – ADyson Jul 11 '17 at 16:08
  • I wonder if you should add the `dataType:"json"` option to your ajax call. Otherwise It might thing `data` is just a string when it comes back, and you may not be able to access the properties. You should have had a console error if that was the case. – ADyson Jul 11 '17 at 16:11
  • @ADyson Well that works by adding dataType:"json". The last part is just display "var data = data['data'];" in anoth div and its complete. – DCJones Jul 11 '17 at 16:15
  • rinse and repeat. https://jsfiddle.net/yukot05x/5/ P.S. You should have had console errors or at least output telling you that your variables were "undefined". Would have been useful to know that, I'd have spotted the dataType thing earlier. Basically that tells jQuery to treat the response as JSON (and therefore make it into a JS object immediately) and not just leave it as a string, which it is by default. – ADyson Jul 11 '17 at 16:19
  • @ADyson What I star. All working. I don't know how to thank you enough. You need to post your solution as an answer so I can accept it. – DCJones Jul 11 '17 at 16:23
  • @DCJones done - thankyou. Hopefully you've learned a lot about dealing with JS and AJAX. – ADyson Jul 11 '17 at 20:42
  • 1
    @ADyson again, many thanks for all your time. I have ordered two books relating to javascript and Jquery. I will and do learn. – DCJones Jul 11 '17 at 20:47

1 Answers1

1

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/

ADyson
  • 57,178
  • 14
  • 51
  • 63