$.ajax({
url: 'http://localhost/xampp/htdocs/ajax.php',
contentType: 'application/json',
type: 'post',
data: {
//score is a new variable and count2 is an integer variable which i want to send it to the database
"score":"count2"
},
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
The above code alerts me "ok".
function connect(){
$connect = mysql_connect('localhost','root','') or die("ERROR");
$connect2Database = mysql_select_db('fypdb', $connect);
return $connect;
}
if(isset($_POST)){
if($connect = connect()){
$query = "INSERT INTO fypdbtable (score) VALUES ('".$_POST['score']."');";
$completeQuery = mysql_query($query, $connect);
}
}
I think the problem is on "insert into" query because in ajax.php prompts me Notice: Undefined index: score in C:\xampp\htdocs\xampp\htdocs\ajax.php on line 14 where it is the query line
Any help would be appreciate
Problem here is in your ajax code. You are using contentType: 'application/json' but you try to acces
param in your php script with $_POST, but post works with form encoded content types.
So you can remove contentType from your ajax call and it will use default which is
contentType:'application/x-www-form-urlencoded; charset=UTF-8'
EDIT
Make your ajax code like that:
$.ajax({
url: 'http://localhost/xampp/htdocs/ajax.php',
type: 'post',
data: {
"score":"count2"
},
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
The "error" message tells you, that $_POST['score'] is not defined. But thats just a warning. If you want to know if your variable is set, use isset() function or turn off warnings in the configuration.
Related
I'm trying to get the count of a variable using ajax but it keeps printing fail everytime
here is the php file that works perfectly when I test it
<?php
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bdpfe") or die ("no database");
$rech=$_GET['q'];
$sql=mysqli_query($conn,"select count(id_com) as nbr from commentaire where id_pub like '".$rech."' ");
$response = array();
$nbrs = array();
$result=$sql;
while($row=mysqli_fetch_array($result))
{
$nbr=$row['nbr'];
$nbrs[] = array('nbr'=>$nbr);
}
$response['nbrs'] = $nbrs;
echo "mycallbackcom(".json_encode($response).")";
?>
and here is the ajax call using jsonp
(function getnbr() {
$.ajax({
type : 'GET',
url : 'http://127.0.0.1:800/test/count_com.php?callback=?&q='+$('#idpub').val() ,
jsonpCallback: 'mycallbackcom',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
alert("succes");
},
error: function () {
alert("fail");
}
});
})(jQuery);
and the callback function is empty for now:
function mycallbackcom()
{}
it keeps printing fail every time.
Try only returning the JSON. You have specified this as your expected return dataType.
echo json_encode($response);
Then handle the response:
(function getnbr() {
$.ajax({
type : 'GET',
url : 'http://127.0.0.1:800/test/count_com.php?callback=?&q='+$('#idpub').val() ,
jsonpCallback: 'mycallbackcom',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
mycallbackcom(data)
},
error: function () {
alert("fail");
}
});
});
You need to parse the $_GET variable..
$data = json_decode($_GET['q']);
function mycallback($data) {
//Do something
}
return mycallback($data);
i am writing a online tictactoe game and i have a function in javascript that check that if some where clicked in the screen is not X or O then mark it with X or O and then update the database where is clicked. here is my javascript code in play.php page (this is in ) where check that with isEmpty function . path is the variable that detect which cells in tictactoe is clicked(from 1 to 9) :
....
if (isEmpty(xBoard, oBoard, bit)) {
path.push(y*3+x+1);
alert(path);
markBit(bit, playerXO);
$.ajax({
type: "POST",
url: "gameProcess.php",
data: {
'ID' : path
},
dataType: "json",
success: function(){
alert('success');
},
});
....
i use ajax to update something in database with PHP (gameProcess.php) and send 'ID' value to write in a table of mysql Database.here is my gameProcess.php code:
<?php
function post($key) {
if (isset($_POST[$key]))
return $_POST[$key];
return false;
}
// setup the database connect
$cxn = mysql_connect('localhost', 'root', 'Mazda1428');
if (!$cxn)
exit;
mysql_select_db('irgc', $cxn);
// check if we can get hold of the form field
if (!post('ID'))
exit;
// let make sure we escape the data
$val = mysql_real_escape_string(post('ID'), $cxn);
// lets setup our insert query
$sql = "UPDATE game SET sequence=".$val." WHERE id = 2;";
// lets run our query
$result = mysql_query($sql, $cxn);
// setup our response "object"
$resp = new stdClass();
$resp->success = false;
if($result) {
$resp->success = true;
}
print json_encode($resp);
?>
but when i open the browser and go in play.php and click in tictactoe game the first time is OK. but after that no thing will add in DB (but still i see the alert('success')).
finally,sorry for bad english.
disable cache and try again.
$.ajax({
type: "POST",
cache: false,
url: "gameProcess.php",
data: {
'ID' : path
},
dataType: "json",
success: function(){
alert('success');
},
});
Perhaps you should add a random URL address parameter
I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);
So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}
I have this php function inside a class the returns json data
function getPhotoDetails( $photoId ) {
$url = $this::APP_URL . 'media/' . $photoId . $this::APP_ID;
return $this->connectToApi($url);
}
and this ajax request
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php',
success: function (data) {
console.log(data);
}
});
}
The question is how I can call the php function to get the json data.
Solution:
A big thanks to all of you guys and thanks to Poonam
The right code
PHP:
I created a new object instance in php file
$photoDetail = new MyClass;
if(isset($_REQUEST['image_id'])){
$id = $_REQUEST['image_id'];
echo (($photoDetail->getPhotoDetails($id)));
}
JavaScript
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: './instagram.php?image_id=' + photoId,
success: function (data) {
var data = $.parseJSON(data);
console.log(data);
}
});
}
Try with setting some parameter to identify that details needs to send for e.g assuming photoid params needed for function
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php?sendPhoto=1&photoid=23',
success: function (data) {
console.log(data);
}
});
}
and then on index.php check (You can make check for photoid whatever you need as per requirement)
if(isset($_REQUEST['sendPhoto'])){
$id = $_REQUEST['photoid'];
return getPhotoDetails($id);
}
setup a switch-case. Pass the function name as GET or POST variable such that it calls the php function
You need a file which calls the PHP function. You can't just call PHP functions from Ajax. And as pointed out by Tim G, it needs to use the proper header, format the code as JSON, and echo the return value (if the function is not already doing these things).