I have the following script:
$("#spid").blur(function() {
$.ajax({
url: 'getsponsor.php',
type: "POST",
dataType:'json',
data: ({ spid: $("#spid").val() }) ,
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#sponname").text(result);
},
error: function () {
$("#sponname").text("Cannot fetch the sponsor name.");
}
});
});
Note: #sponname is a label tag.
Following is the php code of getsponsor.php:
if(!isset($_POST['spid']) || empty($_POST['spid']))
echo json_encode("No Data");
else {
$spid=$_POST['spid'];
$stmt = $con->prepare("SELECT name FROM users WHERE id=?");
$stmt->bind_param("s",$spid);
$stmt->execute();
$stmt = $stmt->get_result();
if ($stmt->num_rows >0) {
$row = $stmt->fetch_object();
echo json_encode($row->name);
}
else {
echo json_encode("No Records");
}
}
When I Inspect the page and goto Network->Params, I get the right value from the textbox:
spid=1125468
But, when I go to Network->Response, I get the following message
"No Data"
Please tell what wrong I am doing?
Get rid of this line:
contentType: 'application/json; charset=utf-8',
The data is being sent URL-encoded, not as JSON. jQuery will send the correct Content-type header by itself.
Related
So i have this jQuery:
$("#dropbin").droppable(
{
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
and that includes this url: url: 'deleteNote.php',
in deleteNote.php:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid']))
{
// $noteid2 = $_POST['noteid1'];
echo "You finally hit this bit, congratulations...";
// $stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
// $params = $noteid2;
// $stmt = sqlsrv_query($conn, $stmt, $params);
// if ($stmt === false)
// {
// die( print_r(sqlsrv_errors(), true));
// }
}
else
{
echo "No Data";
}
?>
Now even in the URL if i run /deleteNote.php?noteid=25 it hits the "No Data" part of my PHP.
When i run in debugger it populates the variable noteid with a NoteID so that bit is working but the PHP file is saying its not set?
Let's look in your Ajax call:
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
Looks nice, but you are sending post data with no id, you're just sending a value. Try this instead.
$.ajax({
type: 'POST',
data: {
noteid: noteid
},
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
I tried everything but it still don't work.
Without $_POST value it is working, without JSON it's working, with both it's not.
Function shows this error:
<b>Notice</b>: Undefined index: someVar1 in <b>C:\xampp\htdocs\ajax3\test.php</b> on line <b>2</b><br />
Array()
{"jeden":"Po obr\u00f3bce 123 123 ","dwa":null}"
script.js
$(document).ready(function(){
var data = {
someVar1: '123'
};
data = JSON.stringify(data);
$.ajax({
method: "POST",
url: "test.php",
dataType : 'json',
contentType: "application/json; charset=utf-8",
data: data,
success: function(json) {
$.each(json, function(i, ob) {
console.log(i, ob);
});
},
error: function(error) {
console.log(error);
}
});
});
and test.php
<?php
$someVar1 = $_POST['someVar1'];
$a = " 123 ";
$result = array();
$result['jeden'] = 'Po obróbce ' . $a . $a;
$result['dwa'] = $someVar1;
echo json_encode($result);
?>
It because you send data in JSON format. $_POST will be empty always
In this case you need to use I/O stream
Try this
$postData = json_decode(file_get_content('php://input'));
look more http://php.net/manual/en/wrappers.php.php
I have a javascript that sends an array through AJAX to a server side PHP script.
I am attaching relevant code snippets of my javascript AJAX function below:
$.ajax({
url: "bar2.php",
type: "POST",
data:{data:x},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(xhr, status, error) {
console.log(status);console.log(error);
},
success:function(data){
//do stuff
}
}
);
x is my array which I am sending.
I access this array in my PHP script as shown below:
$data = $_REQUEST['data'];
$len = $data.length;
$x=format_array($data);
function format_array($data){
return "'" . implode("', '", $data) . "'";
}
$myquery = "
select state,count(device_id) as c_num from base_data where state
IN($x)group by state order by c_num DESC limit 10;
";
$query = mysql_query($myquery);
But when I run it I get the error:
Warning: implode(): Invalid arguments passed in **** on line 16
Please help. I have spent an hour on this and am not able to figure it out. Am I sending the data in the correct way?
Any pointers would be appreciated.
You need to convert your array to JSON then send it to PHP (server side):
$.ajax({
url: "bar2.php",
type: "POST",
data: {data: JSON.stringify(x)},
dataType: "json",
contentType: "application/json; charset=utf-8",
error: function(xhr, status, error) {
console.log(status);console.log(error);
},
success:function(data){
//do stuff
}
});
PHP:
$data = json_decode($_REQUEST['data']);
$len = count($data);
//.....
//.....
Remove contentType: "application/json; charset=utf-8", and you will receive as array of form encoded data (application/x-www-form-urlencoded) which is $.ajax default
Also use count() instead of length in php
Okay now i am having a weird issue here, sometime back i learned how to encode and decode a json array properly here on stackoverflow but now i am having a weird issue on my godaddy server that i cannot comprehend, maybe i may have made i typo or something somewhere in code but i honestly cannot tell what is wrong here. The code works okay on my localhost but not when i upload it too my godaddy server.
The code here is basically supposed to pass an id as a json to the php server which is then supposed to execute a query using the id as a parameter.
Here is the jquery code:
<script text="text/javascript">
$(document).ready(function() {
$('#download').click(function(e) {
// e.preventDefault();
var tid = $('#id').val().trim();
var data = {
ID:tid
};
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
}
});
});
});
</script>
and this is the php code:
<?php
if (isset($_POST['data']))
{
$Data = $_POST["data"];
$arr = json_decode($Data);
$id = $arr->ID;
$sql = $pdo->prepare("update ********** set ******** = ******** + 1 where id=:id");
$sql->bindValue("id", $id, PDO::PARAM_INT);
$sql->execute();
unset($_POST['data']);
}
?>
Now i checked if the value was being sent to the server using my browser console and it was. I also checked if the $_POST['data'] on the server contained any data using var_dump and it did in fact have the data i wanted.
in the ajax set the content type to contentType: "application/json",
so:
$.ajax({
type: "POST",
url: "xxxxx-xxxxxxx.php",
data: {
data: JSON.stringify(data)
},
contentType: "application/json",
success: function(response) {
}
});
and in the php use:
$json = file_get_contents('php://input');
$data = json_decode($json);
I've got a game which refreshes info every 10 seconds from a MySQL database. There will be a JS function which is called each time this happens. I can't get the success function to execute, and I have no idea why. No errors on the console, either.
Javascript:
function refreshStats() {
console.log("number 1");
$.ajax({
url: "refreshData.php",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType : 'json',
data: { },
cache: false,
async: true,
success: function (msg) {
if(msg){
console.log("number 2");
var arr = JSON.parse(msg);
document.getElementById("interface_stats").innerHTML =
"Fatigue: " + arr[0];
}
}
});
}
PHP:
<?php
$username = $_POST['user'];
ini_set('display_errors', 1);
error_reporting(E_ALL);
$con = mysql_connect("localhost","redacted","redacted");
if (!$con)
{
die('SQL error! Aborting: ' . mysql_error($con));
}
$db = mysql_select_db("aftertheend",$con) or die("Database error! Aborting. Inform the admin.");
$query = "SELECT fatigue, food, water, radiation, condition FROM users WHERE username='TheMightyThor'";
$result = mysql_query($query, $con);
$data = mysql_fetch_row($result);
$stats = [
"fatigue" => $data[0],
"food" => $data[1],
"water" => $data[2],
"radiation" => $data[3],
"condition" => $data[4]
];
echo json_encode($stats);
?>
I think your PHP is returning an error, rather than the JSON you are expecting. Since you have dataType: 'json', jQuery attempts to parse the response, but fails. When that happens, jQuery does not call the success callback.
If you can, use Firebug to see what is being returned by the ajax call. Another way would be to temporarily change to dataType: 'html' and then change your success callback to:
success: function(msg) { alert(msg); }
Hopefully when you see the message being returned, it will help identify the problem. One thing you should do though, is add code to handle the cases where the query fails to execute and where no row is fetched from the database. You could add the following code to the PHP file:
$result = mysql_query($query, $con);
if (!$result) {
die('Could not run query: ' . mysql_error($con));
}
if (mysql_num_rows($result) < 1) {
echo 'null';
exit;
}
$data = mysql_fetch_row($result);
There are also a few issues with the Ajax call though:
(1) You are specifying contentType: "application/json; charset=utf-8", but then you are not sending JSON. You should do something like this:
data: JSON.stringify({}),
But if you do this, you cannot get the data on the server using the $_POST function. Therefore, you might want to get rid of the contentType setting instead. See this SO answer for more information.
(2) When you specify dataType: 'json', JQuery will parse the response to an object before calling the success callback, so the msg parameter should already be an object. Therefore, you should not call JSON.parse(msg).
(3) You are returning an associative array from the PHP file. That will be converted to a JavaScript object, not an array.
I think you should try the following:
$.ajax('refreshData.php', {
type: 'post',
dataType: 'json',
data: { },
cache: false,
success: function (data) {
if (data) {
$('#interface_stats').html('Fatigue: ' + data.fatigue);
}
}
});