5

Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post.

I have managed to create the following which is a form that displays a message on submit. If form was successfully submitted a message is displayed without page refreshing as you can see in image below:

enter image description here

FORM

        <form name="message-form" action="" id="contact-form" method"post">
        Message<br /> <input type="text" name="msg" value="" /><br />
        <input type="submit" value="Contact Us" name="contact" class="buttono" />
        </form>
        <div class="form-feedback" style="display:none">
        Thank You We will Get Back to you 
        </div>
         <div class="form-feedback" style="display:none">
        Ooops....Something Went Wrong
        </div>
       <div> 

JQUERY

  $(function(){
        $("#contact-form").submit(function(e){
        e.preventDefault(); 

        $form = $(this);

        $.post(document.location.url, $(this).serialize(), function(data){
            $feedback = $("<div>").html(data).find(".form-feedback").hide();
            $form.prepend($feedback)[0].reset();
            $feedback.fadeIn(1500)
        })

        });
    })

What I want to do

Retrieve the value from text field message and assign it to php variable

My problem

When I try to retrieve the value of message with the following code, nothing happens:

PHP code below form

 <?php
     if(isset($_POST['contact'])){
        $message = $_POST['msg'];
        echo $message; 
     }
     ?>  

Im very new to Ajax so I guess I am doing something wrong here, unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.

Thanks in advance

Timothy Coetzee
  • 5,626
  • 9
  • 34
  • 97
  • is that last code on the same page? – M H Jul 12 '15 at 02:49
  • in chrome dev tools on the network tab, when you click, do you see the post to the page? – M H Jul 12 '15 at 02:51
  • @Hanoncs I do when I use firbug I can see the value of the text box and the PHP `$msg` variable but it is not echoing on page...? Why – Timothy Coetzee Jul 12 '15 at 03:01
  • ok, so you see msg: 'whatever you entered'? thats should work. What IDE you using? – M H Jul 12 '15 at 03:06
  • Yes, thats correct my only problem is it is the value which is entered does not get echoed on the page when i do `echo $msg` yet I can see the value of `$msg` it in the console network tab... – Timothy Coetzee Jul 12 '15 at 03:09
  • see my answer. you have it right – M H Jul 12 '15 at 03:10
  • Did my anwser solve it for you? If you really want to send it to php with ajax you can create another php page to do the processing. Let me know EXACLTY what you're trying to do. – M H Jul 12 '15 at 14:26

4 Answers4

1

The issue is that you are using ajax, which does not cause a page refresh, and then trying to echo out the posted variable, since there is no page refresh, php will not process the page again to echo the posted variable.

My solution is to use javascript to display the text entered and then database it using php.

Here is an example,

$(document).ready(function () {
    $(".button").click(function () {
        $('p').text($('#msg').val());
    });
});

http://jsfiddle.net/r4nanmof/ you dont need ajax if all you want to do is display it on the page. If you plan on saving in the database then ajax is required.

M H
  • 2,179
  • 25
  • 50
  • No mate but I need to avoid a page refresh...so Ive got to use AjAX there has to be some other solution to this +1 for helping though – Timothy Coetzee Jul 12 '15 at 03:11
  • Yes, you can avoid it. You can just set the text from the $msg into a

    using javascript. You dont even need ajax for what you are trying to do.

    – M H Jul 12 '15 at 03:38
1

Hanoncs suggestion will work, but keeping things only browser side (by displaying the message only from form to div), will always give the user the impression that message is send (processed) server-side, while it is not always the case, one would make php return it before displaying it with javascript. So here is another approach I suggest:

First, Make a Separation of concerns: Sending a POST HTTP Request to the same current page contardicts somehow the purpose of AJAX. The HTTP Response will contain all the page ( the HTML rendred by PHP, the embeded HTML used for templating, and maybe the script if it is not joined in a script tag). Instead, I suggest you create a small separate php file that is responsible for rendereing only the needed markup. And so, instead of using $.post(document.location.url.., one would use $.post('pathToSmallPHPFile'..

Second, let jQuery AJAX functions accept callbacks or use promises. I suggest you carefully read the following link.

Community
  • 1
  • 1
Adib Aroui
  • 4,981
  • 5
  • 42
  • 94
0

Jquery Code for posting the message value to the php file is given below:

$('#contact_btn').click(function(event){
  event.preventDefault();
  var url = "url/of/the/php/page/where/to/process/data";
  var data = $("#msg_box").val();
  var wrapper = $('#wrapper');
  
  $.ajax({
    type: "POST",
    url: url,
    data: data,
    success: function(response){
      wrapper.html("The reponse from the page is " + response);
      },
    error: function(xhr,status,msg){
      //Handle error here
      }
  });
  
});
<code>
<div id="wrapper">
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" id="msg_box" value="" /><br />
<input type="submit" id="contact_btn" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you 
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
</div>  
</code>
Message

Thank You We will Get Back to you Ooops....Something Went Wrong
vs_lala
  • 715
  • 2
  • 8
  • 18
-1

Its not necessary in your case but change method"post"> to method="post">

And change your Form

<form name="message-form" action="" id="contact-form" method="""post">
      Message<br /> <input type="text" name="msg" value="" /><br />
    <input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">    </div>

And use the following jQuery code to post your data

$(function () {
    $("#contact-form").submit(function (e) {
        e.preventDefault();
        $form = $(this);
        $.post(
                document.location.url,
                $(this).serialize(),
                function (data) {
                    $(".form-feedback").html("Your msge " + data + " is recieved and we will get back soon");
                    $(".form-feedback").show();
                })

    });
});
Umair Ayub
  • 19,358
  • 14
  • 72
  • 146