Posting a comment in PHP with Ajax - javascript

I know there are a few of these questions posted on here already but i am having trouble finding a solution to my problem. I am very bad with anything javascript/ajax and i am having difficulties trying to get my ajax code to work.
I am building a simple commenting system on a video page for my website. I have built the commenting system with php but now i want to get more advance and post the data to my comments.php file via ajax. I want the comments to display dynamically without refreshing the page. I've read a few tutorials but for some reason whenever i try work with js i get really confused. I think it's the syntax :S. I'll post my code below and if anyone can tell me where i am going wrong it will be a massive help!
videos.php
// comment box
if($user->isLoggedIn()){
//login to comment
} else { ?>
<div id="user-comment" class="comment-post">
<form id="comment-form" method="post">
<textarea id="comment_body" name="comment"> </textarea>
<input id="submit-btn" type="submit" name="comment_post" value="Post Comment" >
// csrf-token generator
<input type="hidden" id="auth-token" value="<?php echo token::generate(); ?>"></input>
</form>
</div>
//post comments
<div id="comments_post" class="comments-box">
<?php
$get_comments = // query the db here
if(!$get_comments->results()){ ?>
//no comments...
<?php
} else {
foreach ($get_comments->results() as $comment) { ?>
<div class="comment-header">
<?php echo $comment->username . ' | ' . $comment->added;
if ($user == $comment->user OR $user->hasPermission('admin')) { ?>
<i class="fa fa-trash-o onl-link-icon text-right"></i>
<?php
}
?>
</div>
<div class="comment-body">
<p><?php echo $comment->comment; ?></p>
</div>
<?php
}
}
?>
</div>
ajax request
<script type="text/javascript">
$(document).ready(function(){
//Post Comment
$("#submit-btn").on('.submit','click',function(){
var body = $('#comment_body');
$.ajax({
url: 'comments.php',
type: 'post',
async: false,
data:{
'comment_body' : body
},
success:function(){
$('#comment-box').toggleClass("comment-hide");
}
});
});
});
</script>
comments.php
if($_POST['auth_token'] === session::get('access_token')){
if(isset($_POST['comment_body'])) {
$validate = new validate();
// Validate Data from $_POST
$validation = $validate->check($_POST, array(
'comment_body' => array(
'name' => '<b>Comments</b>',
'required' => true,
'str_min' => 1,
'str_max' => 400,
'comment_filter' => true,
'sql_safe' => true
),
));
if($validation ->passed()){
$comment = escape($_POST['comment']);
try {
$user->create('video_comments', array(
'comment' => $comment,
'user_id' => $user->id,
'video_id' => $video,
'username' => $user->username,
'added' => date('Y-m-d H:i:s')
));
} catch(Exception $e) {
die($e->getMessage());
}
redirect::to($page);
} else {
session::flash('comment_error', 'Comment Failed');
redirect::to($page);
die();
}
} else { redirect::to(404); }
} else { redirect::to(404); }
UPDATE #1
the console error is showing me this:
GET (localhost/WEBSITES/myvideosite/css/homepage.css) - Failed to load resource: the server responded with a status of 404 (Not Found)
it points to my jquery <script src="js/jquery-1.11.3.min.js"></script> file which is defiantly there?

Sucess!
After a long day of researching and trying out different things I have finally got it to work!!
<script type="text/javascript">
$(document).ready(function(){
$("#submit-btn").click(function(){
var body = $('#comment_body').val();
var token = $('#auth-token').val();
if(body== null)
{
window.alert('Please enter a comment.');
}
else
{
$.ajax({
type: 'POST',
url: 'comment.php',
async: false,
data:{
'auth_token' : token,
'comment_body' : body
},
success: function(result){
//alert(result);
$('.comment-post').toggleClass("comment-hide");
$('.comment-sucess-hide').toggleClass("comment-sucess");
$('#comments_post').load(document.URL + ' #comments_post');
}
});
}
return false;
});
$('.del-com').click(function(){
var comid = $(this).attr('id');
$.ajax({
url: 'comment.php',
type: 'POST',
async: false,
data:{
'rmv' : comid
},
success:function(){
$('#comments_post').load(document.URL + ' #comments_post');
}
});
});
});
</script>
If anyone has some better suggestions please feel free to share as i am a real novice with js and really want to improve. Thanks to all that shared comments.

Related

Problems with Ajax-request via Laravel

I have a big problem with Ajax-request via Laravel. I can't understand why it is not Ajax. All resources here.
It is my Ajax-request.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var nickname = "<?php echo $name_user; ?>";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.subscribe').click(function() {
jQuery.ajax({
type: 'post',
url: "{{ route('postSubscribe', '<?php echo $name_user; ?>') }}", //Путь к обработчик
data: {'user_name': nickname},
response: 'text',
success: function(data) {
console.log(data['result']);
},
error: alert('Error');
})
})
</script>
It is my web-routes.
Route::group(['middleware' => 'auth'], function() {
Route::get('/', 'AccountController#redirectToAccountPage');
Route::get('/account', 'AccountController#showAccount')->name('account');
Route::get('/account/settings', 'AccountController#showSettings')->name('settings');
Route::post('/account/settings', 'AccountController#sendSetting');
Route::get('/account/subscribe', 'AccountController#showSubscriberForm')->name('subscriber');
Route::post('/account/subscribe', 'AccountController#findUser')->name('postFindUser');
Route::get('/account/load_image', 'AccountController#showLoadImage')->name('load_image');
Route::post('/account/load_image', 'Photos\LoadPhotoController#loadPhoto');
Route::post('/account/logout', 'AccountController#logout')->name('logout');
Route::post('/user/{user_name}/', 'AccountController#subscribe')->name('postSubscribe');
Route::get('/admin', 'AccountController#showAdminPanel');
});
It's my main request.
public function subscribe(Request $request, $name_user) {
if($request->ajax()) {
$query = 'SELECT id FROM subscriptions WHERE id_subscriber = ? AND id_subscribtion = ?';
$queryFindAnother = 'SELECT id From new_users WHERE nickname = ?';
$idAnotherUser = DB::select($queryFindAnother, [$name_user]);
if(!DB::select($query, [Auth::user()->id, $idAnotherUser[0]->id])) {
$query = 'INSERT INTO subscriptions (id_subscriber, id_subscribtion) VALUES (?, ?)';
dd('Я здесь');
//id_subscriber - тот, кто подписался.
//id_subscribtion - на кого подписан.
DB::insert($query, [Auth::user()->id, $idAnotherUser[0]->id]);
return response()->json([
'result' => '1', //всё прошло успешно, я подписан
]);
}
return back();
}
dd("It's not ajax");
return back();
}
As a result I got the message "It's not Ajax". Help me please!
I think the problem is in your form
Please update your form
<form>
{!! csrf_field() !!}
<button class="subscribe" name="user" type="button">Подписаться.</button>
</form>
Here, you don't need any action or method also does not need any form
because you passing the form data as ajax
and add the type of your button as button, by default its a submit type, so its submitting the form as normally.
Make sure you have imported the Request Facade on top

