In Angular4, Array from .subscribe is empty in component.ts [duplicate] - php

This question already has answers here:
How to return object from service to component in angular
(3 answers)
Closed 3 years ago.
I am fetching data from PHP API, But the variable after subscribe is empty in component.ts but, while using in component.html it displays data. I want to modify after fetching from API.
In service.ts:
get_tournaments(){
return this.http.get("http://localhost/Website/api/tournament/read.php")
.map(res=>res.json());
}
In component.ts:
tournaments:Object[] = [];
ngOnInit() {
this.ongoing_ser.get_tournaments()
.subscribe(value=>this.tournaments=value);
console.log("Main:",this.tournaments); <-- this is empty
}
In component.html:
it displays everything correct as required.
I want to modify the data fetched from API and then display in html

#Sudhindra Purohit
Javascript is synchronous so it will to wait to complete subscribe your request. So that It will return empty in console.
If you want to modify your data then you can do like below
this.ongoing_ser.get_tournaments()
.subscribe(value=> { this.tournaments=value;
// DO here what ever you want with tournaments
this.tournaments = this.tournaments.map(tour => {
console.log(tour);
}
});

You need to assign the value to the component variable and then alter it or display it using interpolation {{}}
In the componenet.ts
ngOnInit() {
this.ongoing_ser.get_tournaments()
.subscribe(
(data:any)=>{
this.data=data;
//you can do the data modification here
})
}
In component.html
<div>{{data}}</div>
This will display the data in HTML

Related

Joomla ajax call function inside controller [duplicate]

This question already has answers here:
How to get data from one php page using ajax and pass it to another php page using ajax
(4 answers)
Pass object to PHP through AJAX
(3 answers)
How to print all information from an HTTP request to the screen, in PHP
(8 answers)
Closed 3 years ago.
I'm trying to call a function inside controller that will return a echo
but I get error as result show inside my id #ly-id-result
{"success":false,"message":"View not found [name, type, prefix]: places, raw, hpj_storemanagerView","messages":null,"data":null}
My Ajax call in : httpdocs/modules/mod_storemanager_map/tmpl/default.php
var ly_inputVal = document.getElementById("ly-val-inp").value;
jQuery.ajax({
url: "index.php?format=raw&option=com_storemanager&task=abc",
data: {text:ly_inputVal},
method: "POST", //Use post method
cache: false, //Specify no cache
success: function(result){
//console.log(ly_inputVal);
jQuery("#ly-id-result").html(result);
}
});
in my controller in : httpdocs/components/com_storemanager/controller.php
public function abc()
{
// Get Joomla's input object:
$input = JFactory::getApplication()->input;
// Get the variable
$value = $input->get('ly_inputVal');
return $value;
}
I found the error; I have to change
$value = $input->get('ly_inputVal');
to
$value = $input->get('text');
Now it working

Sending multiple data types in Angular post to php

I'm trying to work out how I can send two data types to my php file.
I have a big array which posts correctly and I can retrieve it correctly. I now want to be able to send a string with it and retrieve it separately in my php file. The reason for this is because dependent on the value of the string I will be sending a different array.
function send(result, selectedButton) {
console.log(selectedButton)
return $http.post(apiUrl + 'write_to_database.php', {'data': result}).then(function(data){
return $q.when(data);
});
}
so to retrieve the above in php I want something like this
$data = $_POST['data'];
$selectedButton = $_POST['selectedButton'];
Using the code above how can I send the selectedButton the php file so I can work out what array was sent?
Try this
function send(result, selectedButton) {
console.log(selectedButton)
return $http.post(apiUrl + 'write_to_database.php', {'data':result,'selectedButton': selectedButton}).then(function(data){
return $q.when(data);
});
}
Alternatively you can also pass it as query string parameter with the post url
return $http.post(apiUrl + 'write_to_database.php?selectedButton=' + selectedButton, {'data': result})

jQuery.inArray conditional returning false despite element existing within json array

What I'm attempting to do is invoke the loading of data from mysql into a php that's being called through jQuery then json_encode the array and send it via header('Content-type: application/json') to the jQuery function that's going to subsequently process the array as data for updating specific elements on the page.
I'm at the final lap here, having jQuery making the call, php accessing the database and sending the data back as a json array to the main page and getting most of the elements updated with their fresh data. Where I'm stuck is at analyzing a specific attribute of one element of the array: determining if a specified element exists in the array and, if so, disabling and hiding an input element.
What is being returned by the call is "btn1:true" ("true" being an arbitrary value) and no matter how I approach checking its existence, inArray gives me a -1, meaning that, even though it is making it through as an element of the array, my code is failing to find it.
Here is the code that makes the call and processes the incoming data:
<script type = "text/javascript">
$(document).ready(function () {
$('#refresh').click(function () {
$.get('includes/refresh.php', function (data) {
if (jQuery.inArray(btn1, data) > -1) {
$('#btn1').prop("disabled", true);
$('#btn1').hide();
}
});
});
});
</script>
Here's the JSFiddle, though without understanding exactly what format the array is in, getting positive results here doesn't help.
Here's the code that's called to pull data from mysql and send it back as a json array:
if (isset($_SESSION['id'])) {
$divs = array ();
$divs['item'] = $row['item'];
$divs['cost'] = "Ticket price: ".$row['cost'];
for ($i = 1; $i < 20; $i++) {
$divs['tname'.$i] = $row['t'.$i];
if ($row['t'.$i] != "") {
$divs['btn'.$i] = "true";
}
}
$divs['end'] = $row['end'];
$divs['winner'] = $row['winner'];
header('Content-type: application/json');
echo json_encode($divs);
die();
} else {
// nothing to refresh. clear the page and prompt user to start a new raffle.
}
... and here's the button that I totally want to make disappear:
<input id="btn1" class="submit" name="t1" type="submit" value="Buy!" />
So, to sum: the call is functioning, the data is being dragged from mysql and compiled into an a json-encoded array that's subsequently being passed to and being received by the calling script. My element check is failing to find what I know to be in the array. What am I overlooking?
Couple of things. Use getJSON instead of get because you're getting JSON.
$.getJSON('includes/refresh.php', function (data)...`
And, you're sending this data
$divs['btn'.$i] = "true";
// which gives $divs['btn1'] = "true";
but you're using btn1 as a variable not a string literal
if (jQuery.inArray(btn1, data) > -1) {
and it's a KEY not a variable in the array.
It should read
if (data.btn1) {
// or to be really specific:
// if (typeof data.btn1!='undefined' && data.btn1)
Also, while "true" IS truthy, so is "false", I think you mean $divs['btn'.$i] = true;
Also also (it's not part of the problem but...)
$('#btn1').prop("disabled", true);
$('#btn1').hide();
There's no need to keep selecting the element. Chain the commands.
$('#btn1').prop("disabled", true).hide();
Every time you select it, jQuery has to search for it. If you can't chain them, set a variable once. $btn=$('#btn1'); and use that $btn1.hide(); $btn1.show(); ....

PHP unserialize error when deserializing jQuery serialized form [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What to do with php after jquery .serialize()
I am serializing the following form using jQuery, sending it to the server using ajax and deserializing using PHP.
When I deserializing I get the error:
Error at offset 0 of 39 bytes
<form id="Marriage" style="display: none">
<input type="text" name="city" class="txtt" value="city"/>
<input type='button' value='Apply' id="msendsend" class="sendaf" name="jobforming"/>
</form>
Here is the jquery function to send this form
$(document).ready(function () {
$('#msendsend').click(function () {
var id=getParam('ID');
$.ajax({
type:'POST',
url:"send.php",
data:{option:'apply', sr:$("form").serialize()},
success:function (jd) {
}
});
});
});
This is the server code:
if($_REQUEST['option']=='catapply') {
$sc=$_POST['sr'];
mysql_query("insert into user_data(uid,data) values('$session->userid','$sc')");
}
And here I am unserializing .
$sql = mysql_query("SELECT * from user_data");
while ($row = mysql_fetch_array($sql)) {
$un = unserialize($row['data']);
$city=$un['city'];
echo $city;
}
The data in the database is shown as
to=&select_category=25&msg=&city=laho
jQuery's serialize function is way different from PHP's. It creates a query string, as you can see in your database.
This format may be decoded in PHP with the parse_str function. Use it instead of unserialize.
Instead of parsing it manually, though, you may be better off posting your form data as the query string:
data: $("form").serialize(),
You can add a hidden field to convey the option=apply value.
That way, you don't have to decode anything (it'll already be in $_POST) and you may insert every value in a separate row. It'll save you a lot of trouble in the future, e.g. when there's more data and you need to search through it.

Getting JSON data from Javascript

I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.

Categories