'How can I make good efficent AJAX live forms with just jQuery and
I've been trying to make AJAX forms but made no luck, I tried using iframes but I frames aren't that good. That's all I've tried, and that's all I know.
I have tried using the $.AJAX function but not sure how exactly to send data and receive it back
I have also used the AJAX load function, but that's also smt I counlt figure out on how to send data via.
I tried many pure JavaScript ways but there just too messy
And also, how can I return the variables back form the server to make the text box red and showerrors.
Solution 1:[1]
You can send ajax request like this
JQUERY code for sending ajax request to the server
$.ajax({ method:"POST" url:"form.php", data: $("form").serialize(), dataType: 'json', success: function() {
// code to run in success
},
error: function() {
// code to run on an error
}
});
then you can return the data like this
PHP code to return data back as json
// make sure that this is an array to send multiple data back
echo json_encode($data);
PHP code to get data from client
$_REQUEST['username'];
and to read the data via JS , you should put this in our success function
JS code to access returned json data from server
data.name
// ^ ^ ^
// the first arrow is the php var
// the second arrow is the array offset
Solution 2:[2]
I am adding a simple example for you to search the names using keywords.
action.php
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
index.html
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "action.php?q="+str, true);
xmlhttp.send();
}
}
</script>
<p><b>Start typing a name in the input field below:</b></p>
<form action="">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |
Solution 2 | John Doe |