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!
Related
I wrote a function to delete an item from cart; the success message flash, but the item is not getting deleted. There's no error message being flagged in the console. However I think my query is wrong.
cart.php
<form id='updateCartForm' action="update_cart.php" method="get">
<input name="cart_item_id" type = "hidden" id ="cart_item_id" value='<?=$product['id'];?>'>
</form>
<button class="btn btn-warning" onclick='update_cart(); return false;'>×</button>
footer.php
function update_cart(){
jQuery('#updateCartErrors').html("");
var cart_item_id = jQuery('#cart_item_id').val();
var error = ' ';
var data = jQuery('#updateCartForm').serialize();
jQuery.ajax({
url : '/ecommerce/customer/parsers/update_cart.php ',
method: 'get',
data : data,
success : function (){
location.reload();
},
error : function(){alert("Something went wrong");}
});
}
update_cart.php
<?php
ob_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/ecommerce/core/init.php';
$cart_item_id = $_GET['cart_item_id'];
$sql = "DELETE FROM cart WHERE id = $cart_item_id" ;
//flash success message
$domain =($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$_SESSION['success_flash'] = $product['prod_name']. ' was deleted from your cart.';
Please update code as given below and try :
$sql = "DELETE FROM cart WHERE id =" . $cart_item_id; // update this
$db->query($sql); //add this new line in code.
If any confusion please let me ask.
Thanks...
Can you try this?
I think you need to append value instead.
$sql = "DELETE FROM cart WHERE id =".$cart_item_id;
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
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;
});
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);
});