views:

325

answers:

1

Hello. Does anyone know how I can get the value of an input box, without having a form? I want a submit button, but instead of submitting a form, I want it to change data in a MySQL database. Something like this maybe?

$img1="WHAT DO I PUT HERE?"
$idx=1  
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";  
$result=mysql_query($sql); 

Could I use that code on a "onclick" event? The input box's name and id is "img1".

Thanks for the help!

+4  A: 

If you don't want to submit a form, the only two other ways of accomplishing this are to click a link with the data as query parameters in the url, or use AJAX to send the data to the server in the background.

update:

Javascript, as usual. You'd put a link or button somewhere on the page with "Send to Server" or whatever for the text. The script would pull your information from the input fields, and then send it on to the server via an AJAX call. Something along these lines (note that I'm using Mootools for all this, as it makes life much easier than having to do the remote calls yourself):

 function clickHandler() {
     var img1 = $$("input[name='img1']")[0].value;

     var r = new Request.JSON({
         'url: 'http://yourserver.example.com/script.php',
         'method': 'post',
         'onComplete': function(success) { alert('AJAX call status: ' + (success ? 'succeeded': 'failed!'); },
         'onFailure': function() { alert('Could not contact server'); },
         'data': 'img1=' + img1
     }).send();
}

and on the server you'd have something like:

<?php

$img1 = mysql_real_escape_string($_POST['img1']);
$idx=1;
$sql="INSERT INTO games SET img1='$img1' WHERE id=$idx";  
$result=mysql_query($sql);

echo (($result !== FALSE) ? 1 : 0);

You'd probably want something more complicated than this, but this is the basis of an AJAX application. Some client-side javascript that makes requests, and a script on the server that handles them and returns any data/errors as needed.

Marc B
How would I get the data from the input boxes to be sent in the URL?
Joey Morani
You need to use JavaScript, as it can access the living DOM, and hence any changes to it (like those in values of fields).
dclowd9901