0

I want to send user typed string via AJAX POST request and add to database:

Új gyártó: <input type="text" id="new_mfg" size="20">
<button id="add_mfg">Hozzáadás</button>
<script>
    $("#add_mfg").click(function(e){
        e.preventDefault()
        var new_mfg = $('#new_mfg').val();
        //$(this).text(new_mfg);                    
        request = new XMLHttpRequest();
        request.open("POST","/phps/add_mfg.php",true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        request.send('$new_mfg');
    });
</script>

Here is the add_mfg.php script:

require_once('login.php');

$new_mfg = $_POST['new_mfg'];
$new_mfg = stripslashes($new_mfg);

$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if(!$db_server) die("Unable to connect to MYSQL:" . mysql_error());

mysql_select_db($db_database)
    or die("Unable to select database:" . mysql_error());
$query = "INSERT INTO mfg(ID, mfg_name) VALUES(NULL, '$new_mfg')";
$result = mysql_query($query);

mysql_close($db_server);

The code doesn't work and I don't know what the problem is.

4
  • why don´t you use JQuery ajax method? api.jquery.com/jQuery.ajax Commented Aug 26, 2013 at 11:13
  • Is the request sending to add_mfg.php.Do you have any error in the console? Commented Aug 26, 2013 at 11:13
  • As a matter of fact, you cannot send data to mysql databse using AJAX post request. You can send it to PHP script only Commented Aug 26, 2013 at 11:23
  • Nope, I dont have any error log. I'll try to change to jquery ajax method, but does it matter for this case? Commented Aug 26, 2013 at 12:14

2 Answers 2

3

You need to wrap your click event handler into $(document).ready(function(){ });

$(document).ready(function(){  
$("#add_mfg").click(function(e){

});
});
Sign up to request clarification or add additional context in comments.

4 Comments

or the shortcut $(function(){});
@user874774 Yes...But i think OP is newbie so its easier for him to google it.
even you need to replace new XMLHttpRequest(); request with $.ajax({});
I think there is no problem with the jquery event. My first tough was the same, but I tried to print out the readed new_mfg variable:
0

Use this short version:

$(function() {
  $("#add_mfg").click(function(e){
      // ...
  });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.