Jump to content

A simple post and recall AJAX query.


greenace92

Recommended Posts

First if I affected anyone negatively in my previous posts, I apologize, I sometimes have problems.

 

I do not use a framework, I haven't/rarely use AJAX.

 

I have "designed" this basic interface that I was using for a while, it's a simple entry and keyphrase storage / recall application that I use to take notes while I research various subjects online. The inteface looks like the photo below, which may not be relevant. 

 

post-164367-0-34170000-1436027540_thumb.jpg

 

It is pretty simple as you can see, I was able to use it using POST but the problem is that I don't want the page to refresh everytime. I have used AJAX briefly for a project involving a widget-position-auto-update where a widget's coordinates when changed would be automatically updated on a database that kept track of the widget(s) position.

 

The general code looks like this:

$.post( "update_coordinate.php", {
'id':$id,
    'name':$name,
    'wname':$wname,
    'xcor':$xcor,
    'ycor':$ycor,
    'xwid':$xwid,
    'yhei':$yhei,
    'photo':$photo,
    'targeturl':$targeturl
    }).done(function( data ) {
    //alert( "Server Response: " + data );
    });
}

So what I'm after here is to submit the written content and then retrieve without refreshing the page. I have tried to do this without success. For the display, I am after that search-hint layout where I start typing and suggestions come up, hence no submit button on the search/display interface.

 

I have been reading on this and tried to use the link below which I'm not sure if that is overkill / not what I'm after.

 

http://www.tonymarston.net/php-mysql/dom.html

 

I have been told not to follow/use W3Schools, I was looking at their AJAX search suggestion/hint entry and it makes sense using the onkeyup to trigger the function, I followed the link to their php code which was not formated eg. indexed , it was compressed and thus hard to follow.

 

Anyway I'd appreciate any input, at this time I am going back to the old post method as I need to start using this again, unfortunately I lost 5 months of work (arrghhh) hence I'm investing into an almost life long server, although on second thought, I think onedrive gives you free storage but I'm not sure about their TOS as in "Whatever you upload legally belongs to us" or whatever.

 

So there are two databases:

 

Key with columns id,key,count

Entry with columns, id,user,key,entry,date

 

Firs problem is a simple post of textarea, keyphrase, along with the id, user and date.

 

Second problem is the recall part, display is no problem, encase it in a CSS to make it pretty/jquery for dropdown functionality. But pulling the data back, the link above was using associated array.

 

I can't tell if the AJAX is going through.

 

Thanks for any help and happy 4th of July. I am thankful to live in this country.

Link to comment
Share on other sites

I'm not 100% sure what you're asking for here, but it sounds like you want a text field to show search results as you type using AJAX. If so, you just need an onkeyup event to trigger when typing in the text field. In the event handler, you'd perform an AJAX call to your server-side script, get the results, and then do whatever logic to add them to the search results.

 

Here's a quick JSFiddle to illustrate.

 

http://jsfiddle.net/2zrd10av/

Link to comment
Share on other sites

For making simple "POST" in ajax and get the response ,i am describing here a good example as tested:

 

Step-1:

Make a html form for the same which you have to sent with using ajax for server:

 

<form id="foo">

    <label for="bar">A bar</label>

    <input id="bar" name="bar" type="text" value="" />

 

    <input type="submit" value="Send" />

</form>

 

Step-2:

 

Here i am using a function which is related to your requirement:

 

<script type="text/javascript">

// Variable to hold request

var request;

 

// Bind to the submit event of our form

