Ajax PHP MYSQL on enter - php

I am using the below code to search a mysql database but cannot get the form to submit when the return key is pressed.
Does anybody have any ideas?
function ajaxFunction(){
var ajaxRequest;
{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var kw = document.getElementById('kw').value;
var division = document.getElementById('division').value;
var queryString = "?kw=" + kw + "&division=" + division;
ajaxRequest.open("GET", "search/jsearch.php" + queryString, true);
ajaxRequest.send(null);
}
Form code is:
<form name='myForm'>
Keywords<input type='text' id='kw' /> <br />
<br />
<select id='division'>
<option value='0' selected="selected">window & door</option>
<option value="1">window</option>
<option value="2">door</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>

Where is your event code for the form? Are you using an onclick instead of onsubmit? I don't think we have enough code/information to answer this, but from what you describe your first step to make sure you are using an onsubmit event for the form so you can fire off the xhr.
EDIT:
Then the answer to this problem: "...cannot get the form to submit when the return key is pressed", is use onsubmit instead of onclick. You also need to attach the event to the form instead of the button, and if possible refrain from using inline js.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

onclick fires when you click the button. You are pressing return, not clicking the button.
As mentioned earlier, you should use onsubmit which fires when the form is submitted. You will need to return false, ie use onsubmit="ajaxFunction();return false;", to prevent the normal submission from occurring.

Related

Cross Browser Ajax Issue

I have created an ajax function that works on chrome and firefox but not i.e 8 can anyone spot the issue?
html section:
<select id='choices'>
<option id="no" value="no" onClick="check()">No</option>
<option value="yes" onClick="check()">Yes</option>
</select>
Javascript section:
function check(){
var a = document.getElementById("choices").value;
var type = "label";
ajaxFunction(a,type);
if(a == "yes"){
document.getElementById("results").style.display="block";
}
else{
document.getElementById("results").style.display="none";
}
}
AJAX Section:
function ajaxFunction(result,dif){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(dif == "label"){
var ajaxDisplay = document.getElementById('results');
}
else{
var ajaxDisplay = document.getElementById('results1');
}
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
if(dif == "label"){
var hiddenvalue = document.getElementById('hiddenvalue').value;
var queryString = "?type=" + result + "&label=" + hiddenvalue + "&dif=" + dif;
}
else{
var queryString = "?type=" + result + "&dif=" + dif;
}
ajaxRequest.open("GET", "scripts/script.php" + queryString, true);
ajaxRequest.send(null);
}
PHP Section:
var_dump($_GET);
I'm not sure if this is just a compatability issue or not as i have used very similar code to this in another project which worked fine however i also have a couple of other scripts that are loading in such as jquery 1.2.3 and google analytics (with there advanced link tracker which i had to get rid of as it was throwing an error). I have checked the debugger and clicked break all on error and i can click about on the onclick but no error actually shows in the debugger. Has anyone got any sugestions other then jquery (can't get my head around it)
IE does not suppot onclick on an option.
onchange needs to be on the select.
<select id='choices' onchange="check()">
<option id="no" value="no">No</option>
<option value="yes">Yes</option>
</select>

AJAX weird redirection?

I have some AJAX code that is redirecting when button is pressed.
It is redirecting to members.php
This is the AJAX code:
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Please update your browser.");
return false;
}
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
// We still need to write some code here
if(ajaxRequest.readyState == 4){
// Get the data from the server's response
response = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "accept.php?id=<?php echo $articleid; ?>&state=accept$p=a9dafdd0fe68c6f64841e265e1c8832a", true);
ajaxRequest.send(null);
}
</script>
And this is the button:
<input type="submit" onChange="ajaxFunction();" />
And this is the contents of accept.php:
<?php
echo "ACCEPTED";
?>
Ideas?
<input type="submit" onChange="ajaxFunction();" />
should be
<input type="submit" onclick="ajaxFunction();" />
and use return false; at the end of your function
or you can use simple jquery
$("#submit").click(function(){
// or $("#form").submit(function(){
$.get("accept.php?id=<?php echo $articleid;
?>&state=accept&p=a9dafdd0fe68c6f64841e265e1c8832a",function(data){
rasponce=data;
})
return false;
})
what is this?
"&state=accept$p=a9dafdd0fe68c6f64841e265e1c8832a",
... should it be something like
"&state=accept&p=a9dafdd0fe68c6f64841e265e1c8832a",
members.php is the action on your form? If so I'd remove the action and try it again, to see what happens.

