hello i want to get text from textarea and register in database but not work where is problem thanks all. $get_text show empty value.
<script type="text/javascript">
$(function() {
$(".new_post").click(function(){
var get_text = $("#post_text").val();
$.ajax({
type: "POST",
url: "ajax/ajax_new_post.php",
data: get_text,
success: function() {
alert(get_text);
$('#post_text').val('');
//$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
//.animate({ opacity: "hide" }, "slow");
}
});
return false;
});
});
</script>
<body>
<textarea id="post_text" placeholder="What's on your mind?"></textarea>
</body>
ajax_new_post.php
$get_text = $_GET['get_text'];
mysqli_query($Connection, "INSERT INTO posts VALUES('$ID', '$get_text')");
You are missing key. Change your data to:
data: { get_text : $("#post_text").val() },
And your type is POST, so use $_POST['get_text'] in PHP file.
You are using post method . So use $_POST['get_text'];
The problem is that you are making a POST and trying to get the value as GET.
Use :
$get_text = $_POST['get_text'];
mysqli_query($Connection, "INSERT INTO posts VALUES('$ID', '$get_text')");
Use jQuery to send a JavaScript variable to your PHP file:
'$url = 'path/to/phpFile.php';
$.get($url, {name: get_name(), job: get_job()});'
In your PHP code, get your variables from $_GET['name'] and $_GET['job'] like this:
<?php
$buffer_data['name'] = $_GET['name'];
$buffer_data['job'] = $_GET['job'];
?>
Related
I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)
Using ajax, I'm trying to display what is being typed in the text box, but it's not displaying anything at all for some reason. I know the ajax function itself got called, by using alert inside the function, and I think the real problem is actually in test2.php, but I'm not sure what I did wrong. Please take a look:
test1.php
<?php
include('ajax.php');
echo "<input type = 'text' name = 'select' onkeyup = 'ajax(\"test2.php\",\"select\",\"output\")'>";
echo "<div id = 'output'/>";
?>
test2
<?php
$select = $_POST['select'];
echo $select;
?>
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,select,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $('select[name="select"]').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
function ajax(url,unused,id) {
$.post(url,{select: $('input[name="select"]').val()})
.error(function(e){
alert(e);
})
.success(function(d){
$("#"+id).text(d);
});
}
The problem is here:
data: {select: $('select[name="select"]').val()},
There is no select element. And if you meant to get the id named element, then you need to change it to:
data: {select: $('#select[name="select"]').val()},
or in your case:
data: {select: $('input[name="select"]').val()},
Please check my code in the following:
PHP & HTML Code(file1.php):
<?php
$conn = //connected to db successfully.
$sql = "SELECT t1.column1 AS Column_1 FROM table1 t1";
$rs = mysqli_query($conn,$sql);
$rows= mysqli_fetch_assoc($rs);
do{
?>
<button data-id="<?php echo $rows['Column_1']; ?>" type="button" onclick="handle_item('id')">Click Me</button> <br>
<?php }while($rows = mysqli_fetch_assoc($rs)); ?>
jQuery AJAX code(file1.php):
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data: {
'button_id': c
},
success: function (data) {
alert(data);
}
});
}
</script>
PHP Code(handle_input.php):
<?php
echo "Button with id ".$_POST['item_id]." clicked!";
?>
Now the problems is (as you might expect) the infamous error in this case, "undefined index: button_id" error. I receive it as an alert error when I click on one of the buttons. I've already read the duplicate questions on SO but unfortunately none of those I read could resolve my problem. I appreciate your guiding me with this.
Besides, as you see from my codes, I'm fetching several button from database and while displaying, I assign each one a data-id and use that data-id in ajax to use in 'handle_input.php' and I want to receive each button id which I've clicked on. Thanks in advance.
UPDATE:
It's been a while since I've asked this question but I've been curios about something in my question:
Why doesn't the array mode(data: {"button_id":c}) work for me in the $.ajax function(which leads to undefined index error for the $_POST variable) whereas the string mode(data: "usg_id="+c) does?
You're sending:
button_id:..
but you're using, also with a missing '
$_POST['item_id]
change to:
$_POST["button_id"]
UPDATE
Add this as first parameter:
onclick="handle_item(this, 'id')"
Then, changehandle_item function as this:
function handle_item(obj,item_id) {
var c = $(obj).data(item_id);
<script type="text/javascript">
var item_id;
function handle_item(item_id) {
var c = $(this).data(item_id);
$.ajax({
url: 'handle_input.php',
type: 'POST',
data:"item_id="+c,
success: function (data) {
alert(data);
}
});
}
</script>
There is no button_id defined in you function hence the error.
Also in handle_input you are fetching item_id
I would like to know how I can pass a Javascript array from Javascript to PHP through Jquery/Ajax. In fact I created two files: t1.html and moslem3.php . The code of each file is below:
The code of t1.html:
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: table
});
});
</script>
</body>
</html>
The code of moslem3.php:
<?php
$myArray = $_REQUEST['table'];
echo $myArray;
?>
The file moslem3.php displays this message:
Notice: Undefined index: table in C:\wamp\www\test1\moslem3.php on line 2
So my question is: where is the wrong here exactly?..Is there any one who has any idea?
Thanks in advance.
PHP doesn't inherently know anything about the JavaScript variables being used, such as var table. Its insights for the $.ajax() request are completed limited to the data structure.
So, for PHP to know about a 'table' parameter in $_REQUEST, the data needs to include it that as a named value:
data: { table: table }
This defines the data as an Object with a property table assigned to the value of the variable by the same name.
You can witness the difference using $.param(), which $.ajax() uses:
var table = ["actor", "subject", "object"];
console.log($.param(table));
// "undefined=&undefined=&undefined="
console.log($.param({ table: table }));
// "table%5B%5D=actor&table%5B%5D=subject&table%5B%5D=object"
Change Jquery
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: {t_name:table },
success:function(data){
console.log(data);
}
});
});
</script>
Change in moslem3.php
<?php
$myArray = $_REQUEST['t_name'];
print_r($myArray);
?>
Output:
Try this :
$.ajax({
type : "POST",
url: 'moslem3.php',
cache:false,
async:true,
global:false,
data : {
"table": table }
}).done(function(msg) {
alert(msg);
})
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
{
}
?>