Ajax call insert - javascript

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.

Related

Send variable to php via ajax

I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);

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);
}
});
});

INSERT query via looped AJAX call not working second time and beyond?

I have a JS function called db_input:
function db_input(dataString,x){
$.ajax({
url: "custom_scripts/db-input.php",
type: "POST",
dataType:'json',
data: dataString,
cache: false,
success: function(data){
if(data.auth==true){
//alert("success: " + x);
} else {
alert(data.error);
return false;
}
}
})
}
that is passed a JS var called dataString through a forloop:
for(x=1;x<=var;x++){
...
var dataString = 'a_var='+ a_var + '&b_var='+ b_var + '&c_var='+ c_var + '&d_var='+ d_var + '&e_var='+ e_var;
db_input(dataString,x);
}
that looks for non-empty, validated, HTML input elements and inserts the values into JS variables which are appended to dataString each iteration and passed via AJAX to a PHP script that inserts them into a table in a database:
<?php
...
$a_var=$_POST['a_var'];
$b_var=$_POST['b_var'];
$c_var=$_POST['c_var'];
$d_var=$_POST['d_var'];
$e_var=$_POST['e_var'];
$rVal=array("auth" => false, "error" => NULL);
//connect
$query="INSERT INTO `db`.`table` (`a_var`, `b_var`, `c_var`, `d_var`, `e_var`) VALUES (?, ?, ?, ?, ?);";
$stmt = $conn->prepare($query);
$stmt->bind_param("sssss", $a_var, $b_var, $c_var, $d_var, $e_var);
$stmt->execute();
$rVal['auth']=true;
$stmt->close();
$conn->close();
echo json_encode($rVal);
...
?>
Each HTML element are stored in divs (some together; some separated) ... the JS validation function (that leads to the loop that calls db_input) is called by a button onclick:
<input class="submit" style="float:left; color: #595959;" type="button" value="submit" onclick="validate();" />
This works the first time ... depending on how many divs are open and validated with non-empty data, the JS loops through and inserts a_var, b_var, c_var, d_var, and e_var into the database via the db_input ajax call to the db-input.php script ...
The issue is that, while the call appears to complete each time (success), data is only inserted into the database the first time or until the page is refreshed ... what'(s)(re) the issue(s)?
Try setting async to false:
function db_input(dataString,x){
$.ajax({
async: false,
url: "custom_scripts/db-input.php",
type: "POST",
dataType:'json',
data: dataString,
cache: false,
success: function(data){
if(data.auth==true){
//alert("success: " + x);
} else {
alert(data.error);
return false;
}
}
})
}
How about we change the logic to hit the server all of ONE time instead:
function db_input(dataStrings){
$.ajax({
url: "custom_scripts/db-input.php",
type: "POST",
dataType:'json',
data: dataStrings,
cache: false,
success: function(data){
if(data.auth==true){
//alert("success: " + x);
} else {
alert(data.error);
return false;
}
}
})
}
...
var dataStrings =[];
for(x=1;x<=var;x++){
dataStrings.push('a_var='+ a_var + '&b_var='+ b_var + '&c_var='+ c_var + '&d_var='+ d_var + '&e_var='+ e_var);
}
db_input(dataStrings);
You'd have to fix the PHP (someone else would have to weigh in there) to accept a list of value-lists but this would be how I would structure the entire process.
I figured it out ... I accidentally cleared one variable (a boolean on the form to '' instead of a default value of 1) ... I'll add additional validation in db-input.php to make sure query is successful ... thanks everyone for your help ...

How to catch array sent by PHP script as Ajax response and use further?

I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});

Ajax Post Value not being passed to php file

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.

Categories