Héctor Rivera
Héctor Rivera

Reputation: 119

PHP calls inside jQuery?

found this rotative banner http://www.impressivewebs.com/mlb-switcher and I'm trying to make it work with my MySQL database using PHP, im fairly new to this stuff.

The banner has a data.js file connected to it which is here below, I'm trying to upload the first 6 news from my database, for example, the headlineText would display the title, but the only way I know isn't working (which is <?php echo $nw_Title; ?>), how can I use the <?php echo $nw_Title; ?> function and others like that inside this .js?

Thanks in advance! Here's the data.js file.

var currentItem = 1,

objMLB = {
    headlineText: [

        "Debuta José Figueroa en Clase-A Avanzada",
        "Cañizares impulsa a Guerreros sobre Diablos",
        "'El mejor momento de mi carrera'- Marwin González",
        "Peleando y arrebatando, Mochis saca el triunfo",
        "El incierto futuro de R.A. Dickey se podría definir",
        "Alex Ramírez llega a 2000 hits en la pelota Japonesa"
    ], // headlineText

    smallCaption: [
        "José Figueroa quedó segundo en porcentaje de bateo en la Dominican Summer League en 2012.",
        "David Reyes no permitió carrera y recetó siete chocolates en cinco entradas y un tercio.",
        "El venezolano Marwin González le rompió el juego perfecto a Yu Darvish en la novena entrada.",
        "Enterraron a los Venados con rally en la octava entrada para desempatar el juego.",
        "Los Mets de Nueva York negociarán con Dickey en Nashville.",
        "'Ramichan' se convirtió en el primer extranjero en lograr la hazaña de los 2000 imparables."
    ], // smallCaption

    descText: [
        "José Figueroa tuvo su primer aparición con los Tampa Yankees de Clase-A Avanzada donde bateó de 3-1 con un doble y una carrera anotada, el año pasado bateó .382 y produjo 39 carreras en 58 encuentros en la Dominican Summer League...",
        "Apoyados de una noche perfecta de Bárbaro Cañizares quien tuvo cuatro producciones, las cuales sirvieron para que los Yaquis de Ciudad Obregón a triunfo de 8 por 3 sobre los Tomateros.",
        "Con el pitcheo luciendo en todo lo alto, los Algodoneros de Guasave se hicieron de la doble cartelera  al vencer a los Mayos de Navojoa con marcadores de 3-2 y 2-1 respectivamente.",
        "Los Cañeros armaron su éxito con ataque en la parte alta de la octava entrada en el cual rompieron empate para asegurar el triunfo de 6 por 4 sobre los Venados de Mazatlán",
        "El pitcher nudillero y recientemente nombrado Cy Young de la Liga Nacional, R.A. Dickey, podría definir su futuro en su ciudad natal, Nashville, sede de las Juntas Invernales de Grandes Ligas.",
        "El venezolano Alex Ramírez logró su imparable número 2000 en la pelota japonesa de manera espectacular, conectando un cuadrangular en el triunfo de Yokohama contra Hiroshima..."
    ], // descText

    extURL: [
        "noticia_id1.php",
        "#2",
        "#3",
        "#4",
        "#5",
        "#6"
    ] // extURL

}; // objMLB ends here

Is it impossible to add querys like the one below inside .js?

<?php 
$sQuery = "Select * From tb_noticias Where nw_Status='activo' Order by nw_ID DESC LIMIT 0, 6";
$result = mysql_query($sQuery, $cnxMySQL) or die(mysql_error());
$rows_result = mysql_fetch_assoc($result);
$total_rows_result = mysql_num_rows($result);

if ($total_rows_result > 0){
    do {
        $id_noticias = $rows_result ['nw_ID'];
        $not_Titulo = $rows_result ['nw_Titulo'];
        $not_Resumen = $rows_result ['nw_Resumen'];
        $not_ImagenDesc = $rows_result ['nw_ImagenDesc'];
?>

smallCaption: [
    "<?php echo $nw_SmallCaption; ?>",
],

<?php
    }while($rows_result = mysql_fetch_assoc($result));
}else{
?>
<strong> "Error Fatal"</strong>

<?php  
}

mysql_free_result($result);

?>

Thanks in advance for the help, I hope you understand my question, sorry for my english...

EDIT --- I tried something like this

var currentItem = 1,

<?php 
$sQuery = "Select * From tb_noticias Where nw_Status='activo' Order by nw_ID DESC LIMIT 0, 6";
$result = mysql_query($sQuery, $cnxMySQL) or die(mysql_error());
$rows_result = mysql_fetch_assoc($result);
$total_rows_result = mysql_num_rows($result);

if ($total_rows_result > 0){
    do {
        $id_noticias = $rows_result ['nw_ID'];
        $not_Titulo = $rows_result ['nw_Titulo'];
        $not_Resumen = $rows_result ['nw_Resumen'];
        $not_ImagenDesc = $rows_result ['nw_ImagenDesc'];
?>


objMLB = {
    headlineText: [

        "<?php echo $not_Titulo; ?>",
    ], // headlineText

    smallCaption: [
        "<?php echo $not_ImagenDesc; ?>",
    ], // smallCaption

    descText: [
        "<?php echo $not_Resumen; ?>",
    ], // descText

    extURL: [
        "noticiasid.php?id=<?php echo $id_noticias; ?>",
    ] // extURL
<?php
    }while($rows_result = mysql_fetch_assoc($result));
}else{
?>
<strong> "Error Fatal"</strong>

<?php  
}

    mysql_free_result($result);

?>
};

</script>

But it won't work, thanks again, sorry for the long post, it's my first time here.

Upvotes: 0

Views: 276

Answers (2)

Shady Atef
Shady Atef

Reputation: 2401

I agree with Niloy and I will give you a little example of that

 $news = array();
 $sQuery = "Select * From tb_noticias Where nw_Status='activo' Order by nw_ID DESC LIMIT 0, 6";
                    $result = mysql_query($sQuery, $cnxMySQL) or die(mysql_error());
                    $rows_result = mysql_fetch_assoc($result);
                    $total_rows_result = mysql_num_rows($result);

                    if ($total_rows_result > 0){
                        do {
                                $new=array(
                                "id_noticias" => $rows_result ['nw_ID'];
                                "not_Titulo" => $rows_result ['nw_Titulo'];
                                "not_Resumen" => $rows_result ['nw_Resumen'];
                                "not_ImagenDesc" => $rows_result ['nw_ImagenDesc'];
                                );
$news[]=$new; // Adding the new to our news collection  } 
                            ?>

// After Looping we can encode them into JSON

<script type="text/javascript">
var newsObj = <?php json_encode($news); ?>    
</script>

Now you have JS obj that contain objects of individual news . You can add its data to the object you have like that

objMLB.headlineText.push(newsObj.new1.headline);

Upvotes: 1

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11290

Actually it is possible to have data.js generated by php script, but you will have to deal with some caveats:

  1. Web server (e.g. Apache) has to be configured with rewrite rule (for Apache you need mod_rewrite) to pass every request for data.js to a php script e.g. data_js.php
  2. As web browsers tend to cache js files aggressively, you have to provide mechanics to convince the browser that you really fetch different content. For some browsers it's fine to just send proper HTTP headers (no-cache, must-revalidate, expires with date from the past) but to make sure the browser will download your dynamic js every time, I use something like <script type="text/javascript" src="/data.js?dynamic=$some_random_value"></script>. You may ignore this dynamic parameter when generating your script, but the browser won't ignore it and will issue a new request - that's what we want.

However, I believe achieving your goals isn't worth of such work. @Shady's answer is enough for you.

Upvotes: 0

Related Questions