Kaba
Kaba

Reputation: 83

Send multiple variables via ajax

Im so noob at this, been working with PHP and Js for like 4 months, sorry if im making a noob question, also, im a spanish speaker, sorry for english grammar fails you are going to read =[

Basically, this is my problem: In this Php File i have some Vars and VarArrays, i need to send them to another one

//First PHP File - This one Search on DataBase, at the end, i have 5 vars, 2 of them are arrays
<?php
$var1 = '1';
$var2 = '2';
$var3 = '3';

$arr1 = array();
$arr2 = array();

//¿How to json_encode the 5 vars above?//
?>

In this one i need to catch the previus values

//Second PHP File
<?php
$newVar1 = $_POST['var1'];
$newVar2 = $_POST['var2'];
$newVar3 = $_POST['var3'];

$newArr1 = $_POST['arr1'];
$newArr2 = $_POST['arr2'];
?>

I think i have to do something like this, but how should i do it?:

$.ajax({
        type: "POST",
        url: "php/FIRSTFILE.php",
        data: ????,
        dataType: "json",
        success:
                function(respuesta)
                {
                  $('#MainDiv').load('php/SECONDFILE.php', function(data) {
                      $(this).html(data);
                  });
                  $('#MainDivLabelVar1').val(respuesta.¿¿EncodeStuff??);
                }
 });

Upvotes: 0

Views: 724

Answers (3)

Jasper Chang
Jasper Chang

Reputation: 50

you could deocde the json string into object or array

$js_array = json_encode(array(
         'var1'   =>    '1',
         'var2'   =>    '2',
         'var3'   =>    '3',
         'arr1'   =>     array('a' => 'mobile', 'b' => 'PC'),
         'arr2'   =>     array('price' => 600, 'day' => 7)
          ));

$decode = json_decode($js_array, true); //decode into array

//you could use or seperate something you get back from json decode like this
foreach($decode as $key => $value) {
    if(is_array($value)) {  
        foreach ($value as $k => $v) {
            echo "$k => $v <br />";
        }
    } else {
        echo "$key: $value <br />";     
    }
}

and the output:

var1: 1 
var2: 2 
var3: 3 
a: mobile 
b: PC 
price: 600 
day: 7

Upvotes: 0

user2478240
user2478240

Reputation: 369

maybe you can encode your data like this

json_encode(array(
         'var1'   =>    '1',
         'var2'   =>    '2',
         'var3'   =>    '3',
         'arr1'   =>     array(),
         'arr2'   =>     array()
          ));

Upvotes: 1

3Letters
3Letters

Reputation: 23

In this line you are sending values in POST to your php file:

 data: {id: id, CAT: CAT},

So, if you need to receive data like (in file "second.php")

<?php
  $newVar1 = $_POST['var1'];
  $newVar2 = $_POST['var2'];
?>

You should send it by this:

$.ajax({
        type: "POST",
        url: "php/second.php", 
        data: {var1: 'value1', var2: 'value2'}
});

Upvotes: 0

Related Questions