jQuery Ajax data to same PHP page not working as INTENDED? - javascript

I have 22.php that both form and PHP script reside.
Problems;
1) when I submit, result shows below. But duplicates the form.
2) Further entering in the top (above) form, changes the result accordingly.
3) When I enter in the bottom form, then also the result changes accordingly and disappear the bottom from.
What I have tried so far as solutions;
1) removed totally - url: '',
2) replaced to the same page - url: '22.php',
3) replaced to this - var yourData = $(this).serialize();
4) Placed the PHP script just soon after body tag
None of above solve! Please help!
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>

Just place PHP code top and put exit();. Here is your full code:
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
exit;
}
?>
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>

Related

jQuery PHP Post

I got a problem maybe is simple but dont know how to load jquery_post.php when I send the data for jquery_send.php I resume I send information from jquery_send.php to jquery_post.php and I want that after send the page jquery_post.php load with the data
This is what I have in jquery_send.php:
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("jquery_post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
});
}
});
});
</script>
</head>
<body>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
and in jquery_post.php I have this:
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
?>
It works just fine, but you have a syntax error in you jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
} // you missed this
?>
it was returning Parse error: syntax error, unexpected end of file
Please try, this may help
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
window.location.href = 'post.php';
});
}
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
And in jquery_post.php I have made some changes When you post data to jquery_post.php it will create a session named "user" you can retrieve name any time from the session as I did.
<?php
session_start();
if(isset($_POST["name"]))
{
$_SESSION['user'] = $_POST["name"];
$name = $_POST["name"];
$email = $_POST["email"];
}
echo "Welcome ". $_SESSION['user'] ."!";
?>

populate data from database using php ajax val()

