MySQL/PHP: Update MySQL with Ajax - php

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>

Related

Sending POST with javascript

What is wrong with this code? Trying to send data over POST w/ javascript to a PHP page but it isn't sending anything, nothing comes across in the headers $_POST contains nothing.
HTML:
<form method="POST" id="userSub" class="userSub">
<table>
<tr><td colspan="2">Sign In Here </td></tr>
<tr><td>Username:</td><td><input name="username" type="text" id="username" /></td></tr>
<tr><td>Password:</td><td><input name="pwd" type="text" id="pwd" /></td></tr>
<tr><td><input name="submit" type="submit" value="submit" id="submit" onclick="loginSub()" /></td></tr>
<tr><td colspan="2">Need a Username? Sign Up</td></tr>
</table>
</form>
Javascript:
function loginSub(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("rssnav2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","PHP/login.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
PHP doesn't do anything special right now, just seeing if I can pass the post information to it:
<?php
echo "test";
$username=$_POST['username'];
echo $username;
?>
It is IS echoing that 'test' line to the correct so it is communicating w/ the PHP page. Also, I know that I still have the pwd input in "text" type and I know its probably a good idea to hash a password before sending it to the server.
Thanks for your help, everyone!
The xmlhttp doesn't actually have any knowledge of the <form>, so it won't send any data automatically.
You'll instead have to gather the <form>'s data yourself, format it as URL-encoded, and .send() it along with the request.
function loginSub(){
var user = document.getElementById('username');
var pass = document.getElementById('pwd');
var postData = [
encodeURIComponent(user.name) + '=' + encodeURIComponent(user.value),
encodeURIComponent(pass.name) + '=' + encodeURIComponent(pass.value)
].join('&');
// ...
xmlhttp.send(postData);
}
For more details, you may want to read through MDN's Using XMLHttpRequest, especially the sections on Using nothing but pure AJAX.
It includes a generalized solution for gathering <form> data in A little vanilla framework, which you could use with:
<form method="POST" action="PHP/login.php" onsubmit="AJAXSubmit(this); return false;">
Side note:
Your <form> is likely still submitting as well and may interrupt the Ajax request. You can prevent this by cancelling its onsubmit event:
<form method="POST" id="userSub" class="userSub" onsubmit="return false">
Also, there are more ways to submit a <form> than clicking the type="submit". For example, most browsers allow submitting by simply tapping Enter while typing in a type="text" or type="password". And, doing so won't typically imitate a click of the type="submit".
So, you'll want to at least consider moving the call out of the onclick and into the onsubmit:
<form method="POST" id="userSub" class="userSub" onsubmit="loginSub(); return false;">
You are not sending parameters in your XMLHttpRequest. Something like:
var params = "username=user&password=something";
xmlhttp.open("POST", "PHP/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("rssnav2").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(params);
Try changing
xmlhttp.send();
to
xmlhttp.send('username='+document.getElementById('username').value);
Of course you will need to put in validation logic.
function loginSub()
{
var xmlhttp = false;
if(window.XMLHttpRequest)
{
if(typeof XMLHttpRequest != 'undefined')
{
try
{
return xmlhttp= new XMLHttpRequest();
}
catch(e)
{
return xmlhttp= false;
}
}
else if( window.ActiveXObject)
{
try
{
return xmlhttp= new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e)
{
try
{
return xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e)
{
return xmlhttp = false;
}
}
}
}
var xmlhttp=false;
xmlhttp=createobject();
if(xmlhttp)
{
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('rssnav2').innerHTML = xmlhttp.responseText;
}
}
parameter=username+'='+document.getElementById('usernname').value;
xmlhttp.open('POST','PHP/login.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameter);
}
}
this will solve your problem

Why with ajax I can update mysql but cannot use value from mysql/php variable?

All happens in one php file
HTML code
<td>
<input type="text" name="date_day1" id="date_day1"
value="<?php echo $_POST['date_day1']?>" size="1">
</td>
<td>
<input type="text" name="amount1" id="amount1"
value="<?php echo $_POST['amount1']?>" size="5"></td>
Then javascript
<script type="text/javascript">
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp; // The variable that makes Ajax possible!
//Global XMLHTTP Request object
//Creating object of XMLHTTP in Internet Explorer
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc) {
XmlHttp = null;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
// Set var the new request Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}//try {
catch (e) {//if it fails move onto the next
xmlhttp = false;
}//catch (e) {
}//if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
return xmlhttp;
}//function getHTTPObject() {
function init(){
window.setInterval(autoSave,3000); // 15000=15 seconds
}
function autoSave(){
var date_day1 = document.getElementById("date_day1").value;
var amount1 = document.getElementById("amount1").value;
var params = "date_day1="+date_day1+"&amount1="+amount1;
var http = getHTTPObject();
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
</script>
And php
$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($_SERVER["REQUEST_METHOD"]=="POST"){
if ($stmt = mysqli_prepare($mysqli,
"UPDATE 2_1_journal SET Amount = ? WHERE RecordDay = ? ") ) {
$stmt->bind_param( 'ds', $amount1 , $date_day1 );
$stmt->execute();
echo $date_day1 .' date_day1 from update<br>';
echo $amount1 .' amount1<br>';
}
}
So what happens. Javascript (ajax) without clicking button takes user input, send to php code. Php code updates mysql. That means that somehow without clicking submit button are created php variables to update ($amount1 , $date_day1)?
But why these variables do not exist latter? I want without page refresh (without clicking submit button) use variables. For example in input form as value=""
How to do that? As I understand need to use json? but from information I have found can not understand.... Can someon write step by step how with json pass user input (or value from mysql) to input value=""
Or may be some book/tutorial how all works (book/tutorial for dummies to understand)?
Your php script should echo a json. For example, i have ajax.php:
<?php
$myVariable = $_POST['myVar'];
//Do something with database here
//Here goes whatever you want to pass back to your page
echo json_encode(array('result' => 'Done doing things', 'data' => $someData)).
// This outputs a json
// {"result" : "Done doing things", "data" : "Contents of $someData"}
And then jQuery will process this. Where your html file is something like
<html><head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('.myButton').click(function(e) {
e.preventDefault(); //Prevent the page from reloading
$.post('ajax.php', function(data) {
$('#myContent').html(data.result); //Put the result into the div
}, 'json');
});
});
</script></head>
<body>
<div id="myContent">This text will be replaced</div>
Click Me
</body>
</html>
Read here about jQuery post function.
http://api.jquery.com/jQuery.post/
Don't forget to include the jQuery library (read the documentation thoroughly).
If you need the data to be not erased between calls, you can :
Pass it back in your json and store it in a javascript variable,
Store it in the session or cookie
Store it in the database

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ĂȘ!

