2
I tried to implement an Ajax call in a project and I can’t identify the error. I have a form for posting status and I would like that as soon as I post something it does not refresh the page but shows the result, then in a div.
It turns out that it is redirected to page and goes to / update_post.php when I return to Dashboard the result is in the div of Status. and appears in the lower div. You can publish and display the result immediately?
Follows the code:
Dashboard
<form name="updatePost" method="post" action="update_post.php">
Nome: <input type="text" class="input-xxlarge" id="status" name="data" /> </br>
<input style="margin-left:10px" type="submit" class="btn btn-primary" value="POST" onclick="updatePost"/>
</form>
<script>
$("#updatePost").click(function(){
$.ajax({
dataType:'html',
url:"update_post.php",
type:"POST",
data:({+input+'did='+did+msg='+msg}),
beforeSend: function(data){
success: function(response) {
$('#status').html(response);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;});
</script>
update_post.php
<?php
session_start();
require_once('connect.php');
$msg = $_POST['data'];
$sid = $_SESSION['id'];
$did = $_POST['did'];
$type = 'user';
if(!empty($msg)){
$sql = "INSERT INTO post(SID,DID,Message,`P/U`) VALUES ('$sid','$did','$msg','$type')";
if($result = mysqli_query($dbc,$sql) or die('error!!'))
{
echo 'OK';
header('http://localhost/profile.php');
}
else{
echo 'Error';
}
}
?>
There is a div that shows all status below the send form:
<div id="posts" class="span9">
<br><b>Recent Posts</b><br><br>
<?php require_once('recent_posts.php');?>
</div>
Ta even giving Refresh? I tried to reproduce your code more or less here and it worked.
– Lucas de Carvalho
Can you explain where these variables come from
data:({+input+'did='+did+msg='+msg}),
? and what data do you want to send to the server? (because I only see 1 input)– Sergio
Hello, so here’s the problem, I know this is wrong, and it’s not sending anything, no request, I think the data I have to send is the one from update_post.php $msg = $_POST['data']; $sid = $_SESSION['id']; $Did = $_POST['Did']; $type = 'user';
– Rafael Fleitas
But you want to send from the browser to the right PHP? and then only 1 input you want to send?
– Sergio
I think yes, I have never touched Ajax, I know very little, what I need, is to send the user post I think is just the $msg = $_POST['data'];, through the input, after clicking the button it should appear in a div, through jquery, without having to refresh the page, I’m sorry I can’t explain more, I’m a student, still learning... From Now on Thank you!
– Rafael Fleitas
I restored my answer from yesterday. I think there’s what you need to do. Read carefully and ask in the reply comments or here if you don’t understand any part. You can use
@sergio
or someone else to receive an email here on the site. Now I go to sleep but take a look later here.– Sergio