Jump to content

could a ajax submit call directly to a php script ?


adrianmak
 Share

Recommended Posts

i'm going to create a live content search.

Typing in a text field will return search result   on the fly.

for testing purpose, I search on another database

query,php

<?php
/************************************************
	The Search PHP File
************************************************/

/************************************************
	MySQL Connect
************************************************/

// Credentials
$dbhost = "127.0.0.1";
$dbname = "ajaxsearch";
$dbuser = "root";
$dbpass = "root";

//	Connection
global $tutorial_db;

$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");

//	Check Connection
if ($tutorial_db->connect_errno) {
    printf("Connect failed: %s\n", $tutorial_db->connect_error);
    exit();
}

/************************************************
	Search Functionality
************************************************/

// Define Output HTML Formating
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';

// Get Search
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);

// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
	// Build Query
	$query = 'SELECT * FROM search WHERE function LIKE "%'.$search_string.'%" OR name LIKE "%'.$search_string.'%"';

	// Do Search
	$result = $tutorial_db->query($query);
	while($results = $result->fetch_array()) {
		$result_array[] = $results;
	}

	// Check If We Have Results
	if (isset($result_array)) {
		foreach ($result_array as $result) {

			// Format Output Strings And Hightlight Matches
			$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['function']);
			$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['name']);
			$display_url = 'http://php.net/manual-lookup.php?pattern='.urlencode($result['function']).'〈=en';

			// Insert Name
			$output = str_replace('nameString', $display_name, $html);

			// Insert Function
			$output = str_replace('functionString', $display_function, $output);

			// Insert URL
			$output = str_replace('urlString', $display_url, $output);

			// Output
			echo($output);
		}
	}else{

		// Format No Results Output
		$output = str_replace('urlString', 'javascript:void(0);', $html);
		$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
		$output = str_replace('functionString', 'Sorry :(', $output);

		// Output
		echo($output);
	}
}

?>

custom.js

/* JS File */

// Start Ready
$(document).ready(function() {  

    // Icon Click Focus
    $('div.icon').click(function(){
        $('input#search').focus();
    });

    // Live Search
    // On Search Submit and Get Results
    function search() {
        var query_value = $('input#search').val();
        $('b#search-string').text(query_value);
        if(query_value !== ''){
            $.ajax({
                type: "POST",
                url: "query.php",
                data: { query: query_value },
                cache: false,
                success: function(html){
                    $("ul#results").html(html);
                }
            });
        }return false;    
    }

    //$("input#search").live("keyup", function(e) {
    $("input#search").on("keyup", function(e) {
        // Set Timeout
        clearTimeout($.data(this, 'timer'));

        // Set Search String
        var search_string = $(this).val();

        // Do Search
        if (search_string == '') {
            $("ul#results").fadeOut();
            $('h4#results-text').fadeOut();
        }else{
            $("ul#results").fadeIn();
            $('h4#results-text').fadeIn();
            $(this).data('timer', setTimeout(search, 100));
        };
    });

});

While I step thru the js, it seems the query.php is not executed (or not found ?).

As I input a random text, it should display "No Results Found." on the page.

Link to comment
Share on other sites

Have you created a template in PW (with just a title field) and assigned query.php to it? If not, you'll need to do that and add the following to the top of query.php if you only want it to be called via ajax...

if (!$config->ajax) {
    return;
}

There might be something else missing from your example - but I'm in a rush and those are the most obvious things.

HTH

Link to comment
Share on other sites

Just a guess, but what about the path to your query.php. You say it's in your website root, but if it's being called from a PW page, then you need to use a root relative path, likely just: 

url: "/query.php",

Don't forget that you can find out if there was a 404 on that file in the Network tab of your dev tools console.

  • Like 4
Link to comment
Share on other sites

Just a guess, but what about the path to your query.php. You say it's in your website root, but if it's being called from a PW page, then you need to use a root relative path, likely just: 

url: "/query.php",

Don't forget that you can find out if there was a 404 on that file in the Network tab of your dev tools console.

You are correct.

Edited by kongondo
Marked Adrian's answer as the correct one :-)
Link to comment
Share on other sites

  • 2 weeks later...

THe only i can think of Ajax working in a sane manner is to have a page handle Ajax codes and from that page dispatch external Class function depending on the Ajax request. seriously can't wait for PW to have a View like, my project is littered with templates

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...