I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
Data1
Data2
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
You are not using the data as mentioned in the other answers:success: function(data){
$("#someid").html(data);
},
You are not cancelling the default click action so your link will be followed:$('a[class="some-class"]').click(function(e){
e.preventDefault();
...;
As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:data: {"id": somedata},;
You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:$data = (int) $_POST['id'];;
As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }
Related
So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.
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);
I created this script to read from various web sources. This script updates all notifications (mail, post, friends) and their own drop-down window's details and also two side update bars together. I used this script in my top manu.php page.
This script is working well for login user.
Now I pass a session id variable with JavaScript var uid = '<? echo $session->id; ?>'; So when a user is not logged in, my browser console displays 500 Internal Server Error because here the session has no ID so it passes uid= ''
How do I overcome this problem?
Here is my JavaScript script:
var uid = '<? echo $session->id; ?>';
function addmailno(type, msg){
//Do something for display mail/friend/post notification
}
function addmailup(type, msg){
//Do something for display mail/post/friend drop-down.
}
function addside(type, msg){
//Do something for display all friend/new post in side bar.
}
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
setTimeout(waitFormailno, 15000);
},
error: function(){
setTimeout(waitFormailno, 15000);
}
});
}
$(document).ready(function(){
waitFormailno();
});
serverforupandside.php
<?php
include("db.php");
include_once("mysession.php");
while (true) {
if($_GET['uid']){
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
flush();
mysqli_close($dbh);
}
}
mysqli_close($dbh);
}
?>
Your Javascript code should be modified to:
function waitFormailno(){
$.ajax({
type: "GET",
url: "serverforupandside.php",
cache: false,
async : false,
dataType : 'json',
data: "uid="+ uid,
timeout:15000,
success: function(data){
addmailno("MyDivClass", data);
addmailup("MyDivClass", data);
addside("MyDivId", data);
}
});
}
$(document).ready(function(){
setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});
PHP Code:
<?php
include("db.php");
include_once("mysession.php");
if (!empty($_GET['uid'])) {
global $dbh;
//All php query is here one after one
//Output is here by data
$data = array();
$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all
if (!empty($data)) {
echo json_encode($data);
}
}
Also, you should add validations before filling $data array.
I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.
I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>