How to show result via ajax and jquery without refresh on page

2

I tried to implement an Ajax call on a project and I can not identify the error. I have a form for posting status and I would like it as soon as I post something it does not refresh on the page and rather it shows the result, then in a div.

It turns out that it is redirected to the page and goes to / update_post.php when I return to the dashboard the result is in the Status div. and appears on the bottom div. Can you publish and show the result immediately?

Follow 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 the statuses below the submission form:

<div id="posts" class="span9">
        <br><b>Recent Posts</b><br><br>
        <?php require_once('recent_posts.php');?>
    </div>  
    
asked by anonymous 16.07.2017 / 08:03

1 answer

1

If you do not want to reload the page by clicking the button it changes the type="submit"  for type="button" then changes onclick="updatePost" to id="updatePost" , so your jQuery selector will already work to be activated when the button is clicked.

In your data I do not know where you are going to get these values, is the question JavaScript missing? but from what I see it should look like this:

data:({
    data: $('#status').val()
}),

The other fields do not have the question but you can use the same idea: chave: valor

    
16.07.2017 / 11:22