Ajax Post Value not being passed to php file - javascript

I am having problems passing the variable to the php page.
Here is the code below:
var varFirst = 'something'; //string
var varSecond = 'somethingelse'; //string
$.ajax({
type: "POST",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});
PHP:
$first = $_GET['first']; //This is not being passed here
$second = $_GET['second']; //This is not being passed here
$con=mysqli_connect("localhost","root","pass","mydb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO mytable (id, first, second) VALUES ('', $first, $second)");
mysqli_close($con);
}
I'm I missing something? The actual data is saving to the database BUT $first and $second value is not being passed to the php file.

You are using the POST type, retrieve it in POST :
$first = $_POST['first'];
$second = $_POST['second'];
Or change your JQuery call :
$.ajax({
type: "GET",
url: "test.php",
data: "first="+ varFirst +"&second="+ varSecond,
success: function(){
alert('seccesss');
}
});

This is appening because your are passing data throw POST method and try to get with GET so change those two lines
$first = $_POST['first']; //This is not being passed here
$second = $_POST['second']; //This is not being passed here
Or simply change your method to GET in your jquery
type: "GET"

You are using type: "POST" in ajax and trying to fetch using $_GET, try
$first = $_REQUEST['first']; //This is not being passed here
$second = $_REQUEST['second'];

And there is a method to pass data like that
$.ajax({
type: "POST",
url: "test.php",
data: {first: varFirst,second: varSecond},
success: function(){
alert('seccesss');
}
});
And there you can use
$_POST['first'];
$_POST['second'];
Hope it helps.

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Ajax change php variable

I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});

AJAX data returns empty

I have the code at the bottom that get's a name from a hidden input type, and I want to send that to a php page but the ajax data returns empty. The console.log on line 4 returns the value, but the console.log on the bottom returns empty. I tried changing the way I assign data inside the ajax call according to this article but this didn't change anything. Any ideas?
$('.uploadImage input[name="userImage"]').on("change", function(){
var image = new FormData($('input[name="userImage"]')[0].files[0]);
var name = $('.hidden').attr("name");
console.log(name);
$.ajax({
type: "POST",
url: "includes/ajax-image.php",
processData: false,
data: name,
success: function(data){
console.log(name);
}
});
});
ajax-image.php
<?php
$name = $_POST["name"];
$dir = ("../user_img/".$name."");
if (!file_exists($dir)) {
mkdir($dir,0700);
}
?>
I added the ; at that line
Feel free to edit both of my code's, I really don't have and idea what to do next
The processData option here is not needed remove that and try again
try this
$('.uploadImage input[name="userImage"]').on("change", function(){
var image = new FormData($('input[name="userImage"]')[0].files[0]);
var name = $('.hidden').attr("name");
$.ajax({
type: "POST",
url: "includes/ajax-image.php",
processData: false,
data: {"name": name },
success: function(data){
console.log(data);
}
});
});
<?php
$name = $_POST["name"];
$dir = ("../user_img/".$name."");
if (!file_exists($dir)) {
mkdir($dir,0700);
}
echo $name;
?>

Ajax call insert

I have 2 ajax calls one to insert data, one to get data. Together with the functions for select and insert. the console log of the ajax call select is empty. However, when i check phpmyadmin the correct value is there.
If i start the game again, there will be 1 value (from previous game) but the score of the actual game isn't there. Until I start the game again. And so on. Does anyone know why the values are in my sql but the ajax call says it's empty?
What I understand from it. There's a score via ajax and in php it will get into the part "Check json" it sees json isn't empty so it goes to InsertScore().
The second ajax is cast but this time it doesn't have json so it will get to the method "GetScores".
The insert happens always before the select so the last score should be seen, I don't understand why it doesn't do that.
Ajax call insert:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData }
});
ajax call select:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
console.log(obj);
stageRef.$("txtTopscorePunt").html(obj[0].Score);
stageRef.$("txtTopscoreNaam1").html(obj[0].Naam);
stageRef.$("txtTopscorePunt2").html(obj[1].Score);
stageRef.$("txtTopscoreNaam2").html(obj[1].Naam);
stageRef.$("txtTopscorePunt3").html(obj[2].Score);
stageRef.$("txtTopscoreNaam3").html(obj[2].Naam);
}
});
php insert:
function InsertScore($obj) {
$query = "INSERT INTO topscoresNew (Score, Naam) VALUES('" . $obj['score'] . "','" . $obj['naam'] . "')";
$result = mysql_query($query);
}
php select:
function GetScores() {
$query = "SELECT * FROM topscoresNew ORDER BY Score DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['Score'] = $row['Score'];
$scoresArray[$i]['Naam'] = $row['Naam'];
$i++;
}
echo json_encode($scoresArray);
}
check json:
if (isset($_POST['json'])) {
$score = json_decode($_POST['json'], true);
InsertScore($score);
} else {
GetScores();
}
Make the ajax-calls synchronous:
$.ajax({
type: "POST",
url: "Database.php",
dataType: "json",
data: { json: jsonData },
async: false
});
This way the 'select'-call will wait for the 'insert'-call to finish.

What is the proper or best way to get data from ajax?

I have this javascript code with ajax.
$('#btnCart').click(function() {
var pName = document.getElementById('prodName').value;
$.ajax({
url: 'index.php',
data: 'prdName='+pName,
success: function(data) {
$('#prod').html(data);
}
});
});
I want to get the value of pName to be returned on my php. Here's my code on my index.php side:
<?php
$prodName = $_GET['prdName'];
echo $prodName;
?>
But it returns Unidentified index: prdName.
How can I get the value from ajax to my php? Please help...
if(isset($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo $prodName;
}
You should send the data as:
data: {prdName: pName},
add this to your PHP code:
if(!empty($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo cartTable($prodName);
}
also some corrections in js:
$('#btnCart').click(function() {
var pName = $('#prodName').val();
$.ajax({
url: 'index.php',
data: {prdName:pName},
success: function(data) {
$('#prod').html(data);
}
});
});
In index.php Get the prdName value from $_POST[] global array.
to send data to index.php file add type type:'POST' in ajax code
$.ajax({
type:'POST',
url: 'index.php',
data: {'prdName': pName},
success: function(data) {
$('#prod').html(data);
}
});
or you can use $.post() method in jQuery
$.post(
'index.php',
{'prdName='+pName},
function(data) {
$('#prod').html(data);
}
});
in index.php
if(isset($_POST['prdName']){
$prodName = $_POST['prdName'];
echo $prodName;
}

Categories