4

I have the following form:

<form id="f-comment" class="form" method="post" action="submit_img_comment.php">
    <textarea name="comment"></textarea>
    <input type="submit" value="Publish" data-params='{"imageid":<?php echo $imageid; ?>}'>
</form>

and the following javascript:

$(document).on("submit", ".form", function(e) {
    e.preventDefault();

    // what form are you submitting?
    var form = $("#" + e.target.id);

    var data = new FormData(this);
    var params = $("input[type=submit]", this).data("params"); // parameters to send along with data
    data.append("params", params);

    // data is ok
    console.log(params)

    $.ajax({
        type: form.attr("method"),
        url: "include/" + form.attr("action"),
        data: data,
        dataType: "json",
        contentType: false,
        processData: false,
        cache: false
    }).done(function(data) {
        alert(data['msg']);
    }).fail(function(data) {
        alert("Error: Ajax Failed.");
    }).always(function(data) {
        // always do the following, no matter if it fails or not
    })
});

in my php file (submit_img_comment.php) im able to get the comment, like this

$_POST['comment'];

But, when i try to get the imageid, like this

$_POST['imageid'];

I get the error: Undefined index: imageid

The comment is part of the form, but the imageid is send as a parameter and appended in FormData.

How do i get the imageid in my php file?

2
  • check what are you getting in jQuery variable data? Commented Mar 3, 2016 at 14:31
  • i did using console.log(params). I'm getting the correct data. Commented Mar 3, 2016 at 14:35

3 Answers 3

8

You are look at this all wrong, what you have appended to your form is not imageid but params. Also, what you are sending is a javascript object, you need to convert this to a string first. You will need to do the following in JavaScript:

var data = new FormData(this);
var params = $("input[type=submit]", this).data("params"); // parameters to send along with data
var json_params = JSON.stringify(params); // This converts your javascript object into a string that you can send to the server.
data.append("params", json_params); // We are adding the string we have converted from the javascript object.

Now that we have sent a JSON string to the server, we now need to decode it. To decode the JSON in php we use:

$params = json_decode($_POST['params']);

The variable $params will now be a php object which contains imageid as a property. This means that your image id is now stored in $params->imageid variable e.g. echo $params->imageid will output your image id.

As @baboizk has rightly mentioned, you should use isset() in PHP to make sure it actually exists before using it. E.g.

$params = json_decode($_POST['params']);

// Check that imageid exists.
if(isset($params->imageid) == true) {
    // Do code that needs $params->imageid;
} else {
    // Fail gracefully.
}
Sign up to request clarification or add additional context in comments.

4 Comments

using var_dump i get: array(2) { ["comment"]=> string(10) "testing123" ["params"]=> string(15) "[object Object]" }
Then I am correct, you are not converting your javascript object into a string before sending it first. If you look at my answer, I have used JSON.stringify() function (which is built into the browser as standard) which converts your javascript object (e.g. {imageid: 'value'}) into a string that you can submit to the server. You then need to decode that string back into a php object, otherwise you can't use the information - also see my answer where I mentioned json_decode().
Genius!! That did it! Thanks. Before, i was able to send the object without FormData and it work. I guess when appending into FormData, it is different. Thanks.
Yeah it is a bit different when you are using a form javascript object. I've updated the answer so that it no longer includes the assumptions I made. Also, you're welcome. :)
2

You are probably attempting to acces an unset value and this leads to a runtime error. $_POST does not have any element with the index 'imageid' so your program gets aborted by the interpreter before it ever gets to the null test.

Here is where isset() is handy for testing the existence of a variable or array element without actually trying to acces it.

http://php.net/manual/en/function.isset.php

3 Comments

isset() is useful to check if something exists, but it seems that OP is not checking to make sure that the correct information is being sent first, nor is he checking that he is accessing the correct value. isset() will only be useful if you know that the variable you are testing against is sometimes available and sometimes isn't.
@hazrpg you are partially right. I just thought in this situation its alot of times the issue of an unset value. Maybe not perfect in this situation though, thanks for your feedback.
No problem, thanks for your feedback too. I appreciate the fact that you mentioned isset() because a lot of programmers forget that they should check a variable exists first - which is good advice to give!
1

Try

$_POST["params"]["imageid"]

3 Comments

Unfortunately, i get: Illegal string offset 'imageid'
@Marco What does $_POST["params"] return ?
For future reference, $_POST['params'] contained this: string(15) "[object Object]"

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.