$("#foo").submit(function(event){

 

    // Abort any pending request

    if (request) {

        request.abort();

    }

    // setup some local variables

    var $form = $(this);

 

    // Let's select and cache all the fields

    var $inputs = $form.find("input, select, button, textarea");

 

    // Serialize the data in the form

    var serializedData = $form.serialize();

 

    // Let's disable the inputs for the duration of the Ajax request.

    // Note: we disable elements AFTER the form data has been serialized.

    // Disabled form elements will not be serialized.

    $inputs.prop("disabled", true);

 

    // Fire off the request to /form.php

    request = $.ajax({

        url: "/form.php",

        type: "post",

        data: serializedData

    });

 

    // Callback handler that will be called on success

    request.done(function (response, textStatus, jqXHR){

        // Log a message to the console

        console.log("Hooray, it worked!");

    });

 

    // Callback handler that will be called on failure

    request.fail(function (jqXHR, textStatus, errorThrown){

        // Log the error to the console

        console.error(

            "The following error occurred: "+

            textStatus, errorThrown

        );

    });

 

    // Callback handler that will be called regardless

    // if the request failed or succeeded

    request.always(function () {

        // Reenable the inputs

        $inputs.prop("disabled", false);

    });

 

    // Prevent default posting of form

    event.preventDefault();

});

</script>

  

 Now You can access the values posted by jQuery.ajax through the global variable $_POST, like this:

 

 $bar = $_POST['bar'];

 

 

 You could also use the shorthand .post in place of .ajax in the above JavaScript code:

 

<script type="text/javascript">

 $.post('/form.php', serializedData, function(response) {

    // Log the response to the console

    console.log("Response: "+response);

});

 </script> 

Link to comment
Share on other sites

I'm not 100% sure what you're asking for here, but it sounds like you want a text field to show search results as you type using AJAX. If so, you just need an onkeyup event to trigger when typing in the text field. In the event handler, you'd perform an AJAX call to your server-side script, get the results, and then do whatever logic to add them to the search results.

 

Here's a quick JSFiddle to illustrate.

 

http://jsfiddle.net/2zrd10av/

 

Sorry that the photo which I attempted to attach did not show up.

 

I'm trying to use something similar to search suggestions where, as a person types for example if the word "apple" exists and a person types "a", then the sql database entry apple should appear in the display while also filling in the first suggesion by alphabetical order the word "apple", but instead of that, the search suggestion populates a div with entries.

 

The interface currently looks like this, which current runs on post via non-ajax (refreshes page on post/search)

 

post-164367-0-45349100-1436351191_thumb.png

 

This is just a mock of what I want to accomplish, currently when a result is displayed, the input shows "keyphrase" which is in the placeholder eg. this was not trickered by onkeyup rather by post with an exact match eg. apples not the letter a which is what I would like.

 

Anyway, the part that I haven't been able to bridge is the sql/php to ajax... I have seen % used in SQL for a partial call to get matching results by parts like a in apples... I have read through some articles about this... but anyway I'm going to look at the second response.

 

Thanks for your responses.

Edited by greenace92
Link to comment
Share on other sites

Anyway, the part that I haven't been able to bridge is the sql/php to ajax

There is no "bridge". AJAX is simply your browser performing a request to your server, just like you would do if you hit refresh or navigated to links. You would need a separate PHP script that can accept a search parameter, and return a JSON encoded list of results.

 

I have seen % used in SQL for a partial call to get matching results by parts like a in apples

Yes, they're called wildcards. There's information here: https://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html

 

You'd probably do something like:

SELECT * FROM fruits WHERE name LIKE 'a%';
Edited by scootstah
Link to comment
Share on other sites

Alright so this is my current working setup

 

I took the majority of the javascript script directly from W3Schools' tutorial here:

 

www.w3schools.com/php/php_ajax_livesearch.asp

 

I have not implemented the JSON part yet, do I need to? Notice I commented it out.

 

I was wondering about the combination of % and _, also curious about the IN operator, I can read up on that. So far I am accomplishing what I wanted but I was thinking about for example typing in a vowel which would happen in many words, the words would be listed... but this doesn't seem to be the case, % seems to be from left to right, the initial character and so on.

 

I wonder if there is some logic in that when they designed/created SQL because that would be a headache right? To display that many entries that have the single letter 'e' for example.

 

I'm also concerned about using GET, my aim is to pull the rows as I am doing now, but then individually modify them for example incrementing something in a specific row out of the rows pulled by the GET method... I imagine the increment part would be a separate script with its own POST method...

 

This is the script aspect: (literally from W3Schools)

