AJAX on keypress? - php

So i'm a completely rookie at AJAX so I was wondering if someone could help.
I'd like to get this, SQL command to be activated onkeyup:
SELECT * FROM commands WHERE tag=$_POST['search_input']
This is the current code I have for the form:
<form method="post">
<input class="search_input" type="text" name="search_input" placeholder="Search..." onkeyup="suggest()" autocomplete="off" />
</form>
Current jQuery:
$(document).ready(function() {
$('.search_input').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
function handleKeyPress(e,form){
var key=e.keyCode || e.which;
if (key==13){
form.submit();
return false;
}
}
});
the function suggest() is what I'd like your guy's help on. To send the command above on a keypress.

Use $.post(). You have here examples http://api.jquery.com/jquery.post/
The basic structure is
$.post(url(string), data(object), function(response){ /* do something */ });
A delay between inputs would be really good so it won't continuously send requests to the server. You may also want to use keyup instead of keypress, test it and you'll see why.

I would recommend to use...
HTML
<form method="post">
<input class="search_input" type="text" name="search_input" placeholder="Search..." autocomplete="off"/>
</form>
JS
// shorthand for document ready
$(function(){
var $input = $('.search_input');
// using on-function (see jQuery Docs)
// bind event instead of using on-attribute (nicer)
// bind input event instead of keyup, because it will fire on paste too
$input.on('input', function(evt){
$.ajax({
// maybe use GET?
type: 'POST',
url: '/yourQueryPath',
// assign the input value to the needed query parameter
data: {'search_string': $input.val()},
success: function(response){
// whatever you want to to with your response
}
)};
});
});
Additionally a hint: Never use unfiltered user input like your SQL does (MySQL-Injection)!
E.g. if you are with PHP please use filter_input() and mysql_real_escape_string() or simliar.

Related

Multiple submit buttons on one page but distinguishable (jquery)

I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.

PHP + AJAX - Pass Current $_GET Variables So Far

I have a page where users fill out $_GET data for some options. I'd like to pass these $_GET variables using AJAX to a .php script. But my issue is how do I pass those $_GET variables they filled out so far, without refreshing the page?
Here is my code so far.
$.ajax({
type: "GET",
url: "serverside script to process on data",
data:{name:youwant}, // Here is where I want to take what the user has filled out so
// far, and place it here all without refreshing the page
success: function(data){
alert("return here if success")
}
})
First of all, drop this task into small ones:
1) Get/process variables in JavaScript
2) Send them to PHP
3) Parse/handle the ones
4) Depending on result send respond back to JavaScript
5) Handle that respond and display a message to user
Take a look at this example,
Let's assume that jquery.js is loaded.
Assume that we want to send the values of the inputs we have - email and password.
<script type="text/javascript">
$("#Send").click(function(){
$.ajax({
type : "GET",
//Look carefully:
data : {
// it'll be PHP vars // This is JS vars
email : $("#email").val(),
password : $("#password").val()
},
success : function(respondFromPHP){
alert(respondFromPHP);
}
});
});
</script>
<input type="text" id="email" />
<input type="password" id="password" />
<br />
<button id="Send">Send to php</button>
In your php script, just handle vars you get, like this:
<?php
print_r($_GET); // will print smth like Array("email" => "foo", "password" => "bar")
// Then create function so that you can simplify handling of the vars.
// Like this:
function validate_password($password){}
function validate_email($email){}
I don't know your code, but you can have a form, but instead of submit it, you put a onsubmit method to a javascript function. In that function you gather all variables and pass it through ajax.
Example: <form name="form1" method="get" onSubmit="return send()">
<script>
function send() {
$.ajax(...);
return false;
}
</script>
You can use seralize function to send in $.ajax data field

php parsing jQuery form serialize wrong way

