I need some help setting up DB marker retrieval. I got a bit confused on what exactly to pass back. Here is what I have so far:
data returned:
["Chatswood NSW AU","Chippendale NSW AU"]
JS:
var opdata = [];
function markers() {
$.post("id.php", {id: <?php echo $id; ?>})
.done(function(data) {
//data is array returned
opdata = data; //Tried this
$(opdata) = data; //Tried this
opdata.push(data); //Tried this
$.each(data, function(i) { //Tried this
opdata.push(data[i]);
});
});
console.log(opdata); //Shows [] empty array regardless what i do
}
PHP:
$arr = array();
while ( $selectData -> fetch() ) {
$arr[] = $address;
}
echo json_encode($arr);
How do I go about retrieving data? None of the above is working.
This is driving me nuts.. should i just $.ajax instead?
The call to .done is asynchronous, meaning that .done finishes right away, BEFORE the ajax call is made, and console.log is called right after, even if the http call is not finished yet.
Based on your use case and context you can choose between 3 options to return opdata back to the caller function:
///// OPTION 1: synchronous call
function markersUsingSynchronousCallToAjax() {
var opdata = [];
$.ajax({
type: "POST",
url: "id.php",
async: false, // disable asynchronous call to ajax
data: {id: <?php echo $id; ?>},
success: function(data) {
opdata = data;
}
})
return opdata;
}
var opdata = markersUsingSynchronousCallToAjax();
console.log("using a synchronous ajax call", opdata);
///// OPTION 2: callback
function markersUsingCallback(callback) {
$.post("id.php", {id: <?php echo $id; ?>})
.done(function(data) {
callback(data);
});
}
markersUsingCallback(function(opdata){
console.log("using a callback", opdata);
});
///// OPTION 3: promise
function markersUsingPromise(callback) {
return $.post("id.php", {id: <?php echo $id; ?>});
}
markersUsingPromise().done(function(opdata){
console.log("using a promise", opdata);
});
Related
I have this javascript function with ajax calling a .php calling a function inside a class .php, but the console.log is undefined
function SpinTimeTotal(){
$.ajax({
type:"POST",
url: "app/get_SpinTimeTotal.php",
success: function($a){
return $a;
}
});
}
spinTimeTotal = SpinTimeTotal();
console.log(spinTimeTotal); //undefined
calling this php code
<?php
include_once "read_spindata.php";
$a = read_data_spin :: read_Timespin();
?>
calling this function
<?php
class read_data_spin{
public static function read_Timespin(){
try{
$conexion = new PDO("mysql:host=localhost; dbname=dbname", "user", "pass");
} catch (PDOException $ex) {
echo "Conexion fallida". $ex -> getMessage();
die();
}
$spinTimeTotal = $conexion -> query("SELECT spinTimeTotal FROM data_ruleta ORDER BY id DESC limit 1");
return $spinTimeTotal;
}
}
SpinTimeTotal() is an asynchronous function and this statement won't wait until executed.
spinTimeTotal = SpinTimeTotal();
You should instead use deferred objects or promises.
function SpinTimeTotal()
{
var deferred = jQuery.Deferred();
$.ajax(
{
type: "POST",
url: "app/get_SpinTimeTotal.php",
success: function($a)
{
return deferred.resolve($a);
}
});
return deferred.promise();
}
Your actual function call would then be:
$.when(SpinTimeTotal()).then(function(data)
{
console.log(data);
});
You need to echo the result in your php script like
<?php
include_once "read_spindata.php";
$a = read_data_spin :: read_Timespin();
echo $a;
?>
In most cases there will be more to return than just single value. Then JSON is the preferred format:
echo json_encode($resultObject);
And, of course, you need to change your Ajax call too, like:
function SpinTimeTotal(){
$.ajax({
type:"POST",
url: "app/get_SpinTimeTotal.php",
success: function($a){
console.log($a);
}
});
}
Th console.log in your global scope will have been fired before the Ajax success function had done its job. And even then, the returned value cannot be picked up from the global scope.
The only way to "return" a result value from an AJAX function would be into an async function, see here for a working example: What is different between Fetch and jQuery Ajax post?
try $a without $ , just a
function SpinTimeTotal(){
$.ajax({
type:"POST",
url: "app/get_SpinTimeTotal.php",
success: function(a){
return a;
}
});
}
I have this php
include_once($preUrl . "openDatabase.php");
$sql = 'SELECT * FROM dish';
$query = mysqli_query($con,$sql);
$nRows = mysqli_num_rows($query);
if($nRows > 0){
$dishes = array();
while($row = $query->fetch_assoc()) {
$dishes[] = $row;
}
}else{
$dishes = "cyke";
}
echo json_encode($dishes , JSON_FORCE_OBJECT);
and this ajax (in framework7)
myApp.onPageInit('dailyMenu',function() {
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.log(data);
});
});
What i get in the ajax data is
{"0":{"idC":"2","title":"helloWorld1","subtitle":"hellsubWorld","price":"16.5","img":"img/testeImg.jpg","soldout":"0"},"1":{"idC":"3","title":"helloworld2","subtitle":"hellosubWorld2","price":"20.5","img":"img/testeImg.jpg","soldout":"1"}}
I already tried data.[0]; data.['0']; data.0; data0 when i use data["0"] just gives me the '{'.
I want to acess the title and the rest inside that 0. to do a cicle for where i will print multiple divs where i only change the array position in a html page.
Exemple
for(...){
innerhtml += <div clas="">
<div class""> data(position i).title </div>
<div> data(position i) subtitle</div>
</div>
}
try this one (after callback add type: json)
$$.post('url', {}, function (data) {
var obj = JSON.parse(data);
console.log(obj);
alert(obj["1"].title);
});
or maybe you can use JSON.parse(data);
Since you are receiving a json data as response, you should use this:
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.dir(data);
},'json');
Pay attention to },'json');on end of the code, now the $$.post is reading the response as a JSON.
If you aren't doing any update to data base, you could use:
$$.getJSON('http://theIP/eatsServer/dailyMenu.php',{}, function (data) {
console.dir(data);
});
This is the way with $$.ajax:
$$.ajax({
url: "url_here",
method: "POST",
dataType:"json",
data: {},
success: function(r){
// response r.
}, error: function(error){
//error
}
});
I have a button Next that changes the page -
<a class="disabled" href="step">
<button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>
Also, when this button is clicked, I have an Ajax function that sends data to a controller function -
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: a,
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
And I'm using this to receive the value from Ajax -
public function CreateData() {
$data = $this->input->post('data');
return $data;
}
When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -
public function step()
{
$data = $this->CreateData();
if(!empty($data)){
print_r($data); exit;
}
else {
echo "blank"; exit;
}
$this->load->view('step2');
}
However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?
Your javascript should be something like this
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: {my_data: a},
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
Notice the data property. I have changed it to an object containing the variable a.
Now you should be able to retrieve this in your php function using
public function CreateData() {
$data = $this->input->post('my_data');
return $data;
}
Adr's answer solved part of the problem. In order to actually store and access the data, storing it in the session instead of a variable did the trick -
public function CreateData() {
$data = $this->input->post();
$this->session->unset_userdata('createData');
$this->session->set_userdata('createData', $data);
}
This prevented the $data variable from being overwritten when called the second time.
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 I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;
Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}