Benjamin Oats Benjamin Oats - 1 month ago 8
Ajax Question

post with ajax and php while verifying URL query

I am trying to post variables through ajax and get via php. I am getting


Undefined index: source1

Undefined index: source2


In my php echoing out of the variables, any one know what is up with my code ?

HTML

<head>
<script src="./script.js"></script>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>

<body>

<form action="get.php?&uniId=3" method='post' name='sendform' onSubmit='send_value()'>
<input type='submit' value='Test1'>
</form>

</body>


Ajax

function send_value() {
$.ajax({
type: 'post',
url: 'get.php',
data: {
source1: "some text",
source2: "some text 2"
},
success: function (data) {
console.log(data);
}
})
}


PHP

<?php

if (!empty($_GET{"uniId"})) {

if ($_GET{"uniId"} == 3) {
echo 'your logged in as '; echo $_GET['uniId'];

$src1 = $_POST['source1'];
$src2 = $_POST['source2'];

echo $src1;
echo $src2;

var_dump($_REQUEST);

} else {
echo 'no! no! no!';
}
} else {
echo "Im sorry your on the wrong page ";
}

Answer

You can pass the data as the concatenation of the variables into the JavaScript functions.

Pass Multiple Variables in the data of the AJAX Script.

This is one of the method to pass the data.

function send_value() {
    var value1 = "Post One";
    var value2 = "Post Two";
    $.ajax({
        type: 'post',
        url: 'get.php',
        data: "&data1"+value1+"&data2"+value2,
        success: function (data) {
            console.log(data);
        }
    });
}

And in the PHP you need to check the data like this if you are getting var_dump() perfecth with the unID.

PHP Code:

Error: You need to access the $_REQUEST[] or $_GET[] with the helpf of this brace [] but you have used {} which is entirely a blunder.

Hence You need to replace the below code like this:

Replace:

if ($_GET{"uniId"} == 3) {}

With:

 if ($_POST["uniId"] == 3) {}

An your Entire code will look like as follows.

<?php
if (!empty($_POST["uniId"])) {
if ($_POST["uniId"] == 3) {
   // Data Process Here
}
}
?>

get.php file will be like this on the whole:

<?php
if (!empty($_POST["uniId"])) { // Your brace look wrong in this line
    if ($_POST["uniId"] == 3) { // Your brace look wrong in this line
        echo 'your logged in as '; echo $_GET['uniId'];
        $src1 = $_POST['data1']; // This should be the variable what we have used for seding purpose.
        $src2 = $_POST['data2'];
        echo $src1;
        echo $src2;
var_dump($_REQUEST);
    } else {
        echo 'no! no! no!';
    }
} else {
    echo "Im sorry your on the wrong page ";
}
Comments