简体   繁体   中英

How to update HTML content with javascript but get contents using PHP

So I have a php script called get_info.php In this file is a simple function called get_data() which takes the user submitted input and returns an array.

I have a HTML page called index.html . When the user hits submit, I would like the page not NOT refresh, but rather, it called the get_data() PHP function and updates the HTML.


My questions:

  1. I do not want other websites/people using my get_data() function to grab data. Whats the best way I can prevent other websites from using my get_data() function? For example, just echo-ing the array on get_info.php means other websites can just use file_get_contents on my script. I want people to use my index.html to get the data, not using my php script directly.

  2. Could someone show me how to update the HTML content by grabbing the info it gets from the get_data() function? As well as how I could show the user there was an error if their input is incorrect (for example, if the user entered a number, thats invalid, and should tell the user to enter letters only).


get_info.php

<?php

function get_data($input) {
    $arr['image'] = "https://example.com/$input";
    $arr['username'] = "$input" . rand(1, 50);
    return $arr;
}

function checkInput($input) {
    if (ctype_alpha($input))
        return true;

    return false;
}

if (isset($_POST['userInput'])) {

    $isValid = checkInput($_POST['userInput']);

    if ($isValid)
        $info = get_data($_POST['userInput']);
        // Now some how give this array to index.html
    else {
        // I throw an error, but how would I show
        // the user that the input they entered is
        // invalid?
    }
}

index.html

 // Not sure what to do here, but I want to set the myImage // and myUsername to what I get from the get_data() array. function updateMyPage() { document.getElementById("myImage").innerHTML = ""; document.getElementById("myUsername").innerHTML = ""; showMainCont() } // Shows the main container function showMainCont() { var x = document.getElementById("mainCont"); x.style.display = "block"; }
 .myMain { display:none; background: red; width: 300px; height: 100px; }
 User Input: <input type="text" name="userInput"><br> <button onclick="updateMyPage()">Submit</button> <div class="myMain" id="mainCont"> <div id="myImage"></div> <div id="myUsername"></div> </div>

You need Ajax for fetching data without refreshing the page.

Question 1 -

CORS is there to prevent other users/websites from using your script and all modern browsers have that support by default.

Question 2 -

You can just use a normal PHP script which echo you content and dump that content into the div you want using javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM