I am completely confused:
This is my php script "add_credits.php". It runs perfectly if I create a form and call it via method="post".
$stmt = "UPDATE sites SET credits=:credits WHERE id=:id";
$stmt = $db->prepare($stmt);
$stmt ->execute( array( ":credits" => $_POST['cred'], ":id" => $_POST['id'] ) );
This is my input field that triggers the jquery/ajax.
<input id="<?php echo $row['id']; ?>" type="text" class="credits" value="<?php echo $row['credits']; ?>" />
This is my jquery, which will echo eitther variable in an alert box correctly on success.
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = 'id=' + add_id;
var add_cred = $(this).attr("value");
var info2 = 'cred=' + add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {info:info, info2:info2},
success : function() {
alert(info2);
}
});
return true;
});
So why is it that its reporting success, yet no UPDATE is being performed, as if the php is not receiving the $_POST details? Am I missing something??
You don't have to manually serialize the data like that
$('.credits').on('input', function() {
var req = $.post('add_credits.php', {
info: $(this).attr('id'),
info2: $(this).attr('value')
});
req.done(function(res) {
console.log(res);
});
req.fail(function(err) {
console.error(err);
});
});
On the PHP side of things, make sure you're reading info and info2
// info and info2 were set in the POST request in the jQuery above
$info = $_POST['info'];
$info2 = $_POST['info2'];
do_something($info, $info2);
// respond in some way
header('content-type: application/json');
echo json_encode(['ok'=> true]);
You can name the fields id and cred if that's what you wish. That would change the jQuery data to this
var req = $.post('url', {
id: $(this).attr('id'),
cred: $(this).attr('value')
});
Then make sure you read $_POST['id'] and $_POST['cred'] in the PHP
Use the following jquery code:
$(".credits").bind('input', function() {
var add_id = $(this).attr("id");
var info = add_id;
var add_cred = $(this).attr("value");
var info2 = add_cred;
$.ajax({
type : "POST",
url : "add_credits.php", //add credits on enter php script
data : {id:info, cred:info2},
success : function() {
alert(info2);
}
});
return true;
});
Related
I want to add a javascript value to my php query. The code goes like this
<script>
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
<?php
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
})
</script>
I want to put the value of categoryName to the query which I made in php. How will I do it.
Just spend a few hours trying to figure this out myself today. You can use ajax, and send the information using the data tag in an ajax query.
$.ajax({ url: 'file goes here',
data: {action: '0'},
type: 'post',
success: function(output) { //action }
});
The data tag gives you the information.
In your php:
$data = $_POST["action"];
you should use ajax to get the attribute from your clicked div and send it to a php page where you receive the "javascript variable" and use it as a php variable with $_POST like this:
<script type="text/javascript">
$(function() {
$(document).on('click', '.dropdown-menu li a', function() {
{
var categoryname = $(this).attr("id");
var dataString = 'categoryname'+ categoryname ;
$.ajax({
type: "POST",
url: "yourphppage.php",
data: dataString,
cache: false,
success: function(html)
{
$(".result").html(html);
}
});
return false;
});
});
Now in your php page:
$categoryname=$_POST['categoryname'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = $categoryname
");
It doesn't go this way, unless you make AJAX calls (see http://api.jquery.com/jquery.get/ and other answers).
The simplest solution (if you do not have too many categories, say a few hundreds tops) would be to cache the categories client-side in a Javascript variable, as in:
<script type="text/javascript">
var categoriesCache = <?php
$cache = array();
$result = mysqli_query($con, "SELECT id, category_name FROM tb_category");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$cache[$row["category_name"]] = $row["id"];
}
echo json_encode($cache);
?>;
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
var categoryId = categoriesCache[categoryName];
});
</script>
<script>
$(document).on('click', '.dropdown-menu li a', function(e) {
e.preventDefault();
var categoryName = $(this).text();
// !! be careful here !! send web safe category name, `$(this).text();` or even better a numeric value.
$.get('runquery.php', {'category': encodeURIComponent(categoryName)}).done(function (data) {
// on success do something if needed
});
})
</script>
Put your PHP/SQL script in runquery.php
You can do this with Ajax
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Php-script in a separate File like:
First you JavaScript file:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName});
});
then you php-file.php looks like:
<?php
$categoryname = $_POST['cat_Name'];
$one = mysqli_query($con, "SELECT id FROM tb_category WHERE category_name = '?' ");
?>
if you want to use them again:
add to your PHP on the end:
$return = new array();
$return[0] = ;//your results in this array
echo json_encode($return);
then in your JavaScript should look like:
$(document).on('click', '.dropdown-menu li a', function() {
var categoryName = $(this).html();
$.post("php-file.php",{cat_Name: categoryName}, function(data){
sccess_function(data);}, "json");
});
then add a function:
function succsess_function(data){
//do thing here
}
So I'm trying to create a message system. When I click on the Message to open my template opens in the same page the message content. I'm trying to make like: "See" Button->ajax->replace with jquery .text("Blah Blah"). the problem is that when I try tod
HTML Code:
<form method="POST">
<button type="button" class="btn btn-small btn-success" name="msg_preview_id" value="'.$inbox_row['id'].'">New</button>
</form>
Jquery Ajax Form:
$(document).ready(function(){
$('button[name=msg_preview_id]').click(function(event) {
var formData = {'msg_preview_id' : $('button[name=msg_preview_id]').val()};
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../../class/messages/inbox_preview.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
.done(function(data) {
console.log(data);
//Email Stuff
$('h1[id=emailheading]').text(""+data.info.subject+"");
$('a[id=emailfrom]').text(""+data.info.from+"");
$('span[id=emaildate]').text(""+data.info.rcvdat+"");
$('p[id=emailtext]').text(""+data.info.text+"");
//Ceninhas
$('#inbox-wrapper').addClass('animated fadeOut');
$('#inbox-wrapper').hide();
$('#preview-email-wrapper').addClass('animated fadeIn ');
$('#preview-email-wrapper').show();
//$('.page-title').show();
//Load email details
$('#inbox-wrapper').removeClass('animated fadeOut');
$('#inbox-wrapper').removeClass('animated fadeIn');
});
event.preventDefault();
});
});
PHP:
<?php
include ('../../inc/config.inc.php');
$data = array();
$info = array();
$Msg_Preview_ID = $_POST['msg_preview_id'];
$MsgSQL = mysqli_query($Connection, "SELECT * FROM messages_inbox WHERE id='$Msg_Preview_ID'");
$Msg = mysqli_fetch_assoc($MsgSQL);
$bzQuery = mysqli_query($Connection, "SELECT * FROM members_profile WHERE id='".$Msg['from']."'");
$bzFetch = mysqli_fetch_assoc($bzQuery);
$info['from'] = $bzFetch['fname']." ".$bzFetch['lname'];
$info['subject'] = $Msg['subject'];
$info['text'] = $Msg['text'];
$info['rcvdat'] = $Msg['rcvdat'];
$data['info'] = $info;
echo json_encode($data);
I use $_GET[] in other pge it was easier!
Below is my ajax call code. I want to send one data in .php file via ajax call and want to get two values from .php file. This two values I want to set in different 'input' tags whose id are 'course_name' and 'course_credit'.
Here my ajax call return correct value(real value from DB table) of 'course_name' input tag.
But 'MY PROBLEM IS' the value of input tag whose id is 'course_credit' shows 'success'. How can I get the correct value(real value from DB table) of id 'course_credit' ?
I have a 'select' tag which id is 'c_select'
HTML:
<input type="text" name="course_name" id="course_name" value=""/>
<input type="text" name="course_credit" id="course_credit" value=""/>
AJAX :
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
});
});
get_course_info_db.php
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name,$c_credit;
exit();
?>
AJAX code:-
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
$('#course_name').val(data[0]);
$('#course_credit').val(data[1]);
}
});
});
PHP code:-
<?php
include('db_connection.php');
$c_id = $_POST['c_id'];
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
$c_name = $all_course_data['c_name'];
$c_credit = $all_course_data['c_credit'];
echo $c_name.",".$c_credit;
exit();
?>
The success callback is Function( PlainObject data, String textStatus, jqXHR jqXHR ); http://api.jquery.com/jQuery.ajax/
php:
$data = array(
'name' => $c_name,
'credit' => $c_credit,
);
echo json_encode($data);
javascript:
success: function(data) {
var result = $.parseJSON(data);
$('#course_name').val(result.name);
$('#course_credit').val(result.credit);
}
success: function(reply_data1,reply_data2){
$('#course_name').val(reply_data1);
$('#course_credit').val(reply_data2);
}
second arguement is the status of http request, you have to encode the answer, i suggest you JSON
in your php
$c_credit = $all_course_data['c_credit'];
echo json_encode(array('name' => $c_name,'credit' => $c_credit));
exit();
and in your javascript
success: function(response,status){
var datas = JSON.parse(response);
$('#course_name').val(datas.name);
$('#course_credit').val(data.credit);
}
this is not tested, but this is the way to do it
I'd suggest using JSON to encode the data you fetch from the database.
Try changing your ajax call as follows:
$('#c_select').change(function(){
$.ajax({
type:'post',
url:'get_course_info_db.php',
data: 'c_id='+ $(this).val(),
dataType: 'json', // jQuery will expect JSON and decode it for you
success: function(reply_data){
$('#course_name').val(reply_data['c_name']);
$('#course_credit').val(reply_data['c_credit']);
}
});
});
And your PHP as follows:
include('db_connection.php');
// Escape your input to prevent SQL injection!
$c_id = mysql_real_escape_string($_POST['c_id']);
$result = mysql_query("SELECT * FROM course WHERE c_id = '$c_id'");
$all_course_data = mysql_fetch_array($result);
echo json_encode($all_course_data);
exit();
I haven't tested this but I imagine it'd work for you.
In login.php on button click I execute redirect.php.
This redirect.php perform twitter authentication. For that it invokes some other file which in turn invokes index.php.
index.php gives result name and id, which I want to retrieve in index.php.
source code : Git source code
Currently what happens, login.php executes $.get() before response from login.php and alerts indefined value
login.php
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
//This function needs improvement i think, is this correct place for this to get json value from index.php??
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
redirect.php
<?php
/* Start session and load library. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
... //some other processing
?>
index.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$name = $content->{'name'};
$id = $content->{'id'};
echo json_encode((object) array('id' => $id, 'name' => $name)); //to retreive in login.php
?>
UPDATE
$.get('index.php', function(data) {
var user_id= data.id;
var name = data.name;
alert(name);
// alert(name);
window.location.href = 'button.php';
},"json");
since your php file is outputting a json string your get call needs to know that it is retriving such
$.get('index.php', function(data) {
var id= data.id;
var name = data.name;
alert(name);
},"json");
This will let jquery know that it needs to parse the incoming data as a json string and parse it to an object, otherwise you would have to do the parse yourself
$.get('index.php', function(data) {
data = JSON.parse(data);
var id= data.id;
var name = data.name;
alert(name);
});
Im new In AJAx. My problem is I have ajax Function to pass variable ID in php when the page is load the error is Undefined variable: id but when I look in firebug post id is past successfully . Here is my ajax.
$('.btn_edit').click(function(e){
e.preventDefault();
var $this = $(this);
var id_id = $(this).attr('id');
alert(id_id);
$.ajax({
type: "POST",
url: "edit_query.php",
data:{id: id_id},
success: function() {
alert("Success Input");
and this is my php page to pass.
$id = $_POST['id'];
$sql = mysql_query("select * from user where uid = ".$id."");
$table = mysql_fetch_assoc($sql);
?>
$sql = mysql_query("select * from user where uid = ".$id."");
should be
$sql = mysql_query("select * from user where uid = $id ");
and
var id_id = $(this).attr('id');
alert(id_id);
$.ajax({
type: "POST",
url: "edit_query.php",
data:"id="+id_id,
success: function() {
alert("Success Input");
}
try this
$.post( "edit_query.php", { id: id_id })
.done(function( data ) {
alert( data );
});
try this
edit_query.php
<?php
$id = $_POST['id'];
$sql = mysql_query('SELECT * FROM user WHERE uid = '.$id);
$row = mysql_fetch_assoc();
header('Content-Type: application/json');
echo json_encode($row);
exit;
your.js
$(function(){
var onClick, successHandler;
onClick = function (e) {
e.preventDefault();
$.post('edit_query.php',{id:$(this).attr('id')},successHandler,'json');
};
successHandler = function (json) {alert(json.uid);};
$('.btn_edit').click(onClick);
});