refresh post user without refresh page ajax not working - javascript

i don't know , not working !
-i have table post for user
i want display post without refresh page used ajax
<form class="posting" method="POST" autocomplete="off"
action="createpost.php">
<textarea name="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
</form>
// code mysql the same page
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
(jquery exist in page index ) ( )
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'createpost.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
- but not working

Change this button. Since you want to run an AJAX call It shouldn't be a SUBMIT.
<button class="btn-ajouter" type="submit" name="ajouter" value="ajouter">ajouter</button>
to this
<button class="btn-ajouter" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
and change your JQuery from
$('form').on('submit', function (e) {
to
$('#ajouter').on('click', function (e) {
Also, you won't need to e.preventDefault();

Seems like that you are trying to display the information on the same page where the user submits the form. I would advise you to put the php code in a separate file and then print it somewhere on the page with javascript. A sample code for that would be something like this:
Javascript code on your current page
<script>
$(function () {
// I actually agree with Lawrence Cherone's suggestions here, so i'm including them
$('form.posting').on('submit', function (e) {
form_data = $(this).serialize()
e.preventDefault();
$.ajax({
type: 'post',
url: 'separate.php',
data: form_data,
success: function (response) {
//then you can have the server output as an object
response = JSON.parse(response);
//And print it somewhere, for example:
$('#someDiv').html(response.whatever);
}
});
});
});
</script>
Code for php in a separate file
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
$row = $stmt->fetch();
echo json_encode($row['post']);

Change this form,
<form class="posting" method="POST" autocomplete="off" onSubmit="return false">
<textarea name="text" id="text" class="textarea" ></textarea>
<button class="btn-ajouter" type="submit" id="ajouter" name="ajouter" value="ajouter">ajouter</button>
</form>
Ajax Goes Here,
$(function(){
$("#ajouter").click(function(){
var text=$("#text").val();
$.ajax({
url:"createpost.php",
method:"POST",
data:{text:text},
cache:false,
success:function(data){
$("#result").load(location.href+ "#result");
}
});
});
});
PHP & HTML Code goes here
<div id="result">
<?php
$stmt = $connect->query('SELECT post FROM publications
ORDER BY date_post DESC ');
while($row=$stmt->fetch() )
{
?>
<div class="allpost">
<?php
echo $row['post'].'<br>' ;
?>
</div>
<?php
}
?>
</div>

Related

PHP not returning Ajax Call

I'm trying to send over the data from my textarea using an ajax call to my PHP file, but we aren't getting any response back from the PHP file.
<textarea id="area" cols="70" rows="30"></textarea>
<button id="submit">Submit</button>
<script>
$('#submit').click(function (e) {
e.preventDefault();
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php',
data: {area: info}
});
});
</script>
<?php
if (!empty($_POST['area'])) {
$success = json_encode('succes');
return $succes;
};
?>
-- # Answer # --
I thought I had already tried an echo in this piece of code, but I think I just missed the output on the webpage and thought it wasn't working.
<?php
if (!empty($_POST['area'])) {
echo "success";
};
?>
Thanks Mickael for the answer!
I completely forgot to add an echo to my code.
<?php
if (!empty($_POST['area'])) {
$succes = json_encode('succes');
echo $succes();
};
?>
Your ajax post :
$('#submit').click(function (e) {
e.preventDefault();
// information to be sent to the server
var info = $('#area').val();
$.ajax({
type: "POST",
url: 'pages/assignments/response.php?return=1',
data: {area: info},
dataType:'json',
success:function(r){
console.log(r);
}
});
});
and your php response will be like
Php file:
<?php
if ( $_GET['return'] == 1 && isset($_GET['return']) ) {
echo json_encode('succes');
exit;
};
?>

Pass JavaScript argument to PHP with ajax

I need to be able to send a JavaScript variable to a PHP function. I was able to get it working for hard-coded values such as the code below.
<button onclick="submitform()">Click me</button>
<script>
function submitform(){
document.write(' <?php send_mail('hello'); ?> ');
}
</script>
<?php
function send_mail($subject){
//$subject => 'hello'
//Do something with subject
}
?>
However, I cannot replace the hard-coded value with a variable. I would also like to find another way to issue the PHP function call. I believe the solution lies in an ajax request. I cannot find a way to do this with the PHP code directly embedded as it is now. All of the other examples I cannot get to work. If possible, I would appreciate a demo as well. Thanks!
You can do it using forms:
<form action="send_mail.php" method="post">
<input type="text" id="mail" name = "mail">
<input type="submit" class="btn" value="Send Mail">
</form>
Then you can access the mail using $_POST["mail"] from the send_mail.php page
Another way to do it is ajax:
$.ajax({ url: '/send_mail.php',
data: {action: 'sendEmail', mymail:$('#mail').val()},
type: 'post',
success: function(output) {
alert(output);
}
});
Then in the send_mail.php page you can do:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
$mail = $_POST['mymail'];
switch($action) {
case 'sendEmail' : send_email();break;
// ...etc...
}
}
Demo for same page call:
<?php
if(isset($_GET['action'])=='myfunc') {
echo "Hello";
}
?>
<form action="?action=myfunc" method="post">
<input type="text" id="mail" name = "mail">
<input id="clickMe" type="submit" value="clickme"/>

Unable to identify value of HTML form element using AJAX

I am trying to implement a message system in my project by using AJAX, but I have got some problems because I am new to AJAX.
The code below is able to send input data from the MsgMain.php file to MsgInsert.php perfectly. But when I try to get $_POST['msgSend'] from MsgMain.php on MsgInsert.php it fails.
AJAX Code is on MsgMain.php
$(document).ready(function(){
$("#chatBtn").click(function(){
$("#msgBtn").val("chat");
});
$("#pmBtn").click(function(){
$("#msgBtn").val("pm");
});
});
$(function() {
$("#msgBtn").click(function() {
var textcontent = $("#msgInput").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#msgInput").focus();
}
else
{
$.ajax({
type: "POST",
url: "msg/MsgInsert.php",
data: dataString,
cache: true,
success: function(response){
document.getElementById('content').value='';
$("#msgBtn").focus();
}
});
}
return false;
});
});
MsgMain.php file code just for the HTML form
<form action="MsgInsert.php" id="frmBox" name="msgSend" method="POST" onsubmit="return formSubmit();">
<div class="input-group ">
<input type="text" class="form-control" name="msgBox" id="msgInput" title="Enter your message" required>
<div class="input-group-btn">
<button class="btn btn-success w3-hover-white w3-hover-text-green" type="submit" id="msgBtn" title="Send your message" value="chat"><i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
</form>
MsgInsert.php file code, which works well when I remove the if statement of $_POST['msgSend']
<?php
if(!isset($_SESSION['login_user'])){
header("location: ../index.php"); // Redirecting To Home Page
}
if (isset($_POST['content'])) {
if (isset($_POST['msgSend'])) {
$conn = mysqli_connect("localhost", "root", "", "msg");
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$content=$_POST['content'];
mysqli_query($conn, "INSERT INTO `msgpm`(`id`, `msgFrom`, `msgTo`, `msg`) VALUES ('','bob','ram','$content')");
}
}
?>
Sorry if this type of question has already been asked.
You are not sending the msgSent attribute, according to this line in your JS:
var dataString = 'content='+ textcontent;
I can see only the content which you will be able to use via $_POST['content'].
Try this:
var dataString = 'content='+ textcontent + '&msgSent' + '<?php echo $_POST['msgSent']; ?>';
You have to pass the msgSend Parameter according to your implementation of MsgInsert.php like so:
$("#msgBtn").click(function () {
var textcontent = $("#msgInput").val();
if (textcontent == '') {
alert("Enter some text..");
$("#msgInput").focus();
}
else {
var dataString = 'content=' + textcontent + '&msgSend=1';
$.ajax({...});
}
});
Always think of escaping your content via i.e. prepared statements when saving user generated content into your database to avoid sql injection!

How to submit a form via jQuery if url-parameter is given?

I am trying to make a form be submitted if there is a trigger-parameter in the url. I so far added a code-snippet so automatically insert the parameter into the input field.
This is my current code, working perfectly when using the submit-button or Enter.
e.g => website.com/?lookup=value
<form method="post" name="formid" id="formid">
<?php $paraid = $_GET['lookup']; ?>
<input class="form-control" id="steamid" name="s" value="<?php echo $paraid; ?>" >
<input type="submit" id="invbtn" value="submit" />
</form>
<script>
$('#formid').submit(function() {
var id = $("#steamid").val().replace(/(?:https?\:)?\/\//i, '');
$.ajax({
type: "GET",
data: "s="+id,
url: 'steam.php',
beforeSend:function() {
$("#outputinfo").html("<center><img src='./assets/img/load.gif'></br></br>Wait...</center>");
},success: function(html) {
$("#outputinfo").html(html);
}
});
return false;
});
$(document).ready(function() {
var id = '<?php echo $_GET['s']; ?>';
if (id != null) {
$.ajax({
type: "GET",
data: "s="+id,
url: 'steam.php',
beforeSend:function() {
$("#outputinfo").html("<center><img src='./assets/img/load.gif'></br></br>Wait...</center>");
},success: function(html) {
$("#outputinfo").html(html);
}
});
}
return false;
});
</script>
Thanks in advance.. i hope you guys can help me out..
To submit a form if it has a certain word in the url use:
<?php if(isset($_GET['lookup'}) == 'value') :?> //whatever website.com/?lookup=value is
<script>
$(document).ready(function(){
$('#formid').submit();
});
</script>
<?php endif ?>

Ajax and php, result in a div

I want show the result of my server page in the "result" div.
This is my scheme:
home.php
<script src="myscripts.js"></script>
<div id="loginform">
<div id="result"></div>
<?php include_once 'core.login.php'; ?>
</div>
myscripts.js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
core.login.php
<?php
// stuff about $db variable e other stupid things like $tool = new Tools etc...
$email = $_POST["email"];
$password = $_POST["password"];
// Initializing login process
if (isset($email) or isset($password)) {
$tool->decode($email, $password, $db);
}
?>
<form action="core.login.php" method="POST" id="login">
<fieldset>
<legend>Data login:</legend>
Email:<input id="email" type="email" name="email" placeholder="someone#example.com" required>
<br>
Password:<input id="password" type="password" name="password" required>
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
class.php
public function decode($email, $password, $db) {
if ($stmt = $db->prepare("SELECT password FROM users WHERE email = ?")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($password_db);
$stmt->fetch();
if ($stmt->num_rows == 1) {
if ($password == $password_db) {
echo "Success";
} else {
echo "Error";
}
} else {
echo "Email didn't found!";
}
}
}
Without AJAX if i start the code normally it work, it give me the correct echo result ( success or error ) but when i use AJAX, nothing happen.
UPDATE
Ok guys the problem was the action url, my core file is in the folder core/core.login.php, now it display the page in the result div, but the page core show me this now:
Fatal error: Call to a member function decode() on a non-object in website on line 9
Maybe ajax don't pass the variables like object?
Try this js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $("#login").serialize(), // get the form data
type: $(#login).attr('method'), // GET or POST
url: $(#login).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
Try with that in your js file:
(Or Document)
$('#loginform').on('submit', '#login', function() {
//AJAX etc..
})
instead of :
$('#login').submit(function() {
//AJAX etc..
}

Categories