Jump to content

Fairly simple - Update mysql field to "1"


Recommended Posts

Vigilant Psyche,

 

The following two PHP scripts, and the included JS AJAX script will do the trick.

 

Scot L. Diddle, Richmond VA

 

 


<?php

$id = 3;  // Hard coded for brevity...

$AJAXDivMessage = '<strong><font color=white>  Please wait while the DB is being updated...   <font><br /><strong>';

$html = <<<EOH

	<html>

	<head>

		<style>

			a.ajax:hover {
		      color: WHITE;
		    }

		    a.ajax:link {
		      color: WHITE;
		    }

		    a.ajax:visited {
		      color:  WHITE;
		    }

		    a.ajax:active {
		      color: WHITE;
		    }

		   #div_populate {
       		 		color: #white;
    				background-color:#205E75;
    				width:70%;
    				padding-top:15px;
    				padding-bottom:15px;
   		 		}

		</style>

		<script type="text/javascript" src="javascript/ajaxSQLDriver.js" language="javascript"></script>

		<!--                                                                                                  --> \n
		<!--    It contains the functions:   xmlhttp();                                                       --> \n
		<!--                                 getcontent(url, containerid,divMessage)                          --> \n
		<!--                                 loadpage(xmlhttp_obj, content, containerid) {                    --> \n
		<!--                                 getcontent_post(url, content, containerid, divMessage) {         --> \n
		<!--                                 submit_form(page_to,form_name,containerid,divMessage) {          --> \n
		<!--                                 convertFormDataToPostContent(form_y) {                           --> \n

	</head>


	<body>

	<center>



		<div id="div_populate" class="div_populate">

			<form name='updateForm' id='updateForm' method='POST' action='ajaxUpdate.php'>

			<br /><br />

				<a class="ajax" href="javascript:submit_form('updateSQLDB.php?id=$id','updateForm','div_populate','$AJAXDivMessage');">Click Here to Update DB</a></ul></ul>

			<br /><br />

		</form>

	</center>

	</body>

	</html>

EOH;

echo $html;

?>

 

 

Here is the program called via the AJAX JS:

 

 


<?php

// updateSQLDB.php, called from ajaxSQLDriver.js, via ajaxUpdate.php

$id = $_GET[id];

if(function_exists(mysql_query)) {

	$SQLQureyResult = mysql_query("UPDATE user SET active='1' WHERE id='$id'");

	if (!$SQLQureyResult) {

		echo "<br /> <br /> \n";

		echo "<font color=\"white\">Ratz !:: Did not update UserID: $id  </font>"  . "<br /> <br /> \n";

	}

}
else {

	echo "<br /> <br /> \n";

	echo "<font color=\"white\">Ratz ! :: Did not update UserID: $id  because the MySQL Function \"mysql_query()\"  is un-available...</font>"  . "<br /> <br /> \n";


}


?>

 

And here is the AJAX JS Magic:

 

    /* 'javascript/ajaxDriver.js'               */
    /*                                          */
    /* Called from 'ajaxUpdate.php'             */
    /*                                          */
    /*    Around Line 52                        */
    /*                                          */

    /**
     *
     *  For JS Statement:
     *
     *  var formObj = document.getElementById(formname);
     *
     *      It works great in IE, but on FF it craps out.
     *      I have tried this several different ways, but it
     *      refuses to grab all of the form elements.
     *
     *  Answer from: http://geekswithblogs.net/thibbard/archive/2005/12/03/62046.aspx
     *
     *      You need to set the id attribute of the form tag to be [formname]
     *
     *          <form name="formname" id="formname"...
     *
     *              IE picks up on 'name' which is where the confusion lies...
     *
     */

    rangeBoolean = false;

    // var domain = 'http://172.16.238.147/'; //set domain
    var loading_img = '../images/ajaxLoader.gif'; //set image path
    // Find one here: http://www.phil.muni.cz/wcit/w-Pictures/ikony-moodlu-1.8/i/ajaxloader.gif/image_view_fullscreen

    var loading_No_img = '../images/pixel.gif'; //set image path
    // var loading_msg = '<b>     Querying Oracle for available dates ... Please Wait... </b>';//set loading message
    var xmlhttp_obj = false;

    //create the XMLHttpRequest
    function xmlhttp() {
        if (window.XMLHttpRequest){ // if Mozilla, Safari etc
            xmlhttp_obj = new XMLHttpRequest();
        }else if (window.ActiveXObject){ // if IE
            try{
                xmlhttp_obj = new ActiveXObject("Msxml2.XMLHTTP");
            }catch (e){
                try{
                    xmlhttp_obj = new ActiveXObject("Microsoft.XMLHTTP");
                }catch (e){
                }
            }
        }else{
            xmlhttp_obj = false;
        }
        return xmlhttp_obj;
    }

    //get content via GET
    function getcontent(url, containerid, divMessage) {
        var xmlhttp_obj = xmlhttp();
        var loading_msg = divMessage;

//      alert('url 1' + url);
//      alert('containerid 1' + containerid);
//      alert('divMessage 1' + divMessage);

        document.getElementById(containerid).innerHTML = '<img src="' + loading_img + '" />' + loading_msg;
        xmlhttp_obj.onreadystatechange=function(){
            loadpage(xmlhttp_obj, '', containerid);
        }
        xmlhttp_obj.open('GET', url, true);
        xmlhttp_obj.send(null);
    }

    function loadpage(xmlhttp_obj, content, containerid) {

        if ( xmlhttp_obj.readyState == 4 && xmlhttp_obj.status == 200 ){
            document.getElementById(containerid).innerHTML = xmlhttp_obj.responseText;
        }
    }

    //functions for posted values from forms vis POST
    function getcontent_post(url, content, containerid, divMessage) {

//      alert('url ' + url);
//      alert('content ' + content);
//      alert('containerid :' + containerid);
//      alert('divMessage :' + divMessage);


        var loading_msg = divMessage;

        var xinput = content;

        var xmlhttp_obj = xmlhttp();

        if (divMessage == '') {
            document.getElementById(containerid).innerHTML = '<img src="' + loading_No_img + '" />' + loading_msg;
        }
        else {
            document.getElementById(containerid).innerHTML = '<img src="' + loading_img + '" />' + loading_msg;
        }
        xmlhttp_obj.open('POST', url, true);
        xmlhttp_obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp_obj.onreadystatechange = function() {
            loadpage(xmlhttp_obj, content, containerid);
        }
        xmlhttp_obj.send(content);
    }
    //convert form data sent to POST CONTENT
    function submit_form(page_to,form_name,containerid,divMessage) {

        // alert('Ajax Mom');
        var content = convertFormDataToPostContent(form_name);
        getcontent_post(page_to, content, containerid, divMessage);
    }

    function convertFormDataToPostContent(form_y) {


        // alert('form_y : ' + form_y);

        var f=document.getElementById(form_y);
        var content_to_submit = '';
        var form_element;
        var last_element_name = '';
        for (i = 0; i < f.elements.length; i++){
            form_element = f.elements[i];
            switch (form_element.type){
                // text fields, hidden form elements
                case 'text':
                case 'hidden':
                case 'password':
                case 'textarea':
                case 'select-one':
                content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
                break;
                // radio buttons
                case 'radio':
                    if (form_element.checked){
                      content_to_submit += form_element.name + '=' + escape(form_element.value) + '&';
                    }
                break;
                // checkboxes
                case 'checkbox':
                    if (form_element.checked){
                        // Continuing multiple, same-name checkboxes
                        if (form_element.name == last_element_name){
                            // Strip of end ampersand if there is one
                            if (content_to_submit.lastIndexOf('&') == content_to_submit.length - 1){
                              content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
                            }
                            // Append value as comma-delimited string
                            content_to_submit += ',' + escape(form_element.value);
                        }else{
                            content_to_submit += form_element.name + '=' + escape(form_element.value);
                        }
                        content_to_submit += '&';
                        last_element_name = form_element.name;
                    }
                break;
            }// END switch
        } // END for

        // remove trailing separator
        content_to_submit = content_to_submit.substr(0, content_to_submit.length - 1);
        return content_to_submit;
    }

    function placeParmErrorQuery() {

        Get_placeParm_Error('placeParmErrorDisplay.php','dateForm','Error_populate','');

    }

    function Get_placeParm_Error(page_to,form_name,containerid,divMessage) {

        var content = convertFormDataToPostContent(form_name);
        getcontent_post(page_to, content, containerid, divMessage);

    }

// END 'javascript/ajaxSQLDriver.js'

Link to comment
Share on other sites

My god that is overkill.

 

html:

<div id="span_list"><span>1</span> <span>2</span></div>[code]
javascript:
[code]function spanListener()
{
    var spans = document.getElementById("span_list").getElementsByTagName("span")
    for(var i = 0; i < spans.length; i++)
    {
        spans[i].onclick = function()
        {
            try
    {
	// Firefox, Opera 8.0+, Safari
	xmlHttp=new XMLHttpRequest();
	xmlHttp.overrideMimeType("text/xml");
    }
    catch (e)
    {
	// Internet Explorer
	try
	{
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		if(xmlHttp.overrideMimeType)
		{
			xmlHttp.sendback.overrideMimeType("text/xml");
		}
	}
	catch (e)

	{
		try
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e)
		{
			return false;
		}
	}
    }
        }
        if(xmlHttp)
{
	var URL = "process.php?id=" + this.firstChild.data
	xmlHttp.open("GET", URL);

	xmlHttp.onreadystatechange = function()
	{
		if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
		{
			alert("success")
		}
	}
	xmlHttp.send(null);
}
    }
}

window.onload = function()
{
   spanListener()
}

 

process.php

if(ereg("^[0-9]+$", $_GET['id']))
{
    // insert database connection information here
    mysql_query("UPDATE user SET active='1' WHERE id='{$_GET['id']}'");
}

[/code][/code]

Link to comment
Share on other sites

haku,

 

What one person calls overkill, another will call flexible.  Being able to pass parameters about which program you want AJAX to process, and which div to populate upon success or fail can be quite handy.

 

Scot L. Diddle, Richmond VA

Link to comment
Share on other sites

The guy didn't ask for that, he asked how he could update one column in one row in the database. You gave him half a site.

 

Don't get me wrong, its great that you helped the guy. It's just that it was way more than he was asking for.

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.