0

Hello i want to return data using jquery like this

function countries()
{
    var html='';
    var j='';
var encodedata=JSON.stringify({});
    var url=apiBaseUrl+'api/countries'; 
    ajaxPost(url,encodedata, function(data) {
        if(data.countries.length)
        {
            $.each(data.countries, function(i,data)
            {
                html= '<div class="panel panel-default">'+
'<div class="panel-heading">'+'<a href="'+data.country_id+'" class="feed-author" target="_blank">'+data.name+'</a>'+'</div>'+'</div>';
            });
        }
    });
}
and this is php

function countries() {
try {
       $db = getDB();
        $sql = "SELECT * FROM countries";
        $stmt = $db->query($sql);
        $data = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        return $data[0];
}
catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

   first i dont know what to put in this line
`**var encodedata=JSON.stringify({});**`
and secondly how to i return the html in this div
<div id="allcountries">

Edited by SimonIoa: edit

2
Contributors
12
Replies
57
Views
1 Year
Discussion Span
Last Post by diafol
Featured Replies
  • 1
    diafol 3,720   1 Year Ago

    jQuery: 1. `encodedata` is set to stringify an empty object for some reason - why? 2. Are we to assume that `apiBaseUrl` is a global variable and has a trailing slash in order to allow concatenation of further url fragments? 3. `j` is set to empty string. Why? You don't … Read More

  • 1
    diafol 3,720   1 Year Ago

    Sorry didn't see the following as it was included in the code snippet: > first i dont know what to put in this line `**var encodedata=JSON.stringify({});**` and secondly how to i return the html in this div <div id="allcountries"> You don't need the `encodedata` unless you wish to populate it … Read More

1

jQuery:

  1. encodedata is set to stringify an empty object for some reason - why?
  2. Are we to assume that apiBaseUrl is a global variable and has a trailing slash in order to allow concatenation of further url fragments?
  3. j is set to empty string. Why? You don't use it. You certainly don't use it elsewhere as it is scoped to the function.
  4. You set html to empty string - ok, but then you overwrite it on each iteration of the each loop.
  5. The ajaxPost function is a custom function? I'm assuming that this extends the jQuery $.ajax or $.post functions?
  6. ajaxPost(url,encodedata, function(data) - why is encodedata sent as an empty string?
  7. Choosing a variable name the same as an existing "in use" one can be confusing: $.each(data.countries, function(i,data) - simply no need for this, how about: $.each(data.countries, function(i,v) and use v.country_id and v.name
  8. Concatenation of html var - use += instead of =.
  9. There is no return statement nor are there any assignments to global variables or html elements. So what is this function actually supposed to do?

Sorry was going to tackle the PHP, but ran out of patience. Your JS is held together with sticky tape. Take time to go through it carefully and methodically. You're not a novice - you've been posting about JS for 2 years, so you should be able to sort most of this out for yourself.

1

Sorry didn't see the following as it was included in the code snippet:

first i dont know what to put in this line
**var encodedata=JSON.stringify({});**
and secondly how to i return the html in this div
<div id="allcountries">

You don't need the encodedata unless you wish to populate it from data held in some form control(s).
html can be placed in the specified div like this:

$('#allcountries').html(html);

Or you can make the function return html as a string and place the returned value into the div (using another function).

0

to my excuse i dont really know much javascript especially Jquery. I am more to php. I am an amateur programmer. i make my living from another line of work so between that job and a family to raise (the most difficult thing is in Greece these days) i do programming whenever i have the time. But you are right i should had this for lunch. Anyway enough with the cry baby.

  1. i dont use any parameters from my PHP script (api/countries) to fill in some. I thought even if i left it empty it will still work.
  2. apiBaseUrl is not a global variable but a variable i defined earlier in the script. So that works ok.
  3. J is completely wrong, you are right. Its called nowhere.
  4. well, i dont want the country_id and name to be in a loop. I just want to make a list of countries (i know there are easier ways, i ve done them in other projects, thats not the issue) . What do you mean in a loop? This i dont understand
  5. yes, ajaxpost its a custom function
    6.This is the problem i think. What should a parameter be like? I could filter for all countries to start from a
    $sql = "SELECT * FROM countries WHERE name LIKE '%" . $_REQUES["filter'] . "'";
    and therefore
    JSON.stringify({"filter": 'a'});
    but i dont want that. So i thought an empty would return everything
    7.ok i did it
  6. ok did that too
  7. i want the function to return a list of countries in a <a href in a selected div.
    so this is what i did so far.

    function countries()
    {
    var html='';
    var encodedata=JSON.stringify({});
    var url=apiBaseUrl+'api/countries';
    ajaxPost(url,encodedata, function(data) {
    if(data.countries.length)
    {
    $.each(data.countries, function(i,v)
    {
    html+= '<div class="panel panel-default">'+
    '<div class="panel-heading">'+'<a href="'+v.country_id+'" class="feed-author" target="_blank">'+v.name+'</a>'+'</div>'+'</div>';
    });
    $('#countries').html(html);
    }
    });
    }

php

function countries() {
    try {
           $db = getDB();
            $sql = "SELECT * FROM countries";
            $stmt = $db->query($sql);
            $data = $stmt->fetchAll(PDO::FETCH_OBJ);
            $db = null;
            return $data[0];
    }

and the div, i know it needs a <ul><li> syntax but i ll do it later.

<div id="countries">Countries</div>

Edited by SimonIoa

0

P.S. i dont think that the html needs a +=
and i know that the <ul><li> should go to the html variable on the javascript script

0

I think I'd approach it in a JSON manner:

var apiBaseUrl = 'blah/';

/*
    event handler e.g.
    $('#filter').change(function(){
       var flt = $(this).val();
       byCountry(flt);
    });
 */

function byCountry( countryFilter )
{
    var html;
    var encodeData = {filter: countryFilter};
    var url = apiBaseUrl + 'api/countries';

    $.getJSON( url, encodeData ).done( function( data )
    {
        if( data.countries.length )
        {
            $.each( data.countries, function( i, v )
            {
                html += '<div class="panel panel-default"><div class="panel-heading">'+
                    '<a href="'+v.country_id+'" class="feed-author" target="_blank">'+v.nam+'</a>' +
                    '</div></div>';
            });
            $('#allcountries').html( html );
        }
    });
}

Notice the name change from .name to .namI've run into issues with this before where a keyword like name can bugger you up. This is just in case. Not sure if it would happen here though.

The PHP on the other hand can be used thus - BUT you MUST sanitize your input OR use a prepared statement. You are wide open to SQL injections with your current SQL (filterable).

$exParam = null;
$sql = "SELECT *, `name` AS nam FROM `countries`";
if(isset($_GET['filter']) && trim($_GET['filter']) {
    $exParam = ['%' . $_GET['filter']];
    $sql .= " WHERE `name` LIKE ?";
}
$sql .= " ORDER BY `name`";
$stmt = $pdo->prepare( $sql );
$stmt->execute( $exParam );
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode( $data );

N.B. None of this is tested - just off my noggin.

Edited by diafol

0

i did it still i get nothing no list of countries i ll check the php if it returns the list

Edited by SimonIoa

0

well some other function that i use with success elsewhere (categories) and it doesn't return anything back. I ckeched the $('#allcountries').html( 'ddddd' ); and it returns ddddd on the selected div when i use it outside the function but nothing when i put it inside the function

0

Sounds like your php isn.t returning records. Do a console.log or an alert to see if anything is returned.

Edited by diafol

0

Can you post an example, i mean how do i check if the php script returns

0
echo json_encode( $data );

Will send the data to the js script.

$.getJSON( url, encodeData ).done( function( data )
{
    alert(JSON.stringify(data)); // insert this to show returned php data
    // OR
    // console.log(JSON.stringify(data)); 
    // to display the data in the console
    if( data.countries.length )
    {
        $.each( data.countries, function( i, v )
        {
            html += '<div class="panel panel-default"><div class="panel-heading">'+
                '<a href="'+v.country_id+'" class="feed-author" target="_blank">'+v.nam+'</a>' +
                '</div></div>';
        });
        $('#allcountries').html( html );
    }
});
0

i am getting nothing as an alert or any data returned in the console. That it doesnt return anything right?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.