Not able to display message after submitting form using ajax

I am trying to submit the form using AJAX in CodeIgniter. Values of the form are getting saved in DB but the reply that has been set in the controller is not getting displayed in console.log or alert in AJAX code.
Code of form
<form class="form-signup" id="signup-form" method="post">
<input type="email" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
<button type="submit" class="btn btn-primary btn-lg btn-signup col-sm-offset-1" id="submit_form">SIGN UP</button>
</form>
Script code
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'json',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});
Controller code
public function register()
{
$data = array(
'email' => $this->input->post('email'),
'password'=>$this->input->post('password')
);
$email = $data['email'];
$password = $data['password'];
$this->db->where('email',$email);
$query = $this->db->get('student');
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
return $final;
}
}
Model code
public function register_user($data1)
{
$success=$insert_data = $this->db->insert('student', $data1);
if($success)
{
$result= "success ";
}
else
{
$result= "register unsuccessful";
return $result;
}
}
As shown in the code there are 3 messages
Email already exists
Success
Register unsuccessful
In AJAX, if I do console.log or alert, I want any 1 of the above 3 messages to get displayed according to the flow.
How to display the reply on front end?
You have to use echo instead of return for success.
Please change it as follows
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
echo $final;
}
and remove that 2 variables initialized together. That is unnecessary. This is fine.
$success = $this->db->insert('student', $data1);
Hope this can help you.
The ajax that you have used has datatype as json. So if you want data to be displayed on front end either encode the reply in json or you need to change or remove the json datatype from your ajax
Please change dataType:'json' to dataType: 'text'
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'text',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});

jQuery Ajax function does not work?

