1

I am having a form in which two input's are defined username and password, but i want to send this input as a json object to server, here is my html form

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <form name="MY Form" action="Login" method="post">

        userid<input type="text" name="username" id="username"> <br>
        password<input type="password" name="password" id="password">
        <br> <input type="submit" name="button1" value="login"> 
    </form>
</body>
</html>

now how can i send this data as a json object, i have searched that i can use jquery or ajax but i am finding difficult to implement it, can anyone please tell me how can i send it as a json.

1
  • Use jQuery -> ajax or post or serialize method. It is based on your requirement which method should be used. Mar 20, 2014 at 6:05

4 Answers 4

3

You could send your data using .serialize() method.

$(function() {
  $('input[name="button1"]').click(function() {
    $.post(your_url, $(this).closest('form').serialize(), function(data) {
       console.log(data);
    });
  });
});

It is the same effect with using an object as data:

$(function() {
  $('input[name="button1"]').click(function() {
    var data = {
        username: $('#username').val(),
        password: $('#password').val(),
    };
    $.post(your_url, data, function(data) {
       console.log(data);
    });
  });
});
0
$( "form" ).submit(function( event ) {
  console.log( $( this ).serializeArray() );

  // do submit part here
});
0

As memory serves you can only send data back to the server via POST or GET using javascript. You would probably have to serialize the JSON before sending.

see https://stackoverflow.com/a/912247/1318677 for an example on how to serialize a JSON object.

Assuming you have JSON2 and Jquery included, The code may look like this

// create a listener on the submit event
$('form').on('submit', function (e) {
    e.preventDefault();

    // gets the data that will be submitted
    var data = $(this).serializeArray(),
    // the ajax url
        url = './request/url';

    $.ajax({
       url: url,
       type: 'POST',
       contentType:'application/json',
       data: JSON.stringify(data), //stringify
       dataType:'json',
       complete : function () {
        // do what you want here
       }
     });

    return false;
});

Be aware, untested script. Also make sure DOM exists before calling the script above. Which can be achieved by adding your scripts just before the </body> closing tag or use $(document).ready(/*script here*/);

0

use this one

add id button1

html

<form action="Login" method="post" name="MY Form">
        userid<input id="username" name="username" type="text" /><br />
        password<input id="password" name="password" type="password" /><br />
        <input id="button1" name="button1" type="submit" value="login" />
    </form>

javascript

$("#button1").click(function() {
    formData = {
        username: username,
        password: password
    }
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: "http://localhost/login.php",
        dataType: "json",
        data: formData,
        success: function(data) {
            console.log(data);
            //success handler
        },
        error: function(data) {
            //error handler
        }
    });
});

php

<?php

/*
 * Following code will get single product details
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// check for post data
if (isset($_POST["username"]) && isset($_POST["password"])) {
    $username = $_GET['username'];
    $password = $_GET['password'];

    // get a product from products table
    $result = mysql_query("SELECT *FROM users WHERE username = '$username' AND password  = '$password' ");

    if (!empty($result)) {
        // check for empty result
        if (mysql_num_rows($result) > 0) {

            $result = mysql_fetch_array($result);

            $user = array();
            $user["userId"] = $result["userId"];
            $user["name"] = $result["name"];
            // success
            $response["success"] = 1;

            // user node
            $response["user"] = array();

            array_push($response["user"], $user);

            // echoing JSON response
            echo json_encode($response);
        } else {
            // no product found
            $response["success"] = 0;
            $response["message"] = "No user found";

            // echo no users JSON
            echo json_encode($response);
        }
    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No user found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

Your Answer

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