crmepham
crmepham

Reputation: 4740

How do you post an elements value through ajax with jquery?

I am able to post a string to the PHP file but when I try and select an input field within a form to post the value inside it to the PHP file it doesn't work. Am I selecting the value in the input field correctly?

.js

$.post("js/data.php", {postid: form.postid.value},
            function(output){
                $("#gotpostid").html(output).show();
            }).fail(function(x,y,z){ 
                $("#gotpostid").html(x + "<br />" + y + "<br />" + z)
            });

index.php

<div class="post">
<form name="form"><input type="text" name="postid" value="1234" />
</div>

If i simply do {postid: "some text"} it works fine.

Upvotes: 1

Views: 153

Answers (5)

user1299518
user1299518

Reputation:

try these.

$.post("js/data.php", {postid: document.getElementById("postid").value},

or

$.post("js/data.php", {postid: $("input[name='postid']")[0].value},

Upvotes: 1

Isaac Gonzalez
Isaac Gonzalez

Reputation: 91

you could try to send it like this:

        $.post("js/data.php", $(this).serialize(),
        function(output){
            $("#gotpostid").html(output).show();
        }).fail(function(x,y,z){ 
            $("#gotpostid").html(x + "<br />" + y + "<br />" + z)
        });

that way you send all the values from your form to the php and don't have to worry about it anymore

Upvotes: 0

dbkaplun
dbkaplun

Reputation: 3637

Instead of form.postid.value, try $('[name="postid"]').val().

Upvotes: 1

Nicol&#225;s Torres
Nicol&#225;s Torres

Reputation: 1345

Use

  $('input[name="postid"]').val();

instead of

form.postid.value

Upvotes: 1

ssj1980
ssj1980

Reputation: 391

Try the following:

<input type="text" name="postid" id="postid" value="1234" />

and grab the value by doing

value of postid is $("#postid").val() instead form.postid.value

Upvotes: 1

Related Questions