i tried to Submit my form with ajax with out reloading the whole page, but the ajax is not working, here is the code i used
$("#sendingform").submit(function(){
var mess = $("#urmess").val();
var mid = "1";
alert (mid);
$.ajax({
url: 'ajax/send.php',
data: { mid: mid, mess: mess},
success: function (data){
alert(data);
}
});
return false;
});
the html is
<hr/>
<form action="#" id="sendingform" method="post">
<textarea id="urmess" class="conposer" name="messtxt"></textarea>
<input type="submit" class="sendbtn" name="go" class="send" value="Send"/>
</form>
Try this
$(function(){ /* Execute when the DOM is ready */
$(document).on("submit","#sendingform",function(e){
e.preventDefault(); /* Prevent the default action of the form */
var mess = $("#urmess").val(); /* Get the textarea value */
var mid = "1";
alert (mid); /* Alert 1 */
$.ajax({
url: 'ajax/send.php',
data: {
mid: mid,
mess: mess
}, /* Define AJAX data */
success: function (data){
alert(data); /* Alert return */
}
});
});
});
Here's The Code Hows Your PHP Code Must Look Like :
<?php
$a=json_decode($_POST["Jdata"]);
$con=mysql_connect("localhost","root","");
mysql_select_db("json",$con);
$t=$a->mess;
$u=$a->mid;
$x=mysql_query("insert into test(data1,data2) values('$t','$u')");
?>
And Here's HTML+JQuery Code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<form action="#" id="sendingform" method="post">
<textarea id="urmess" class="conposer" name="messtxt"></textarea>
<input type="submit" class="sendbtn" name="go" class="send" value="Send"/>
</form>
<script>
$("#sendingform").submit(function(){
var mess = $("#urmess").val();
var mid = "1";
alert (mid);
$.ajax({
type: "POST",
url: 'ajax/send.php',
dataType: "json",
data:{Jdata:JSON.stringify({'mid': mid,'mess': mess})},
success: function (data){
console.log(data);
}
});
return false;
});
</script>
</body>
</html>
Related
I have developed the website using jquery & PHP, I have created a page using HTML, / PHP so what I want is if I click on submit, item ajax should send value to PHP variable and then execute index.php and get that value to another page.
Please help me to resolve the issues.
So far, I have tried the following:
index.php
my Javascript Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = $("#number").val();
$.ajax ({
type: "POST",
url: "ajax.php",
data: { val : val },
dataType:'text',
success: function( result ) {
// window.location.href = 'ajax.php';
// alert(result);
}
});
});
});
</script>
my HTML Code
<form name="numbers" id="numbers">
<input type="text" name="number" id="number" >
<button type="button" id="btn">Submit</button>
</form>
ajax.php
<?php
session_start();
$_SESSION['val'] = $_POST['val'];
print_r($_SESSION);
?>
You can store the value in session and redirect the user to other page and get data from session at other pages.
<?php
session_start();
$_SESSION['data'] = $_GET['val'];
?>
Your HTML code must be like that
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<button type="button" id="btn">Submit</button>
</form>
For redirect to other page you can use like
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
window.location.href = 'url';
}
});
});
});
</script>
in this if you click button its refresh the page because you using input type="submit" on button , so just change it to input type="button"
<input type="button" id="btn" value="submit">
and if you want to keep input type="submit" as you already did then just add prevent default to jquery
$(document).ready(function(){
$("#btn").click(function(event) {
event.preventDefault();
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
}
});
});
});
you can use session
in ajax.php you have to add:
<?php
session_start();
echo $_GET['val'];
$_SESSION['val'] = $_GET['val'];
?>
and use variable $_SESSION['val'] to any page
how to clear form after submit the form and pass the data to php file without reloading page...the form data is pass the php file and it stored the data base.but i was unable to clear the form data after submit the form.if i reset the form using javascrip but data not pass the data base.if i pass the data to php the form is not clear.is there a way for me achive both target?thank you..
here my snipt code...
<iframe name="votar" style="display:none;"></iframe>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
Using AJAX you can do this.
$('#submitBtn').click(function () {
$.ajax({
url: 'confirm.php',
data: $('#sfm').serialize(),
type: "post",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
you can try this
in index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: 'ajax.php',
data: $('form').serialize(),
success: function (data) {
$('#name').val('');
alert('data');
//your return value in data
}
});
});
});
</script>
</head>
<body>
<form action="ajax.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" id="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
</body>
</html>
and in ajax.php
<?php
$name = $_GET['name'];
//do what you want to do using name
echo "what you need to return";
Have you thought about to use Ajax to handle the form submit?
Form submit with AJAX passing form data to PHP without page refresh
try making $_POST array empty after submitting and saving the form
$_POST='';
After getting success response you can clear form input
$('#sfm').submit(function () {
var form = $(this);
$.ajax({
url: 'phpfile.php',
data: form.serialize(),
type: "POST",
success: function (data) {
$('input[type="text"]').val('');
}
});
return false;
});
You can do like this, first get form inputs value and then reset
You can also able to reset after success response
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var that = $(this);
var params = that.serialize();
that.get(0).reset();
console.log(params);
$.ajax({
type: 'GET',
url: 'submit.php',
data: params,
success: function (data) {
console.log(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="confirm.php" id="sfm" method="POST" target="votar">
<input type="text" placeholder="Name" name="name" value="" required/>
<input type="submit" value="Submit My Project " />
</form>
SERVER SIDE
<?php
$name = $_GET['name'];
echo 'success';
exit();
?>
I have the following code that i wish to use to submit form without reloading the page, but it reloads the entire page and when checked in console the script.php page is also not getting executed.
Code on index.php page
<script>
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
code on script.php page
<?php
$name=$_POST['name'];
echo $name;
?>
Can anyone please tell how i can submit the form without reloading the page and also display the result from script.php page on index.php page
update your function. pass event object in function. and use event.preventDefault() to prevent default submit action.
$(".submit").click(function(e) {
e.preventDefault();
try this
<script>
$(function() {
$(".submit").click(function(event) {
event.preventDefault();
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function() {
$('#result').html(response);
}
});
return false;
});
});
OR
<input type="button" class="submit" />Submit
You need to send the data from the script.php page back to your index.php page. Swich out the little bit of ajax for this:
$.ajax({
type: "POST",
url: "script.php",
data: "datastring",
dataType: "json",
success: function(dataType){
$("#result").html(dataType);
}
});
In your script.php:
<?php
$name=$_POST['name'];
echo json_encode($name);
?>
Do not mix form submit and button click.
If you are a click event of button then use type="button" and if you are doing $("form").submit() then use type="submit".
Also check for
$(".submit").click(function(e) {
e.preventDefault();
and check your ajax post data , do
$.ajax({
type: "POST",
url: "script.php",
//changes made here
data: { name: $("#name").val()},
//changes made here. you have not written response
success: function(response) {
$('#result').html(response);
}
});
Instead of listening to the input's click event, you should listen to the form's submit.
<script>
$(function() {
$("#name-form").on('submit', function(e) {
e.preventDefault(); // prevent form submission
var name = $("#name").val();
var dataString = 'name=' + name;
console.log(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
success: function(response) {
$('#result').html(response);
}
});
});
});
</script>
<form id="name-form" method="post" name="form">
<input id="name" name="name" type="text" />
<input type="submit" value="Submit" class="submit" />
</form>
<div id="result"></div>
I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.
here is my form
<form >
<input type="text" id="name" >
<input type="submit" value="s" onclick="return chl()" >
</form>
here is my js
<script>
function chl(){
var name= document.getElementByID('name').value;
var dataString='name' + name;
$.ajax({
type:"post",
url:"hi.php",
data:dataString,
cache:false,
success: function(html){
alert ("success");
}
});
return false;
}
</script>
and here is my php
<?php
$name=$_POST ['name'];
echo "response".$name;
?>
The datastring should be formed like a querystring; you've missed the = between the key and the value:
var dataString = 'name=' + name;
That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:
<form method="hi.php">
<input type="text" id="name" />
<input type="submit" value="s" />
</form>
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "post",
url: this.action,
data: $(this).serialize(),
cache: false,
success: function(html){
alert(html); // = 'response: name = [VALUE]'
}
});
});
$name = $_POST['name'];
echo "response: name = ".$name;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--form method="hi.php"--> <!-- Remove this from your code and method is post or get you can't use hi.php as method -->
<input type="text" id="name" />
<input type="submit" id="click" value="s" /> <!-- Give id to your button -->
<!--/form-->
<script type="text/javascript" src="js/jquery.js"></script> <!-- You need to use jquery -->
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#click').on('click', function(event) {
event.preventDefault();
/* Act on the event */
var name=$('#name').val();
$.ajax({
url: 'hi.php',
type: 'POST',
data: {name: name}
})
.done(function(data) {
alert(data); // You can alert that data
console.log(data); //or you view this data on console Ctrl+shift+I
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
});
</script>
</body>
</html>
<!-- Your php page hi.php -->
<?php
echo $_POST['nmae'];
// or just say hi
echo 'hi';
?>
Form
<form name="test" id="test">
<input type="text" id="name" >
<input type="submit" value="s" >
</form>
Script
<script>
$("#test").submit(function(e){
e.preventDefault();
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{"name":name},
cache:false,
success: function(html){
alert (html);
}
});
return false;
}
</script>
You can also try with -
var dataString = $('form').serialize();
By this you can get rid of generating the datastring if you have a number of input fields.
change ajax function like and send data as shown below and your php and js function must be in different pages
function chl(){
var name= document.getElementByID('name').value;
$.ajax({
type:"post",
url:"hi.php",
data:{name:name},
success: function(html){
alert ("success");
}
});
return false;
}
<form method="POST" action="server.php">
<input type="text" name="name" id="myName" >
<input type="submit" value="s" onclick="chl(); return false;" >
</form>
<script>
function chl()
{
var nameElement = document.getElementById("myName");
//Creates formData object and sends it to PHP script
var formData = new FormData();
//name equals to input element name attribute value
formData.append(nameElement.name, nameElement.value);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "server.php");
xmlHttp.send(formData);
}
</script>
<?php
$name = $_POST['name'];
echo $name;
?>
I'm trying to create a simple login with PHP and MySQL and I'm using the AJAX() jquery function to load the PHP script.
All that I want to do is to load a new web page (for example java2s.com) when the script finds the user in my database.
Problem is that the script won't work at all.
This is the HTML with the Jquery:
EDIT: This is the fixed code thanks to all those who commented, which sadly still doesn't work.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
)
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="submit" id="loginForm" class="button positive">
</body>
</html>
The PHP script is very simple:
<?php
$data = file_get_contents('php://input');
$result = json_decode($data);
$con=mysqli_connect("localhost","****","*****","*******");
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."';";
$exists = mysqli_query($con,$str);
if (mysqli_num_rows($exists) ==1)
{
$arr = array('result'=>"login successful");
$ris=json_encode($arr);
echo $ris;
}
else
{
$arr= array('result'=>"login error");
$ris=json_encode($arr);
echo $ris;
}
mysqli_close($con)
?>
When I load the page and press the submit button nothing will happen.
Anyone can help?
Thank you very much in advance
try something like this
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: jsonlogin,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
})
EDITED CODE
you have not implemented DOM ready method correctly
$(document).ready(function(){
// code goes here
});
Maybe because all the php is commented out?
Also in your success function should look like this:
success: function(response){
dosomethingwithrespones(response);
}
The data in the $.ajax denotes what you send.
why are you using function ajaxJson()... try to remove it and if you really want to use it then modify your button code like this and remove $("#loginForm").click(function() { } from jquery...
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
and change <script type="text/javascript"> instead of <script language="javascript">.. this identifier is not standard, this attribute has been deprecated(outdated by newer constructs) in favor of type.
first way
function ajaxJson()
{
//your code goes here without triggering **click** event..
}
<input type="submit" id="loginForm" class="button positive" onclick="ajaxJson()">
second way
$("#loginForm").click(function()
{
//your code goes here...
}
<input type="submit" id="loginForm" class="button positive">
keep everything outside $(document).ready function...
hope it may help you
You have missed ending { and } for ready function.try below code.
<!DOCTYPE HTML>
<html>
<head>
<title> Login </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="JavaScript">
function change()
{
document.location.href="http://www.java2s.com";
}
$(document).ready(function () {
$("#loginForm").click(function() {
alert("hi");
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: sendstr,
success:function(response){
if (response['result']=="login successful")
{
change();
}
}
});
});
});
</script>
</head>
<body>
<h1> INSERT USERNAME AND PASSWORD</h1>
<input type="text" id="username" name="username"> USERNAME <br>
<input type="password" id="password" name="password"> PASSWORD <br>
<input type="button" id="loginForm" class="button positive">
</body>
</html>
try this query in login.php,
$str="SELECT ID FROM users WHERE username='".$result->username."' AND password='".$result->password."' ";
Jquery:
$(document).ready(function(){
$("#loginForm").click(function() {
var jsonlogin=new Object();
jsonlogin.username=$('#username').val();
jsonlogin.password=$('#password').val();
var sendstr = JSON.stringify(jsonlogin);
$.ajax({
type: 'POST',
url: 'login.php',
async: false,
dataType: 'json',
data: sendstr,
success:function(response){
if (response.result=="login successful")
{
change();
}else{
alert(response.result);
return false;
}
}
});
});
});