Variable data in jquery ajax call

I am trying to use a variable in an AJAX call in jquery, but it does not work. Moving a variable contains different values. Check out the following code:

var $move = 'next'; $.ajax({ type: "POST", url: "somephp.php", data: {$move:1}, }); 

Suggest any way to use the $ move variable in data.

+8
source share
7 answers

It should be

 $.ajax({ type: "POST", url: "somephp.php", data: {"data":$move}, }); 
+3
source

If you want to use a variable as the property name, use array notation.

There are two ways to access the elements of an object: note notation and writing in brackets (aka index operator)

Your code with an array designation:

 var $move = 'next'; var data = {}; data[$move] = 1; $.ajax({ type: "POST", url: "somephp.php", data: data, }); 

Jsfiddle example (the message is clearly not working, so check the console to see what will be sent.)

+12
source

If you want to have a variable variable in your POST request, you will need to create a separate JSON object:

 var name = 'next'; var dataObject = {}; dataObject[name] = 1; $.ajax({ type: "POST", url: "somephp.php", data: dataObject, complete : function() { // success! } }); 
+8
source

You can do something like data: $move+"=1"

+1
source

To publish the value of the $ move variable, do the following:

 $.ajax({ type: "POST", url: "somephp.php", data: {move: $move} }); 
0
source

I was looking for something like this. I wanted to have a variable for the key and a variable for the value.

 let dataPair = {}; dataPair[dataKey] = dataValue; $.ajax({ url: TheAPIPath, data: dataPair, method: "GET", (etc) 
0
source

It looks like you are trying to use a PHP variable in javascript. You can use .serialize to collect data and pass it to an ajax call. But as for calls with different named variables for the name of a pair of values, you will need to collect this information from the php page that you pass.

Example:

 $.get("jQueryFunctions.php?action=checkCaptula",$('#resetPasswordDiv :input').serialize()).done(function(data){ .... 

While this is .get instead of .ajax, it simply shortens the .ajax call. PasswordDiv contains HTML inputs with names and identifiers. It collects the information and passes it to the php page for processing.

-one
source

All Articles