I'm developing a simple login form for my website. And to do that I thought to use ajax to connect with php to validate users. However to do that I cannot get output from ajax.
<script>
function submitForLogin()
{
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" }}).done(function(data){alert(data);});
}
</script>
When user clicks on login button it calls submitForLogin() function.
Above part of the code I've placed in my login.html file. To validate whether this works or not I simply replaced data values of email and password with hard coded values.
Note : example#abc.com and 123 both email and password stored in Wamp server database.
This is the PHP file :
<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection
$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
echo "userExist";
}
else
{
echo "fakeUser";
}
mysqli_close($con);
?>
Whenever I run php file only (with $userEmail and $userPass having previous hard coded values) php prints userExist output. But using ajax I cannot get that in an alert box.
Is there something I missing? I'm running the website in wamp server too.
UPDATE
When I check console errors it shows;
And when I click on login.html line 112, it shows;
And ideas guys? Also, none of the solutions provided so far gave me successful answer for the question.
There was a jquery error and now it's fixed. But syntax error exists.
Try this code working for me on my machine. Don't forgot to place Jquery File.
PHP (ajax.php) :
<html>
<head>
<script src="jquery.min.js"></script>
<script>
function submitForLogin()
{
alert("23");
var email = document.getElementById("txtUserName").value;
var password = document.getElementById("txtPassword").value;
$.ajax({
type: "POST",
url: "login1.php",
data: { email: email,password:password },
success : function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<input type="text" placeholder = "Enter user name" id="txtUserName"/>
<input type="password" placeholder = "Enter password" id="txtPassword"/><br>
<input type="button" onclick="submitForLogin();" value="Login"/>
</body>
</html>
Server Side (login1.php) :
<?php
var_dump($_POST);
?>
You need to include a function for when the request is successful, which includes the response.
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success:function(data){
alert(data)
};
});
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success: function (data) {
alert(data);
}
});
your data in AJAX call is in JSON format.
in your php script you should use json decode as below
$data = file_get_contents("php://input");
$data = json_decode($data,true);
$userEmail=$data['email'];
$userPass=$data['password'];
i hope this might help you. your login will work as u expect it
Change your php file like below :
<?php
$userEmail=$_POST['email'];
$userPass=$_POST['password'];
$servername ="localhost";
$username="root";
$password="";
$dbname="AS2014459";
//To create a connection
header('Content-type: application/json');
$con = mysqli_connect($servername,$username,$password,$dbname); //check connection
if(!$con){
die("Connection failed: ".mysqli_connect_error());
}
$sql="SELECT Email,Password FROM USERTABLE WHERE Email='".$userEmail."'";
$results=mysqli_query($con,$sql);
if(mysqli_num_rows($results)>0)
{
$res = "userExist";
$data = json_encode($res);
echo $data;
die();
}
else
{
$res = "fakeUser";
$data = json_encode($res);
echo $data;
die();
}
mysqli_close($con);
?>
And your script :
$.ajax({
type: "POST",
url: "php/login.php",
data: { email: "example#abc.com",password:"123" },
success:function(data){
alert(data);
};
});

"You did not select a file to upload. " get this error while uploading image using ajax

I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document

Login validation not working on HTML using JSON and PHP

I am making a login form on HTML using JSON and PHP but all of the if statements on success are not working but the beforeSend and error is working. Can you help me check my mistakes?
I dont know know what is wrong with the function on success. The alerts are not popping up. For example response.success == true is supposed to pop up ' You are successfully logged in... '
<script>
$(document).ready(function(){
$('#loginForm').on('submit',function(e){
var myForm = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'connections/login.php',
data : new FormData($(this)[0]),
cache: false,
contentType:false,
processData: false,
beforeSend: function(){
$("div#divLoading").show();
},
success: function(response){
$("div#divLoading").hide();
console.log(response);
if(response.success == true)
{
alert(' You are successfully logged in... ')
}
else if( response.success == false ){
alert('please enter a correct email & password');
}
else{
if(response.matric){
alert('email is wrong');
}
if(response.password){
alert('password is wrong');
}
}
},
error: function(data){
alert('error');
$("div#divLoading").hide();
}
});
return false;
});
});
</script>
Here is my PHP:
<?php
require_once('connect.php');
session_start();
header('Content-Type: application/json');
if (!empty($_POST['matric']))
{
$matric=$_POST['matric'];
$password=$_POST['password'];
$pass= $dbh->prepare("SELECT * FROM users WHERE matric=:matric AND password=:password");
$pass->bindParam(':matric', $matric);
$pass->bindParam(':password', $password);
$pass->execute();
if($pass->fetch(PDO::FETCH_NUM) > 0)
{
$_SESSION['matric']=$matric;
$response = array(
'success' => true,
'message' => 'Login successful');
}
else
{
$response = array(
'success' => false,
'message' => 'Login fail');
}
}
echo json_encode($response);
echo json_encode($_POST);
?>
You have
echo json_encode($response);
echo json_encode($_POST);
which is going to issue corrupted JSON. e.g. your output is going to be
{"success":true,"message":"Login successful"}Array
^^^^^^---corruption
Since your JSON is corrupted, it won't decode properly, and response WON'T be what you think it is.
Remove this line:
echo json_encode($_POST);

Categories