Please help me how to submit form (comments) without page refresh for
HTML markup:
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="submit" id="comq"name="compost" class="butn2">post comment</button>
</form>
PHP code (pnf.php):
if(isset($_POST["compost"]))
{
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
jQuery and Ajax:
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
I have tried many times and don't know what mistake I made, Ajax and jQuery are not working, please anyone help - thanks in advance
You have made couple of mistakes.
First:: You should put button type="button" in your HTML form code
Second:: You have made a syntax error. $("#comment").vol(); should be replaced with $("#comment").val(); in your jQuery AJAX
As you mentioned that you have to send request without refreshing page I modified your JS-code with preventing default submitting form:
$(document).ready(function () {
$("#commentf").submit(function (e) {
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
type: "POST",
url: "pnf.php",
data: {
"done": 1,
"comments": comment
},
success: function (data) {
}
})
});
});
Javascript
$('form').on('submit', function(event){
event.preventDefault();
event.stopPropagination();
var dataSet = {
comment: $('#comment').val();
}
$.ajax({
url: "link.to.your.api/action=compost",
data: dataSet,
method: 'post',
success: function(data){
console.log('request in success');
console.log(data);
},
error: function(jqXHR) {
console.error('request in error');
console.log(jqXHR.responseText');
}
});
});
PHP
$action = filter_input(INPUT_GET, 'action');
swicht($action){
case 'compost':
$comment = filter_input(INPUT_POST, 'comment');
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if(!$stmt)
{
http_response_code(400);
echo 'internal error';
}
echo 'your data will be saved';
break;
default:
http_response_code(404);
echo 'unknown action';
}
you have to prevent the submit on the form (look in javascript).
after that you send the request to the server and wait for success or error.
in php try to do it with a switch case. and try to not touch super globals directly, use filter_input function.
hope this helps
Modified JQuery Code...
$( document ).ready(function() {
console.log( "ready!" );
$("#comq").click(function() {
var comment=$("#comment").val();
console.log('comment : '+comment);
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
HTML Code
<form id="commentf" method="post">
<textarea class="textinput" id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<input type="button" id="comq" name="compost" class="butn2" value="Post Comment">
</form> </div>
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="button" id="comq"name="compost" class="butn2">post comment</button>
</form>
script
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
PHP code (pnf.php):
comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
if you are using jquery make sure to include jquery libraries before your script file.
latest jquery cdn minified version
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
example
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="yourjsfile.js" type="text/javascript"></script>
Related
I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}
I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};
This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I'm trying to build a small CMS system, I want to use AJAX and jQuery to do so.
If I do not use AJAX the code works, I have no idea why the data is not being passed properly. AJAX success returns "Success"
Any help is appreciated.
Here is my Javascript:
$(document).ready(function(){
var aboutContent = $('#aboutContent').attr('value');
$('#aboutUpdate').submit(function() {
$.ajax({
type: "POST",
url: "scripts/update.php",
data: "aboutUpdate="+aboutContent,
beforeSend: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...'); },
success: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(500).fadeOut(250); },
error: function(){ $('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(500).fadeOut(250); }
});
return false;
});
});
Here is my HTML:
<?
$query = "SELECT * FROM pageContent WHERE page = 'about'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
?>
<div class="pageContent">
<h2>About</h2>
<form id="aboutUpdate" method="post">
<textarea class="editor" id="aboutContent" cols="50" rows="20"><? echo $rows['content']; ?></textarea>
<input type="submit" value="Save Now"><span class="updateStatus" id="aboutStatus"></span>
</form>
</div>
<?
}
?>
Here is the PHP (scripts/update.php):
$aboutContent = mysql_real_escape_string($_POST['aboutUpdate']);
if(isset($_POST['aboutUpdate'])){
$query="UPDATE pageContent SET content='$aboutContent' WHERE page='about'";
$result=mysql_query($query)or die(mysql_error());
if($result){
echo "Success";
}
else{
echo "Update Error";
}
}
else{
header("location:http://google.com");
}
Fixed the issue. Here is how:
First on the TEXTAREA I need to specify the attribute
name="aboutUpdate"
so the PHP isset can pull the data.
Second, I noticed a variable was 'undefined' when submitting.
var aboutContent = $('#aboutContent').attr('value');
Here is the working Javascript:
$('#aboutUpdate').submit(function() {
$.ajax({
type: "POST",
url: "scripts/update.php",
data: { aboutUpdate: $('#aboutContent').attr('value') },
beforeSend: function(){
$('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...');
},
success: function(){
$('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(2500).fadeOut(250);
},
error: function(){
$('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(2500).fadeOut(250);
}
});
return false;
});
HTML:
<?
$query = "SELECT * FROM pageContent WHERE page = 'about'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
?>
<div class="pageContent">
<h2>About</h2>
<form id="aboutUpdate" method="post">
<textarea class="editor" id="aboutContent" name="aboutUpdate" cols="50" rows="20"><? echo $rows['content']; ?></textarea>
<input type="submit" value="Save Now"><span class="updateStatus" id="aboutStatus"></span>
</form>
</div>
<?
}
?>
PHP update.php:
$aboutContent = mysql_real_escape_string($_POST['aboutUpdate']);
if(isset($_POST['aboutUpdate'])){
$query="UPDATE pageContent SET content='".$aboutContent."' WHERE page='about'";
$result=mysql_query($query)or die(mysql_error());
if($result){
echo "Success";
}
else{
echo "Update Error";
}
}
Try your Ajax function like this:
$.ajax({
type: "POST",
url: "scripts/update.php",
data: { aboutUpdate: aboutContent },
beforeSend: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...'); },
success: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(500).fadeOut(250); },
error: function(){ $('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(500).fadeOut(250); }
});
Notice the change in the POST data line.
Absolutely sure, that with this data: "aboutUpdate="+aboutContent you are sending something totaly wrong.
It should be data: {aboutUpdate: aboutContent}
Plus I'm not sure, that textarea actually has attribute value. Try
$('#aboutContent').val()
or
$('#aboutContent').text()