0

I am practicing doing simple AJAX calls to localhost but experiencing trouble. What I'm trying to do is send two textbox form values to PHP and then have it return a message to an empty div in my form upon successful reception via AJAX. My test.php is like this:

<?php

$num = htmlentities(substr($_POST["num"], 0, 7), ENT_QUOTES);
$name = htmlentities(substr($_POST["name"], 0, 50), ENT_QUOTES);

$result = "'$num ' + 'and' + ' $name' + ' values have been successfully AJAXd'";

echo json_encode($result);

jQuery:

  $("#form").submit(function() {
    event.preventDefault();
    $("#msgcontainer").html("");
    $.ajax({
    url: "test.php",
    data: ("#num").serialize(), ("#name").serialize(),
    contentType: "application/json; charset=utf-8",
    type: "POST",   
    dataType: "json"
      success: function(response) {
        $("#msgcontainer").html(response);
      }
    });
  }

When I try to submit, the page simply reloads and adds form values to the URL. I've been trying to solve this for about a day now, so any help would be greatly appreciated.

EDIT:

I figured it out by trying things from every response. Not sure why it works without serialization... If someone knows, please explain. Working jQuery code:

  $("#form").submit(function(event) {
    event.preventDefault();
    $("#msgcontainer").html("");
    $.ajax({
    url: "test.php",
    data: {
            num: $("#num").val(),
            name: $("#name").val()
          },
    type: "POST",
    dataType: "json",
      success: function(response) {
        $("#msgcontainer").html(response);
      }
    });
  });

Thank you for the help!

2
  • $result = "{$num} and {$name} values have been successfully AJAXd"; would be the correct format Commented Jul 1, 2014 at 14:58
  • Could you share the HTML as well? Btw, you should have seen parse errors in the JavaScript console. Commented Jul 1, 2014 at 15:01

5 Answers 5

1

Two things stand out immediately:

data: ("#num").serialize(), ("#name").serialize(),
contentType: "application/json; charset=utf-8",

The first should be this (assuming you have two text boxes):

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

And the contentType: line should not be there, otherwise you'll have an empty $_POST.

Lastly, event should be a function argument, i.e.:

$("#form").submit(function(event) {
    event.preventDefault();
    // ...
Sign up to request clarification or add additional context in comments.

4 Comments

This works, but why does it work without serialization?
@user3361043 When you pass a simple object as data: jQuery will do the serialisation for you.
I see. So when is it needed?
You can use $(this).serialize() to get a string which you can then pass using data:; this comes in handy when you have a number of input fields and you don't require special handling of the values.
1

Your data parameter in your AJAX call is wrong, should be something like:

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

Comments

0
$("#form").submit(function() {
  event.preventDefault();

event isn't defined anywhere. I'm guessing you meant ...submit(function(event) {.

You should be seeing an error in the JavaScript console telling you "event is not defined" or "TypeError: Cannot read property 'preventDefault' of undefined."

Comments

0

good morning,

You have to serialize the entire form, like:

$("#yourform").serialize();

Instead of just field by field:

("#num").serialize(), ("#name").serialize()

Comments

0

The data is not being sent properly. Consider replacing:

data: ("#num").serialize(), ("#name").serialize(),

With:

data: $(this).serialize(),

And then you may want to edit your PHP script so that you concatenate the strings instead of summing them.

Also pass the event param or simply use the following:

$("#form").submit(function() {
    var event = arguments[0];
    event.preventDefault();
    ....
});

I doubt that you need contentType: "application/json; charset=utf-8",!

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.