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

7
  • is that last code on the same page? Commented Jul 12, 2015 at 2:49
  • in chrome dev tools on the network tab, when you click, do you see the post to the page? Commented Jul 12, 2015 at 2: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 Commented Jul 12, 2015 at 3:01
  • ok, so you see msg: 'whatever you entered'? thats should work. What IDE you using? Commented Jul 12, 2015 at 3: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... Commented Jul 12, 2015 at 3:09

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

He did not say he wanted to save in the database.
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.

2 Comments

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
Yes, you can avoid it. You can just set the text from the $msg into a <p> using javascript. You dont even need ajax for what you are trying to do.
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

Comments

-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();
                })

    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.