i got something weird in my code. honestly, i got this from someone and i try to adapt it for my needs. So the problem is when i click fetch button, the data is not display. can any body here tell me what is wrong with the code?
Any related answer will be appreciated. Thanks in advance.
and here are my code
<script type="text/javascript">
$(document).ready(function() {
function myrequest(e) {
var name = $('.username').val();
$.ajax({
method: "GET",
url: "http://localhost/spdb/debug/autofill.php", /* online, change this to your real url */
data: {
username: name
},
success: function( responseObject ) {
alert('success');
$('#posts').val(responseObject.level);
$('#joindate').val(responseObject.last_login);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
<form method="POST" action="?act=proc">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</fieldset>
</form>
</body>
</html>
and this is the PHP code :
$return = mysqli_query($konek, "SELECT * FROM tb_auth WHERE username ='admin' LIMIT 1");
$rows = mysqli_fetch_array($return);
$formattedData = json_encode($rows);
print $formattedData;`
here are the result from PHP Code :
{
"0":"1",
"id_auth":"1",
"1":"TRC-US001",
"auth_code":"TRC-US001",
"2":"admin",
"username":"admin",
"3":"5f4dcc3b5aa765d61d8327deb882cf99",
"password":"5f4dcc3b5aa765d61d8327deb882cf99",
"4":"1",
"level":"1",
"5":"2018-07-05 13:55:19.200878",
"last_login":"2018-07-05 13:55:19.200878",
"6":"1",
"status":"1"
}
this is the picture :
result
Hope this can help you
first we need to do some modification on html, and php code :
<!-- doctype is mandatory -->
<!DOCTYPE html>
<!-- language en -->
<html lang="en">
<head>
<!-- title also is mandatory -->
<title>tilte of your project</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet" />
</head>
<body>
<form method="POST" action="?act=proc">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">
<p><input type="submit" value="Submit" name="submitBtn"></p>
</fieldset>
</form>
<!-- put all your javascript before the end of the body -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
function myrequest(e) {
// use $('#username') to select by id instead of $('.username') used to select by class
var name = $('#username').val();
$.ajax({
method: "GET",
url: "http://localhost/spdb/debug/autofill.php", /* online, change this to your real url */
data: {
username: name
},
dataType: 'json', /* this is not mandatory */
success: function( responseObject ) {
console.log('success');
$('#posts').val(responseObject.level);
$('#joindate').val(responseObject.last_login);
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
</body>
</html>
php code :
// this line is very important, by using this line
// the browser can recognize that the data sent from
// the server as a json object.
header("Content-type: application/json");
$formattedData = [];
if (isset($_GET['username'])) {
$username = trim($_GET['username']);
// to be sure that the username is not empty
if(empty($username)) {
print json_encode($formattedData);
exit;
}
$konek = mysqli_connect($sql_db_host, $sql_db_user, $sql_db_pass, $sql_db_name, 3306);
$return = mysqli_query($konek, "SELECT * FROM tb_auth WHERE username = '" . $username . "' LIMIT 1");
// use mysqli_fetch_assoc instead of mysqli_fetch_array
// $rows = mysqli_fetch_array($return);
$rows = mysqli_fetch_assoc($return);
$formattedData = json_encode($rows);
// very important every connection created need to be closed
mysqli_close($konek);
}
print $formattedData;
In your html code, there is an input with an id username. In Javascript, search for this line of code var name = $('.username').val();. Change . to #. It should be var name = $('#username').val();.
.username is for any tag that have a class username.
#username will search for a tag that have an id username.
try to parse responseObject to json using
responseObject=JSON.parse(responseObject);
in you success function

Ajax submit doesn't work (can't read $_POST in php)

I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php
$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])
test.php
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
}
?>
<html>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>
test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = "textbox=" + inputText;
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
There're more of problems here
In test.php
how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad
Scripts should be on the <head></head> or before </body>
while you using just button click why you're using <form>
your code should be something like that
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];
return false;
}
?>
<html>
<head>
</head>
<body>
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
<script type="text/javascript" src="test2.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</body>
</div>
</html>
On test2.js
function hit() {
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
}
Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs
If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use
$(document).ready(function(){
$('form').on('submit',function(e){
e.preventDefault(); // to prevent form reload
var inputText = $("#input").val();
var inputTextString = {textbox : inputText}; // use this
$.ajax({
type: 'post',
url: 'test.php',
data: inputTextString,
success: function () {
alert('form was submitted');
}
});
});
});
you never test if you see the reponse from echo - hence you don't alert the response from php at all.
To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:
....
success: function (response) {
alert(response);
console.log(response);
},
....
Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.
Also follow #Mohammed-Yousef's instructions for the other issues!!
you will get the desired results in the response.
function hit() {
var inputText = $("#input").val();
$.ajax({
type: 'post',
url: 'test.php',
data: {textbox : inputText},
success: function (res) {
alert(res);
}
});
}
And you need to change in your test.php file.
<?php
echo "test";
if($_POST)
{
echo $_POST['textbox'];exit;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="test2.js"> </script>
</head>
<body>
<form action="index.php" method="post" align="center" id="form" name="form">
<input type="text" class="form-control" id="input" name="input" oninput="check();">
<input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
</form>
</body>
</div>
</html>

Data is not inserting into database by jQuery and ajax method

I have to insert data through jQuery and ajax method. But data is not inserting in database. Pleas help me is this method is wrong?
Here is my code,
form.html
<!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- <script src="jquery-3.1.0.js" type="text/javascript"></script>-->
<script type="text/javascript">
function submitData()
{
var name = document.getElementById('name');
var age = document.getElementById('age');
var contact = document.getElementById('contact')
$.ajax({
type: 'POST',
url: 'data_ins.php',
data:{
uname:name,
uage:age,
ucontact:contact
},
success: function(response){
$('#success_para').html("Data inserted");
}
});
return false;
}
</script>
</head>
<body>
<form method="POST" onsubmit="return submitData();">
name : <input type="text" name="name" id="name"> <br>
age : <input type="text" name="age" id="age"> <br>
contact : <input type="text" name="contact" id="contact"> <br>
<input type="submit" name="submit" >
</form>
<p id="success_para"></p>
</body> </html>
and, data_ins.php
<?php
$conn = mysqli_connect("localhost","root","","test_db");
$name = $_POST['uname']; $age = $_POST['uage']; $contact = $_POST['ucontact'];
if(!$conn) {
echo"<script>alert('Database Connection Failed or invalid connection');</script>"; }
else {
$sql = "insert into records (name, age, contact) values ('$name', '$age', '$contact')"; mysqli_query($conn, $sql);
mysqli_error($conn); }
?>
Please let me know what's wrong in my code. Thanks, in advance.
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
Your "submit" button causes page reloading, so you'll not be able to see the result of a query in your onSuccess.
<input type="button" name="submit" onclick="submitData();" >
Have you checked your response? You can also view it in browser's inspector.
success: function(response){
$('#success_para').html(response);
}

How to fetch data from sql databse when it changes and updatde to div without reloading page

I'm making a simple comment and reply to comment page. I've some code that can post comment and display with ajax, but when I open same page in two browser it works in one browser and in second browser's div it doesn't update comment. My problem is I want if I post from one browser I want another browser also update div.
My index.php file is like below:
<?php
include('config.php');
$to = 1;
$from = 1;
$pak = 1;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery.min.js"></script>
<script src="process.js"></script>
</head>
<body>
<div id="responds"></div>
<form action="process.php" method="post" name="content_txt" id="contentd">
<input name="from" type="hidden" value="<?php echo $from; ?>" id="from">
<input name="to" type="hidden" value="<?php echo $to; ?>" id="to">
<input name="pak" type="hidden" value="<?php echo $pak; ?>" id="pak">
<textarea id="john" placeholder="whats on your mind ?" name="content"></textarea><br>
<div id="button" style="width:100%;height:33px;font-family:tahoma;">
<div id="update_button">
<input type="submit" value="POST" style="padding:5px;" class="uupdate"/>
</div>
</div>
</form>
<img src="loading.gif" id="LoadingImage" style="display:none" />
</body>
</html>
and process.js file is below
$(document).ready(function() {
//##### send add record Ajax request to process.php #########
$(".uupdate").click(function (e) {
e.preventDefault();
if($("#john").val()==='')
{
alert("Please enter some text!");
return false;
}
$(".uupdate").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
var to = document.getElementById("to").value;
var from = document.getElementById("from").value;
var pak = document.getElementById("pak").value;
var content = document.getElementById("john").value;
var myData = 'to=' + to + '&from=' + from + '&pak=' + pak + '&content=' + content;
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "process.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
$("#john").val(''); //empty text field on successful
$(".uupdate").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$(".uupdate").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
});
and process.php file is
<?php
include('config.php');
if(isset($_POST["content"]) && strlen($_POST["content"])>0)
{
$to = $_POST['to'];
$from = $_POST['from'];
$pak = $_POST['pak'];
$content = htmlspecialchars($_POST['content']);
$time=time();
$john = $mysqli->query("INSERT INTO status(eto, content, efrom, pak, created)VALUES('$to', '$content', '$from', '$pak', '$time')");
if($john) {
$my_id = $mysqli->insert_id;
echo '<div id="item_'.$my_id.'">';
echo '<form class="rep_wrapper" method="post" action="reply.php"><input type="text" class="rep_box" id="rep-'.$my_id.'">';
echo '</form>';
echo $content;
echo '</div>';
$mysqli->close(); //close db connection
}else{
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
?>
this works fine in single browser but doesn't update
<div id="responds"></div> on second browser.
but when I added following code on index.php
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#responds').load('check.php').fadeIn("slow");
}, 1000);
</script>
this code works on both browser but
it doesn't let me type reply on
<input type="text" class="rep_box" id="rep-'.$my_id.'">
because that js reloads my div every second.
How I can fix this problem?
Anyone please answer.

Categories

Resources