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.
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);
});
});
});
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
// do submit part here
});
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*/);
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);
}
?>
Related
I am making a function to change the user's email, this call will be made via AJAX on a button click. The form code is below, which is in a file named profile.php:
<form id="changeEmail" method="post">
<div class="form-group">
<label for="changeEmail">Update Email Address</label>
<input type="email" id="email" class="form-control" name="email" value="<?php echo $currentEmail; ?>">
</div>
<button type="submit" id="updateEmail" class="btn btn-success">Update</button>
</form>
I have also created a script in this file as well to perform some basic functionality such as call the ajax function and hide the button until changed. See it below:
<script>
$("#updateEmail").hide();
var id = "<?php echo $id ?>";
$("#email").change(function(){
$("#updateEmail").slideDown();
});
var email = $("#email").val();
console.log("id: " + id);
updateEmail("<?php echo $id; ?>", email);
</script>
The AJAX function which I created is saved in a file named profileAjax.js, this file will hold all my profile ajax functions passing through the users id and new email address.
function updateEmail(id, email) {
$("#updateEmail").click(function(e) {
e.preventDefault(); // Prevent HREF
$("#spinner").show(); // Show spinner
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/updateEmail.php",
dataType: "HTML",
type: "POST",
data: {id: id, email: email},
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
console.log("This worked");
}
});
}, 1500); // Delay this for 1.5secs
});
}
The final file which is called by the AJAX function is updateEmail.php which can be seen below:
include '../../functions/linkAll.inc.php';
$id = filter_input(INPUT_POST, "id");
$email = filter_input(INPUT_POST, "email");
updateEmail($id, $email);
The function which is called updateEmail is saved in an external file and works fully on its own.
function updateEmail($id, $email) {
$connect = db();
$stmt = $connect->prepare("UPDATE `Account` SET `email` = ? WHERE `id` = ?");
$stmt->bind_param("si", $email, $id);
if ($stmt->execute()) {
successMessage("Successfully updated your email address.");
} else {
errorMessage($stmt->error());
}
$stmt->close();
}
However, when the update button is shown and clicked upon, it runs and gives a success message with nothing being updated in the database table itself.
The jQuery AJAX success function is called when the requested source returns HTTP status 200. You should return something from PHP to the AJAX call to tell it if the database action was successfull.
Example PHP (called by AJAX request):
if($stmt->execute()) {
echo "1";
}
else {
echo "0";
}
Example JavaScript:
success: function(data) {
if(data == "1") {
//code if database action is successfull
}
else {
//code if database action failed
}
}
I have made a simple form through which i can search the keywords and find the related output from database dynamically. The code works perfect without AJAX . But now i have applied some AJAX code to get the response on same page within a div named coupon. I am unable to get the response. I don't know where am i doing wrong. Any suggestions please. Here is the complete code.
form
<form action="" id="search_form" method="POST">
<p><input name="query" autocomplete="off" id="list_search" type="search" required class="list_search" /></p>
<p align="center"><input type="submit" id="click" name="click" class="but" value=" search" /></p>
</form>
<div class="coupons"></div>
AJAX
$("document").ready(function(){
// $(".but").click(function(event){ // here
$("#search_form").submit(function (event) {
{
event.preventDefault();
var myData={ query: $( 'input[name="query"]' ).val() };
$.ajax({
url: 'result.php',
data: myData,
type: 'post',
dataType: "html",
success: function(result){
//console.log(result);
$('.coupons').html(result);
},
error: function() {
alert('Not OKay');
}
});
});
});
result.php
$keyword = mysqli_real_escape_string($con,$_REQUEST['query']); // always escape
$keys = explode(" ", $keyword);
$sql="SELECT c.* , sc.* , sm.* ,ca.* from store_category sc INNER JOIN store_manufacture sm ON sm.sm_id=sc.store_id INNER JOIN categories ca ON ca.cat_id=sc.cat_id INNER JOIN coupons c on c.c_sc_id=sc.sc_id WHERE c.c_name LIKE '%$keyword%' OR sm.sm_brand_name LIKE '%$keyword%' OR ca.cat_name LIKE '%$keyword%' OR c.c_description LIKE '%$keyword%'";
foreach ($keys as $k) {
$sql.="OR c.c_name LIKE '%$k%' OR sm.sm_brand_name LIKE '%$k%' OR ca.cat_name LIKE '%$k%' OR c.c_description LIKE '%$k%'";
}
$result = mysqli_query($con, $sql);
$count=mysqli_num_rows($result);
if($count!=0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$res=$row['c_name'].$row['c_description'];
echo json_encode($res);
}
}
else
{
echo "no result";
}
Do not use a click event and a button does not have a submit event - use the form's submit event instead
$("#search_form").on("submit",function(e) {
e.preventDefault();
$.post("result.php?query="+encodeURIComponent($("#list_search").val()),function(data) {
$('.coupons').html(data); // you likely need to render the JSON instead here or send HTML from server
});
});
You should try with:
var myData={ query: $( 'input[name="query"]' ).val() };
So you can get back a query field on the server.
The Problem is your ajax request does have your value as key in $_REQUEST. There might be some way to handle this but it is not very intuitive.
And right you should register the submit handler on your form not your button.
$("#search_form").submit(function(event){ ... }
I am a wordpress user and try to update the database using jquery.ajax. My code updates the database but the success function doesn't return anything to html div tag. Here are some portions of my code:
PHP Code:
$connect = mysqli_connect(HOST, USER, PASS, NAME);
if(mysqli_connect_errno()){
$msg = "Connection With Database is not Successful. Error: ".mysqli_error();
echo $msg;
die();
}
$nam = $_POST['name'];
$eml = $_POST['email'];
$entry = "INSERT INTO `table` (name, email,) VALUES ('$nam', '$eml')";
if(!mysqli_query($connect, $entry)){
$msg = "Error while submitting Your Data. Error: ".mysqli_error();
echo $msg;
die();
}
$msg = "Your data submitted successfully";
echo $msg;
mysqli_close($connect);
?>
HTML Code:
<form method="POST" id="data_form">
<input type="text" name="name" id="name" placeholder="Full Name" />
<br>
<input type="email" name="email" id="email" placeholder="Email Address" required />
<br>
<button type="submit" id="submit">Submit</button>
</form>
<div id="output"></div>
jQuery Code:
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false,
success: function(result){
$("#output").html(result);
}
});
});
});
I also used 'done' instead of 'success' but didn't work.
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false
}).done(function(result){
$("#output").html(result);
});
});
});
Actually I am trying to print the $msg variable from the php file to the 'output' div tag.
Any help would be greatly appreciated.
This is the ajax function
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {suburb_id: $('#suburb_id').val()},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
this is the php file need to receive data, it worked perfect.
<?php
//Check the form if submit by post
if (isset($_POST["searchBtn"])) {
$strInputSuburb = "";
$strInputSuburb = $_POST["suburb_id"];
//Check if the input box is empty or not
//if BOTH "Suburb" AND "Street" is empty, it will display the error message.
if(!empty($strInputSuburb))
{
//Connect to database server and table
include("connection.php");
#mysqli_select_db($conn, "db")
or die ("Database not available");
$querySql1 = "select * from Infringement
where suburb like '%".mysqli_real_escape_string($conn, $strInputSuburb)."%' and Street1 like '%".mysqli_real_escape_string($conn, $strInputStreet)."%'
order by Suburb, Fines DESC";
$result1 = mysqli_query($conn, $querySql1)
or die ("No information return...");
$count = mysqli_num_rows($result1);
$i=1;
if(!$count==0){
//do stuff, like echo
}
else {
//do stuff
}
//Release the SQL clause
mysqli_free_result($result1);
//Close the connection to database
mysqli_close($conn);
}
else {
//do stuff
}
}
?>
i want load to this div
<div id="tableContent"></div>
the css style is
#tableContent {
width:100%;
height:400px;
}
The input box is below
<input type="textbox" class="form-control" name="suburb" placeholder="Suburb" id="suburb_id" >
<input type="submit"class="btn" name="searchBtn" id='submit' value="Search" />
I used php to get data from form before. after using Ajax, I deleted "form" tag.
Thank you so much.
You're not sending the searchBtn parameter, which the PHP script is checking for. Add it to the data: option.
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {
suburb_id: $('#suburb_id').val(),
searchBtn: 'Search'
},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
Or remove that check from the PHP script, and test if (isset($_POST['suburb_id'])) instead.
as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem