Jump to content

$.post with variable as field name

Recommended Posts

Hi All,

I have a $.post query with a field/value pair as an input parameter




This code is inside a function that is triggered by an onkeyup event


As such it works.

Now, is it possible to pass the "field_name" part of the query as a parameter ? The following triggers the function but fails with a "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data" error.



function myFunctionV(hello) {




Share this post

Link to post
Share on other sites

Is this what you are trying to do



if (isset($_POST['fieldname']))  {
    exit("\"{$_POST['fieldname']}\" was sent OK");         // send ajax response


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type='text/javascript'>

     $().ready( function() {
         $(".mybutton").click( function() {
             $.post (
                "",                                   // send to self
                {"fieldname" : $(this).val() },
                function(resp) {

<button class='mybutton' value='field A'>Button 1</button>
<button class='mybutton' value='field B'>Button 2</button>
<button class='mybutton' value='field C'>Button 3</button>


Share this post

Link to post
Share on other sites

Not really. But anyway thanks for the time spent on it.  I think I was misleading you (and myself too) by using "field name". What is sent is not actually a field/value pair, but a value that will go in the WHERE clause of a MySQL query where fields are already set. I realized I need no JS parameter for this in fact...

Share this post

Link to post
Share on other sites

The syntax you want is

{ [hello]: value }

but it's new to ES6 and not all browsers support it. So you should continue with the old syntax of

var data = {};
data[hello] = value;


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.