CODIGOS SELECT OPTION FETCH JAVASCRIPT API JSON PHP MYSQL GET POST

  

var formdata = {

      'fid' : id

    }


    datos = JSON.stringify(formdata);


    fetch("editar.php", {

        method: "POST",

        body: datos,

        headers: {

        'Content-type' : 'application/json',

        }

  




    }).then(response => response.json()).then(response => {

       

       /* idp.value = response.id;

        codigo.value = response.codigo;

        producto.value = response.producto;

        precio.value = response.precio;

        cantidad.value = response.cantidad;

        registrar.value = "Actualizar"

*/


console.log(response);

console.log(response.id);

console.log(response.nombre);

console.log(response.precio);


document.getElementById('edit-id').value = response.id;

document.getElementById('edit-fnombre').value = response.nombre;

document.getElementById('edit-lprecio').value = response.precio;




    })




<?php

header('Access-Control-Allow-Origin: *');

    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");

    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

    header("Allow: GET, POST, OPTIONS, PUT, DELETE");




$pdo = new PDO("mysql:host=localhost;dbname=tymalua", 'root', 'root');

$pdo->exec("set names utf8");



$input = file_get_contents('php://input');

$decode = json_decode($input, true);



$fnombre = $decode["fcaj"];





$statement=$pdo->prepare("SELECT * FROM ventaxdia WHERE nombre LIKE '%{$fnombre}%' ORDER BY id DESC;");


$statement->execute();


$results = $statement->fetchAll(PDO::FETCH_ASSOC);


if(!empty($results)){

     

   


        echo json_encode($results);



    }else{


     // echo 'error';


       $results='NOESTA';



        echo json_encode($results);



    }


?>








////////////////////////////////////

fetch('jsonpdoconpost.php', {

  method: "POST",

  body: dato,

  headers: {'Content-type' : 'application/json;charset=UTF-8',}

})

.then(respuesta => respuesta.json()) 

.then(tabla => {


      let filas = '';


        tabla.forEach(function(campo) {


           filas += ` 

              <tr>


                <td>${campo.id}</td>


                <td>${campo.nombre}</td>


                <td>${campo.precio}</td>


              </tr>


             `;

        });


document.getElementById("registros").innerHTML = filas;


});


}


<?php


header('Access-Control-Allow-Origin: *');

header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");

header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

header("Allow: GET, POST, OPTIONS, PUT, DELETE");

header('Content-Type: application/json');


$conexion=new PDO("mysql:dbname=tymalua;host=localhost","root","root");


$conexion->query("SET NAMES 'UTF8'");



$input = file_get_contents('php://input');

$decode = json_decode($input, true);



$cnombre = $decode["c_nombre"];



$consulta_sql=$conexion->prepare("SELECT * FROM ventaxdia WHERE nombre LIKE '%{$cnombre}%' ORDER BY id DESC;");







//$consulta_sql=$conexion->prepare("SELECT * FROM ventaxdia ORDER BY id DESC;");


$consulta_sql->execute();


if (!$consulta_sql){

    $resultado = 'Error al ejecutar la consulta';

}else{

    $resultado = $consulta_sql->fetchAll(PDO::FETCH_ASSOC);

  }


echo json_encode($resultado);


?>



/////////////////////////////////////////////////////

<select id='edit-class'></select>


function editRecord(id){

var editModal = document.getElementById("modal");

editModal.style.display = 'block';


fetch('php/fetch-edit.php?editId=' + id)

.then((response) => response.json())

.then((data)=>{

var option = '';

for(var i in data['response']){

document.getElementById('edit-id').value = data['response'][i].id;

document.getElementById('edit-fname').value = data['response'][i].first_name;

document.getElementById('edit-lname').value = data['response'][i].last_name;

document.getElementById('edit-city').value = data['response'][i].city;


var selected = '';

for(var j in data['class']){

if(data['class'][j].cid === data['response'][i].id){

selected = 'selected';

}else{

selected = '';

}

option += `<option ${selected} value="${data['class'][j].cid}">${data['class'][j].class_name}</option>`;

}


document.getElementById('edit-class').innerHTML = option;

}

})

.catch((error) => {

show_message('error',"Can't Fetch Data");

});

}