I have one problem...
These are names of some my html form elements:
name="password"
name="meta[naziv_firme]"
This is my jQuery
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
console.log(data);
$.get('/index.php/admin-ajax', data,
function(response){
// Success
$('div#edit-klijent-div,.tipsy').hide();
$('div#klijent-edit-success').show();
});
Console.log gives me result:
action edit
form userID=12&password=&password-match=&email=test15%5Bmeta%5Bnaziv_firme%5D=test15&meta%5Bkontakt_osoba%5D=test156&meta%5Bkontakt_telefon%5D=test157&meta%5Bkontakt_email%5D=test158
So everything look OK!
Now in PHP I have var_dump($_GET); and the result is:
string(165) "userID=12&password;=&password;-match=&email=test15&meta;[naziv_firme]=test15&meta;[kontakt_osoba]=test156&meta;[kontakt_telefon]=test157&meta;[kontakt_email]=test158"
Why does PHP put ; after password, in &meta;[... ??
And ideas? What am I doing wrong?
Thank you!
In your HTML form element, add:
<input type="hidden" name="action" value="edit">
And change this line:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
Into this:
var data = $('input', 'form#edit-klijent-form').serialize();
Can't really test it since I don't have your HTML or server configuration, but I think it should work.
Update:
To clarify #AnthonyGrist's comment above, let's observe what serialize does:
<form>
<input type="text" name="input1" value="foo">
<input type="text" name="input2" value="bar">
</form>
<script>
var data = $('form input').serialize();
// data is now: 'input1=foo&input2=bar'
</script>
If you assign the value returned above to a query parameter (which PHP accesses using $_GET), you're basically telling PHP that $_GET['form'] equals the string above, which is not what you intended. PHP would not parse the contents of $_GET['form'] to give you $_GET['input1']... The value returned by serialize() should be used as the 2nd argument to $.get() directly.
Change your code from:
var data = {action: 'edit', form: $('input', 'form#edit-klijent-form').serialize()}
To:
var data = "action=edit&" + $('input', 'form#edit-klijent-form').serialize();
I think it is what you're trying to achieve.

What does jquery .ajaxsubmit pass?

I am trying to use jquery's form plugin from http://www.malsup.com/jquery/form/#ajaxSubmit and .ajaxsubmit to submit my data in a form however I am not really sure what .ajaxsubmit is passing and how I can read this in my php file.
I have a validate function
function validate(formData, jqForm, options) {
alert('About to submit: \n\n' + queryString);
return true;
}
that shows queryString which is
first=testfirstname&last=testlastname&age=90
when I use .ajaxsubmit, nothing happens as listed in my script below.
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: validate,
success: showResponse
};
//submission
$('#myForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
My form is
<form action="comment.php" method="post" id="myForm">
I was wondering what format is the data being sent, would I do something with
$_REQUEST['first'];
and also how would I also pass in an addition value from the $_SESSION?
Thanks
As far as I know, the jQuery plugin actually sends the plugin data as POST-data to PHP (similar to setting method="post" on your <form> tag). You can access it like this:
$_POST['name_of_field_in_form'];
The name_of_field_in_form is just the name of a field, for example if you have this code <input name="email" type="text" />, you could access it via $_POST['email'];.
About your second query, not sure what you mean, but you can use session_start(); to create a session and after that $_SESSION acts like a 'normal' array.

Autosaving Form Input Using Prototype and PHP

I'm implementing a relatively simple autosave system and I'd like to do so using the Prototype library. I'm using the PeriodicalUpdater request, but it's not working as I'd hoped. In short, I'm trying to, periodically, send a textarea's content via an AJAX request to a PHP page that will save it to a MySQL database. I'm doing something like (abbreviated code):
<html>
<head>
<script type="text/javascript" src="scripts/prototype.js"></script>
<script>
function autosave() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
}
</script>
</head>
<body>
<input type="hidden" id='id' name='id' />
<textarea id='myInput' name='myInput'></textarea>
<script>
autosave();
</script>
</body>
</html>
Then autosave.php will take the form contents and write them to my database. That part is working fine. What is happening, as I discovered, is PeriodicalUpdater is called with the original form input, then is called periodically with that initial form input.
So that was a long setup for a relatively short question: How do I use Prototype (if possible) to periodically make an AJAX request using the current textarea's value?
you could just use Ajax.Request with setinterval,something like this:
document.observe("dom:loaded", function() {
intervalID = window.setInterval("autosave()",500);
});
function autosave() {
new Ajax.Request('autosave.php',
{
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
});
}
Ajax.Request is the right move, but why not make it more reusable
If you just have one input, or even if you had many I'd advise something like:
<form action="/user/4" method="post">
<input type="text" name="user[name]" value ="John" class="_autosave" />
<input type="hidden" name="user[id]" value ="4" class="uid"/>
<input type="submit" />
</form>
...
$$('input._autosave').each(function(s){
s.observe("change", function(event){
var el = event.element();
var uid = el.next("uid").value;
var r = new Ajax.Request(el.up("form").readAttribute("action"),{
parameters: {el.readAttribute("name"): el.value},
});
});
});
Just place your periodical updater in dom:loaded event. It is used to ensure that all components have been loaded, better than using window.onload event. Just remember, that there is a little bit different between dom:loaded event and native window.onload event, where dom:loaded called when all dom loaded except images and window.onload called when all dom loaded including images file.
document.observe("dom:loaded", function() {
new Ajax.PeriodicalUpdater('save_message', 'autosave.php', {
method: 'post',
parameters: {id: $('id').value, save_text: $('myInput').value},
frequency: 5,
decay: 2
});
});

Categories