Javascript. Passing input variables throughout pages via AJAX

This is a Google suggestion-like script.
I rewrote the AJAX Call code by splitting it up into multiple functions and seems this is a better cross-browser/usability approach. Now I need to pass the input variable that I read from the input #search_text to a php file where I actually fetch the data from database.
For moment all I need is to pass search_text and display it with echo $_GET['search_text'];
Can someone help me?
Here is the script
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php");
}
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and the php file is:
<?php
echo 'Something';//'while typing it displays Something in result div
//echo $_GET['search_text'];
?>
Thanks
The issue is that you're not actually passing in any data to the PHP script. In this case, you need to stick the 'search_text' parameter on the end of the URL, since you're expecting it to be a GET request.
startRequest("ajax-submit.php");
should be
startRequest("ajax-submit.php?search_text="+document.search.search_text.value);
this jQuery Solution is way easier and Cross-Browser compatible:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$('#search_text').keydown(function(){ // Bind event to KeyDown
var search_text = $(this).val(); // get value of input field
$.ajax({ // fire Ajax Request
url: "ajax-submit.php?search_text=" + search_text,
success: function(result){
$("#results").html(result); // on success show result.
}
});
});
});
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" />
</form>
<div id="results" style="background:yellow"></div>
</body>

AJAX on localhost using IIS and php and MySQL

I am trying AJAX for the first time on my localhost.
I am using IIS and PHP with MySQL.
This error is generated: "A HTTP Error 404.3 - Not Found" when I try this javascript command:
xmlhttp.send(null);
xmlhttp is a varable and is used to retrieve the GetXmlHttpObject
Just in-case something inside your xmlhttp object creation is not setup correctly or you have not waited for the correct status, have you looked at some simple xamples like from XUL.fr or W3 Shools or Your HTML Source?
Below is a simple example. Notice the inline function for the onreadystatechange callback and the check on readystate and status. I believe your issue may reside in you note doing these checks, but without your code I could be wrong.
<html>
<head>
<script>
function submitForm()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open(GET, "data.txt", true);
xhr.send(null);
}
</script>
</head>
<body>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>
</body>
</html>

Categories