简体   繁体   中英

Doing an Ajax GET request to return data to PHP

I want to make an Ajax search request agains an API and get the data returned to my PHP file, right now I'm using Javascript and jQuery to do the job. But I want to let PHP do all the job, simply because I don't want my API key to be public and I may want to cash the data in a database further on. It seems that it should be simple, but I just can't figure out how to do it clean, call javascript and return or how to "integrate" it with PHP.

I am doing my PHP in the MVC pattern, like so:

Controller called from "mastercontroller/index":

class SearchController {

    public function DoControl($view, $model) {
        $ret = "";

        $ret .= $view->GetSearchForm();

        if($view->TriedToSearch()) {
            if($view->GetSearchString()) {
                $ret .= $model->CheckSearchString($view->GetSearchString());
            } else {
                // Didn't search for anything
            }
        } else {
            // Didn't press the search button
        }

        return $ret;
    }
}

My view is returning an HTML form, checking if submit is pressed and also returning the searchstring, that I am sending in to my Model above.

Model:

class SearchModel {

    public function CheckSearchString($searchString) {
        // 1. Call Googlebooks api with the searchstring
        // 2. Get JSON response to return to the controller
        // 3. The controller sends the data to the View for rendering
    }
}

I just can't figure out how I should do it.

I'm not entirely sure, but you seem to be asking how to perform an AJAX request without JavaScript. You can't do that -- it's not possible to use the XmlHttpRequest object without JavaScript. That's, according to legend, the origin of the "J" in the AJAX name.

It sounds like you need to use REST to call specific API's. RESTful state allows you to use web services to return specific data according to a predefined API. Data can be returned in XML or JSON.

You can do this very easily with PHP's cURL implementation using whatever keys Google gives you.

See Google's Google Books API Family page for links to PHP API and sample code.

Would the below practice be useful to you? If you just want to implement ajax functionality in your code.

Simple AJAX - PHP and Javascript

I am sorry for mistaking the content. How about the two below:

simple http request example in php
PHP HTTP-Request * from another stackoverflow question

But I think ajax is main in client program meaning. At the server-side, just call it http request.

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