<?php


include 'config.php';


$sid = $_GET['editId'];


$sql = "SELECT * FROM students WHERE id = {$sid}";


$result = mysqli_query($conn, $sql) or die("SQL Failed");

$output = [];


if(mysqli_num_rows($result) > 0){

  while($row = mysqli_fetch_assoc($result)){

    $output['response'][] = $row;

  }

}


$sql1 = "SELECT * FROM class";


$result1 = mysqli_query($conn, $sql1) or die("SQL Failed");


if(mysqli_num_rows($result1) > 0){

  while($row1 = mysqli_fetch_assoc($result1)){

    $output['class'][] = $row1;

  }

}


mysqli_close($conn);


echo json_encode($output);


?>






////////////////////////////////////////////////////////


<select id="classlist"></select>



fetch('php/fetch-class-field.php')

.then((response) => response.json())

.then((data)=>{

var select = document.getElementById('classlist');

var option = '<option value="0" disabled selected>Select Class</option>';

for(var i=0; i < data.length; i++){

option += `<option value="${data[i].cid}">${data[i].class_name}</option>`;

}

select.innerHTML = option;

})

.catch((error) => {

show_message('error',"Can't Fetch Class List");

});






<?php


include 'config.php';


$sql = "SELECT * FROM class";


$result = mysqli_query($conn, $sql) or die("SQL Failed");

$output = [];


if(mysqli_num_rows($result) > 0){

  while($row = mysqli_fetch_assoc($result)){

    $output[] = $row;

  }

}else{

    return false;

}


mysqli_close($conn);


echo json_encode($output);


?>




///////////////////////////////////////////////////////////////////////////

<select name="nombreCategoria" id="nombreCategoria" class="input_form">

    <option value="-">Selecciona categoría padre</option>

  </select>



const select = document.querySelector("#nombreCategoria");

const url = 'https://jsonplaceholder.typicode.com/users';


fetch(url, {

    method: 'GET',

  })

  .then(res => res.json())

  .then(lista_de_categorias => {

    // console.log("Las categorías son:", lista_de_categorias);

    // alert('HAY ' + lista_de_categorias.length) Puedes poner este alert para ver si la llamada POST te devuelve algo


    for (let categoria of lista_de_categorias) {

      let nuevaOpcion = document.createElement("option");

      nuevaOpcion.value = categoria.id;

      nuevaOpcion.text = categoria.name;

      select.add(nuevaOpcion);

      // select.appendChild(nuevaOpcion); <-- Así tambien funciona

    }

  })

  .catch(function(error) {

    console.error("¡Error!", error);

  })



////////////////////////////



const states = document.getElementById('states');

states.innerHTML = '<option value="" disabled selected>Select State</option>';


fetch('https://jarednewnam.com/test/states.json')

  .then(res => res.json())

  .then(res => {

    console.log(res)

    if (res.status) {

      res.data.forEach(state => {

        const option = document.createElement('option');

        option.value = state.abbr;

        option.innerHTML = state.state;

        states.appendChild(option);

      });

    }

  });

<select name="states" id="states"></select>


////////////////////////////////////////////////


const states = document.getElementById('states');

states.innerHTML = '<option value="" disabled selected>Select State</option>';


fetch('https://jsonplaceholder.typicode.com/todos')

  .then(res => res.json())

  .then(res => {

    console.log(res)

   

      res.forEach(state => {

        const option = document.createElement('option');

        option.value = state.id;

        option.innerHTML = state.title;

        states.append(option)

      });


  });

<select name="states" id="states"></select>



///////////////////////////


const batchTrack = document.getElementById("batchSelect");

console.log({ batchTrack });

const getPost = async () => {

  const response = await fetch("https://jsonplaceholder.typicode.com/users");

  const data = await response.json();

  return data;

};


