0

Trying to send a variable with ajax to php.

The js:

var test1 = "test"
$.ajax({
    type : "POST",
    url : "getid.php",
    data:  {test1 : test1},
    success: function() {
         console.log("message sent!");
    }
}); 

"message sent!" comes up in the console

The php:

<?php 
$test1 = $_POST['test1'];
echo $test1; 
?> 

Error message:

Notice: Undefined index: test1...

I don't really see what i have done wrong here... Any ideas?

UPDATE* when doing `

$.ajax({    
        type : "POST",
        url : "getid.php",
        data:  {"test1" : test1},
        success: function(msg) {
            console.log("message sent!");
            console.log(msg);
        }
}); 

This logs "test"

Still getting the same error in the php though..

5
  • 1
    No, because then it'd throw an error looking for a constant. It's $_POST['test1']. Commented Jul 7, 2013 at 17:18
  • @AliBZ nope. please don't advice that. Commented Jul 7, 2013 at 17:20
  • For your updated: you need to add data as argument to success function. Commented Jul 7, 2013 at 17:24
  • i did add it to the success function Commented Jul 7, 2013 at 17:25
  • @Koiski add success: function(**data**) { Commented Jul 7, 2013 at 17:27

2 Answers 2

2

Alter you jQuery code:

var test1 = "test"
$.ajax({
    type : "post",
    url : "getid.php",
    data:  {"test1" : test1}, // this is the row that was causing the problem
    success: function(msg) {
         console.log(msg);
    }
}); 

You had to put test1 in quotes because it was a defined variable containing "test" which resulted in data being {"test":"test"}

Sign up to request clarification or add additional context in comments.

10 Comments

Object keys do not require quotes
You are right however test1 is a variable containing test which changes the key
In both cases it will still be "test1": a = "1"; -> "1"; b = {a: 2}; -> Object {a: 2}; b = {"a": 2}; -> Object {a: 2};
@Koiski I've updated the success function, copy paste it to your code and tell me what this logs
then it works :). "test" is the value you'd expect it to show.
|
0

Its becouse the response is given to the callback functions as arguments. try somthing like this

var test1 = "test"
$.ajax({
    type : "POST",
    url : "getid.php",
    data:  {"test1" : test1},
    success: function(data) { // data argument here
         console.log("message sent!");
         console.log("data:",data); // log it out here 
    }
}); 

1 Comment

it logs "message sent" "test" but i still get the same error when looking at the php. $.get("getid.php", function(data) { alert("Data Loaded: " + data); });

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.