0

I have this code in JavaScript:

$.ajax({
    type: "POST",
    url: "funcoes/a-php/ler/ler_config.php",
    data: 'data_id=fish/config/horse/config/car',
    cache: false,
    success: function(data_o){
        alert(data_o);
    }
});

and on the file 'ler_config.php' I have this codes:

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $data = $_POST['data_id'];
    list($name, $value) = explode('=', $data, 2);
    $result = explode('/config/', $value);
    print_r($result);
}

So I'm having trouble with this line:

list($name, $value) = explode('=', $data, 2);

and php notice me this messanger:

Undefined offset 1

So how can I fix it?

3
  • Do a print_r($data) to see what is in it and add it to your question to help us answer. Commented Dec 22, 2013 at 21:25
  • You aleady have $_POST['data_id'] = 'fish/config/horse/config/car'; Commented Dec 22, 2013 at 21:26
  • Why don't you just combine your two questions into one? You're getting different answers on each question because you haven't provided enough context, now you're chasing a rabbit down a hole... stackoverflow.com/questions/20733720/array-by-expressions Commented Dec 22, 2013 at 21:30

2 Answers 2

2

The problem is that your explode function is splitting $data by = signs (which don't exist in the string) - some basic debugging would have told you that.

This is the format of your string:

data: 'data_id=fish/config/horse/config/car'

... so $_POST['data_id'] = 'fish/config/horse/config/car';

Now, I'm not sure what you're trying to achieve with this code, but if you're trying to split that string from AJAX by the = sign, you just don't need to. It's just telling ajax that data_id is going to be equal to .... The = doesn't actually come out in PHP.

If you're splitting that string, it should be by / instead.

Also, to be clearer with your AJAX, you should wrap your data variables inside {} brackets and not include the variable name inside the quotes:

data: {
    data_id: 'fish/config/horse/config/car'
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is your post data: data_id=fish/config/horse/config/car
That means that $_POST['data_id'] will already contain fish/config/horse/config/car

Since there is no = in it, exploding it will yield an array with only ONE value with index 0. There will be no second value with index 1. Thus your message about the index not existing.

So in stead of list($name, $value) = explode('=', $data, 2);
... you should do:

$name = 'data_id'; // this is the key value you already used for $data
$value = $_POST['data_id']; // or $value = $data; it's the same

Comments

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.