more than one form with the same input ID send just the first value with Ajax

I am doing ajax function to do insert into DB using form and input type=hidden but when I put more than form in the same page it is always take just the first value in the first form
here is the code:
the Ajax function
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("ajaxDiv");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var in1 = document.getElementById("in1").value;
var queryString1 = "?in1=" + in1;
//ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString, true);
ajaxRequest.open("GET", "/sites/all/php/check.php" + queryString1, true);
ajaxRequest.send(null);
}
//–>
</script>
here is the html forms
<form name="myForm1">
<input type="hidden" value="1" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
<form name="myForm2">
<input type="hidden" value="2" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
<form name="myForm3">
<input type="hidden" value="3" id="in1">
<a onclick="ajaxFunction()" class="folloo"></a>
</form>
</form>
</form>
and here is the check.php code that do the DB query
<?php
//Connect to MySQL Server
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","admin","123456") or die('Cannot connect to the database
because: ' . mysql_error());
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("dbname") or die("Unable to select database");
//select which database we're using
// Retrieve data from Query String
$in1 = $_GET['in1'];
// Escape User Input to help prevent SQL Injection
$in1 = mysql_real_escape_string($in1);
//Build and run a SQL Query on our MySQL tutorial
if($in1){
mysql_query("INSERT INTO test (name)
VALUES ('" . $in1. "')");
}
?>
put when i click on any link it is always send the first value.
cah anyone tell mewhat is the problem here?
id values must be unique on the page. You've shown that you have multiple input type="hidden" elements with the same id value ("in1"). If you have more than one element with the same id value, when you try to look it up (for instance, using getElementById), most browsers will give you the first one, but it's undefined behavior because the markup/DOM is invalid.
The fix is to fix the IDs so that they're unique, or not use IDs at all and use something that isn't required to be unique, such as name or class — but then you'll need to retrieve it with querySelectorAll or similar, and deal with the fact that you have multiple matching elements.

Submit Values via POST to multiple PHP files

I have a form :
<form action="moods.php" method="post" id="geog">
Longitude: <input size="15" id="lonbox" name="lon" type="text" />
Latitude: <input size="15" id="latbox" name="lat" type="text" />
<input type="submit" />
</form>
I wish to submit the values of latitude and longitude to multiple .php files apart from moods.php at the same time using the single above form.
How can I do that?? please suggest some ways ..
why have the form submit to multiple pages, when you can have one single script include() the other scripts?
require('script1.php');
require('script2.php');
require('script3.php');
You could submit it to a file containing a cURL script that would handle multiple submissions
<form action="multi_submit.php" method="post" id="geog">
on multi_submit.php handle the form submission using cURL
If you really need to submit the values over multiple .php files, and the require option gave by dqhendricks does not solve it, why not to use several Ajax calls? One for each file.
You could have something like this:
<form onsubmit='sendSeveralPost()'>
... form fields
</form>
And the javascript function
function sendSeveralPost() {
var f1 = document.getElementById('field1');
var f2 = document.getElementById('field2');
var x = getXmlHttp();
var params = 'field1='+f1+'&field2='+f2;
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.setRequestHeader("Content-length", params.length);
x.setRequestHeader("Connection", "close");
var files = new Array();
files[0] = 'script1.php';
files[1] = 'script2.php';
files[2] = 'script3.php';
for (i=0;i<files.lenght;i++) {
var url = files[i];
x.open("POST", url, true);
x.onreadystatechange = function() {//Call a function when the state changes.
if(x.readyState == 4 && x.status == 200) {
alert(x.responseText);
}
}
x.send(params);
}
}
function getXmlHttp() {
var xmlHttp;
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) {
try { // Internet Explorer 6.0+
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e){
try { // Internet Explorer 5.5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
Further explanations about the commands can be found at the article http://www.openjs.com/articles/ajax_xmlhttp_using_post.php, from where I took the inspiration for this example.
Hope this helps.
Namastê!

MySQL/PHP: Update MySQL with Ajax

I am a beginner and I am trying to learn how to add, delete, retrieve and update a database using PHP and Ajax.
At this time I have accomplished how to retrieve and delete so I am trying to update some values. For retrieving data, I just pass the selected ID I want, so I can retrieve the data. Same goes for delete, I just assign which ID I want to delete. Now to update there are more things going on, its where I cant find the solution.
This is my Form:
<form onsubmit="updateuser()">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="Submit" value="Update">
</form>
and this is my javascript:
function updateuser() {
var str = $('.ud_id').attr('value');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?q=" + str, true);
xmlhttp.send();
}
I think the problem comes because my form ajaxupdate.php file doesn't retrieve the First and Last name values from the form. It's like I am not passing them (?).
Here is my ajaxupdate.php file:
<?php include("connection.php");
$id=$_GET['ud_id'];
$first=$_GET['ud_first'];
$last=$_GET['ud_last'];
$query="UPDATE contacts SET first='$first', last='$last' WHERE id='$id'";
mysql_query($query);
mysql_close();
?>
What I'm I doing wrong so that I can update the value first and last of database for a specific ID ?
Try this code
<script type="text/javascript">
function updateuser() {
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
</script>
HTML
<form name="test">
ID Number: <input name="ud_id"><br>
First Name: <input type="text" name="ud_first"><br>
Last Name: <input type="text" name="ud_last"><br>
<input type="button" onClick="updateuser()" value="Update">
</form>
In your javascript, do this
function updateuser() {
var ud_id = $('input[name="ud_id"]').val();
var ud_first = $('input[name="ud_first"]').val();
var ud_last = $('input[name="ud_last"]').val();
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtuser").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last, true);
xmlhttp.send();
}
If you want to use the updateuser() function on submit, then it must prevent the form from actually submitting. Make it return false, otherwise the form gets submitted by the browser before the function has time to execute.
The browser runs the function before submitting the form (that's how on submit works). If the function doesn't return false, then it interprets that as "everything is OK, you can safely submit the form". The form then gets submitted as usual.
In the mean time, the function initiates the asynchronous request. But since the browser has already submitted the form, now you're on a totally different page, thus the connection and the asynchronous request get disconnected and most likely ignored (unless of course the request made it before the page was changed, in which case both requests are processed).
As an alternative, you could execute the function without placing it in the on submit event. See sam_13's answer.
Check this it will work as expected
ud_id = document.getElementById('ud_id').value;
ud_first = document.getElementById('ud_first').value;
ud_last = document.getElementById('ud_last').value;
xmlhttp.open("GET", "ajaxupdate.php?ud_id=" + ud_id +"&ud_first=" +ud_first+ "ud_last="+ud_last, true);
<form onsubmit="updateuser()">
ID Number: <input name="ud_id" id="ud_id"><br>
First Name: <input type="text" name="ud_first" id="ud_first"><br>
Last Name: <input type="text" name="ud_last" id="ud_last"><br>
<input type="Submit" value="Update">
</form>
I came accross this example because i am also running into a similar issue. however I couldnt help but notice that you do not specify a method for your form and your AJAX is assuming it should use the GET method. just food for thought... cheers
This code is tested and works. I needed to do the same thing, update MySql with ajax and combining the above with a wider research I got this to work.
The php file is called ajaxupdate.php:
<?php
$id= $_GET['ud_id'];
$first= $_GET['ud_first'];
$last= $_GET['ud_last'];
require_once ('mysqli_connect.php'); //connection to the database
$sql = "UPDATE contacts SET FirstName ='$first', LastName='$last' WHERE id='$id'";
$result = mysqli_query($dbc,$sql);
mysqli_close($dbc);
?>
The Html file called anyNameYouWish.html:
<html>
<head>
</SCRIPT>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
function MsgBox (textstring) {
alert (textstring) }
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var ud_id = document.getElementById('ud_id').value;
var ud_first = document.getElementById('ud_first').value;
var ud_last = document.getElementById('ud_last').value;
var queryString = "?ud_id=" + ud_id + "&ud_first="+ud_first+"&ud_last="+ud_last;
ajaxRequest.open("GET", "ajaxupdate.php" + queryString + "&random=" + Math.random(), true);
ajaxRequest.send(null);
}
</script>
</head>
<body>
<form method="post" name="test" onsubmit="ajaxFunction()">
ID Number: <input id="ud_id" name="ud_id"><br>
First Name: <input id="ud_first" type="text" name="ud_first"><br>
Last Name: <input id="ud_last" type="text" name="ud_last"><br>
<input type="submit" value="Update">
</form>
</body>
</html>

Categories