const displayOption = async () => {

  const options = await getPost();

  for (option of options) {

    const newOption = document.createElement("option");

    newOption.value = option.username;

    newOption.text = option.name;

    batchTrack.appendChild(newOption);

  }

};


displayOption();

<select id="batchSelect"></select>


/////////////////////////////////////////



<html>

<head>

<title>Dynamic Dependent Select Box using jQuery and Ajax</title>

</head>

<body>

<div>

<label>Country :</label><select name="country" class="country">

<option value="0">Select Country</option>

<?php

include('db.php');

$sql = mysqli_query($con,"SELECT * FROM country");

while($row=mysqli_fetch_array($sql))

{

echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';

} ?>

</select><br/><br/>

<label>City :</label><select name="city" class="city">

<option>Select City</option>

</select>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">

</script>

<script type="text/javascript">

$(document).ready(function()

{

$(".country").change(function()

{

var country_id=$(this).val();

var post_id = 'id='+ country_id;


$.ajax

({

type: "POST",

url: "ajax.php",

data: post_id,

cache: false,

success: function(cities)

{

$(".city").html(cities);

});


});

});

</script>

</body>

</html>


/////////////////////////////

<?php

//include "config.php";



$host = "localhost"; /* Host name */

$user = "root"; /* User */

$password = "root"; /* Password */

$dbname = "bdpersonas"; /* Database name */


$con = mysqli_connect($host, $user, $password,$dbname);

mysqli_set_charset($con,"utf8");

// Check connection

if (!$con) {

 die("Connection failed: " . mysqli_connect_error());

}


  $result = mysqli_query($con,"SELECT * FROM rubros");


  $response = array();


  while($row = mysqli_fetch_assoc($result)){


    $id = $row['id'];

    $nombre = $row['nombre'];


    $response[] = array("id"=>$id,"nombre"=>$nombre);

  }


  echo json_encode($response);


  exit;

//////////////////////////////////////////////////////////////////////


<?php

// Enter your Host, username, password, database below.

// I left password empty because i do not set password on localhost.

$con = mysqli_connect("localhost","root","","parent_child_select");

// Check connection

if (mysqli_connect_errno())

  {

  echo "Failed to connect to MySQL: " . mysqli_connect_error();

  }

?>

4. Create Index File Which Using JQuery and Ajax

Create a file with name index.php and copy paste the below code in this file. Note that I  have added the jQuery and Ajax script in the footer of this file.


<html>

<head>

<title>Dynamic Dependent Select Box using jQuery and Ajax</title>

</head>

<body>

<div>

<label>Country :</label><select name="country" class="country">

<option value="0">Select Country</option>

<?php

include('db.php');

$sql = mysqli_query($con,"SELECT * FROM country");

while($row=mysqli_fetch_array($sql))

{

echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';

} ?>

</select><br/><br/>

<label>City :</label><select name="city" class="city">

<option>Select City</option>

</select>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">

</script>

<script type="text/javascript">

$(document).ready(function()

{

$(".country").change(function()

{

var country_id=$(this).val();

var post_id = 'id='+ country_id;


$.ajax

({

type: "POST",

url: "ajax.php",

data: post_id,

cache: false,

success: function(cities)

{

$(".city").html(cities);

});


});

});

</script>

</body>

</html>

5. Create PHP Action File

Create a file with name ajax.php and paste the below script there.


<?php

include('db.php');

if($_POST['id']){

$id=$_POST['id'];

if($id==0){

echo "<option>Select City</option>";

}else{

$sql = mysqli_query($con,"SELECT * FROM `city` WHERE country_id='$id'");

while($row = mysqli_fetch_array($sql)){

echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';

}

}

}

?>


Comentarios

Entradas populares de este blog

Como proteger una api json con php al pasar el parametro POST[id] de los ataques sql injection y xss

Copia de Seguridad de Archivo MS Access (.mdb) a Pendrive con VB6

NUMEROS SERIE DE DISCO RIGIDO Y PENDRIVER USB CON PHP