<script>
function search(str) {

  if (str.length==0) {
    document.getElementById("livesearch").innerHTML="";
    document.getElementById("livesearch").style.border="0px";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
      document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
  xmlhttp.open("GET","partial_search.php?q="+str,true);
  xmlhttp.send();

}
</script>

PHP

<?php

echo "working".'<br>'.'<br>';

session_start();

$user = $_SESSION['company'];

if(empty($user)){
header("Location: example.domain.com");
}

mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL);
error_reporting(-1);
ini_set('display_errors',true);

require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'database_connection.php');

$link = new mysqli("$servername", "$username", "$password", "$dbname");

$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

$parts = parse_url($url);
parse_str($parts['query'], $query);
$input = $query['q'].'%';

// if($_SERVER['REQUEST_METHOD']=='POST'){

$query = "SELECT id,keyphrasee,numtimes FROM keyphrase WHERE user=? AND id > 0 AND keyphrasee LIKE ? ORDER by keyphrasee asc";

if($stmt = $link->prepare($query)){
$stmt->bind_param('ss',$user,$input);
$stmt->execute();
$stmt->bind_result($id_db,$keyphrase_db,$numtimes_db);

echo "query ran".'<br>'.'<br>';

while ($row = $stmt->fetch()) {

echo $keyphrase_db.'<br>'.'<br>';

// $arr = array('id' => $id_db, 'keyphrase' => $keyphrase_db, 'numtimes' => $numtimes_db);

// echo json_encode($arr);

}
}

// }
?>

Thanks for the help

Edited by greenace92
Link to comment
Share on other sites

You can use the wildcard in front and behind the queried parameter like this

SELECT * FROM fruits WHERE name LIKE '%a%';

But yes it would return anything with an "a" in it anywhere in the column you're searching.  The other thing that can done is to not send the request to ajax until there is at least 2-3 characters typed so there is a general reference to what they are looking for at that point.  That will also increase the likelyhood of returning more relevant items.

 

This seems to be similar to what you are trying to do - https://www.youtube.com/playlist?list=PLfdtiltiRHWGJA_SN2O9t5DSlz7PTwAru

Link to comment
Share on other sites

Hello fastsol,

 

That's a good point about the three char limit till send... Thanks for the tip about the % wow... that was so simple.

 

I am somewhat concerned on bandwith usage about constant ajax query search... for now this application is intended just for myself but... something to think about.

Link to comment
Share on other sites

Is there a way to measure the bandwith? Bandwith used per query, like store in a log or alert it after the response, etc... it's the return that uses the data most right, not the input? That would make sense, a few characters versus many rows from the database...

 

I mean... how bad could it be? (sounds like a prelude to a catastrophic event haha)

 

Okay I will look at implementing a timer / char count

 

 For now it is only myself using the application

Edited by greenace92
Link to comment
Share on other sites

In terms of actual bandwidth, like the size of the response, you're talking minuscule. Above I was talking more about server resources, like minimizing the number of requests for data and minimizing the impact of the requests for the data.

 

The problem you'll likely run into first is too many requests per second to your server. The three items I listed above will help with that.

 

EDIT: The thing you have to understand with AJAX is that you're basically multiplying your user count. Without AJAX, you'd have one server request per page load. With a modern AJAX-heavy frontend application, you basically have a static HTML page with a whole bunch of AJAX calls to get data from the server. You usually break your page down into small sections and then independently request data for those sections. So where you had one server request per user before, now you have 5-10+ server requests per user. It's easy to get carried away and not think about what is happening in the background.

 

But, that doesn't necessarily apply to you for this specific case, just wanted to throw that out there.

Edited by scootstah
Link to comment
Share on other sites

Hi Scootstah,

 

This is very good information to know.

Would you happen to know off hand as far as php.ini goes, what keywords applies to these limitations?

 

Isn't there a limit like 1000 request an instant or something like that? That's not the exact words but...

There was something like you could have 1,000,000 users connected but only 1,000 could post a comment at the same time

Link to comment
Share on other sites

That would be part of the HTTP server, not PHP - so Apache2 or Nginx or whatever you're using. There is a bunch of config values in Apache for determining how many concurrent connections can be handled. It's basically directly limited by how much memory your server has.

 

It's a bit of an art to get it tuned properly. But, I'd wait until you actually run into problems first.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.