How to pass a form value and also user id into ajax?
javascript:
jQuery("#DoneBtn").click(function(){
var data = $("#insertsubs_form").serialize();
<?php
$db = JFactory::getDBO();
$user = JFactory::getUser();
?>
var userid = <?php echo $user->id; ?>
$.ajax({
data: {
data:data,
userid : userid
},
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
});
});
in insert_subs.php:
$userid = $_GET['userid'];
**** APPRECIATED Anand Patel, Deena. Both are the same answers that I want! :D Also thanks to epascarello! I didnt try this but I think is working as well. :)
try this
jQuery("#DoneBtn").click(function(){
<?php
$db = JFactory::getDBO();
$user = JFactory::getUser();
?>
var userid = <?php echo $user->id; ?>;
var data = $("#insertsubs_form").serialize() + "&userid=" + userid;
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
});
})
Try this...
var userid = <?php echo $user->id; ?>
$.ajax({
type : 'POST',
url : '../insert_subs.php',
data : $('#form').serialize() + "&userid=userid"
});
Try using serializeArray:
var data = $('#insertsubs_form').serializeArray();
data.push({name: 'userid', value: userid });
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
or you can use serializeObject
var data = $('#insertsubs_form').serializeObject();
$.extend(data, {'userid': userid });
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
or you can use serialize and param
var data = $('#form').serialize() + $.param({"userid":userid});
$.ajax({
data: data,
type: "post",
url: "../insert_subs.php",
success: function(data){
alert(data);
}
or the best solution just add a hidden field in the form with the user id and use serialize!
<input name="userid" type="hidden" value="<?php echo $user->id; ?>" />
Related
I've been trying to send this information to the js.
$statement = ibase_prepare($sql);
$query = ibase_execute($statement);
while ($row = ibase_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
However, when I try to, I get the response, but I can't get the data.
$('document').ready(function (){
$.ajax({
method: "POST",
url: "../Dashboard/php/chart.php",
dataType: "json",
sucess: function (data){
console.log(JSON.stringify(data));
}
});
})
You just have a grammatical error in a word "sucess", the correct word is "success"
$.ajax({
method: "POST",
url: "./data.php",
dataType: "json",
sucess: function (data){ // Here -> success
alert(JSON.stringify(data));
}
});
I'm trying to make a login through Facebook, in the console it shows that I'm getting the requested data (email, first_name ...) but ajax keeps sending null data to the PHP method.
here's the ajax code:
function saveUserData() {
FB.api('/me?fields=id,first_name,last_name,email', function(response){
$.ajax({
url: '<?php echo base_url();?>Auth/fb_auth',
data: {response: JSON.stringify(response)},
type: 'POST',
dataType: 'json',
success: function (data) {
if(data['state'] == 'ok'){
window.location.href ="<?php echo base_url(); ?>";
}
}
});
});
}
and this is how I get the data in the method:
$response = json_decode($this->input->post('response'), true);
You donĀ“t need to stringify stuff with $.ajax, it does that for you. Also, you can use $.post instead:
function saveUserData() {
FB.api('/me?fields=id,first_name,last_name,email', function(response){
$.post({
url: '<?php echo base_url();?>Auth/fb_auth',
data: response,
dataType: 'json',
success: function (data) {
if(data['state'] === 'ok'){
window.location.href ="<?php echo base_url(); ?>";
}
}
});
});
}
This is probably very simply but I cannot figure it out. I am using a jquery script I found to display a timer. I then want to send the number of seconds to a PHP file. Below is the script, if I just alert the value variable, it contains the correct data, so I am accessing it correctly but its empty on the PHP side when it arrives.
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
The result alert displays empty based on this test php file
<?php
if (isset($_POST['value'])) {
$value = $_POST['value'];
echo $value;
} else {
$value = "Empty!";
echo $value;
}
?>
I would really appreciate some help.
I thought you must add a header to Ajax object.
edits :
change var name
check URL address
add header
$('.get-timer-btn').on('click', function() {
//change this name !
var value_data = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php', //make sure correct address
headers: {'Accept': 'application/json'}, //add header is so important
data: { value : value_data },
cache: false,
success: function(result){
alert(result);
}
});
});
You must end php hier is a worked example:
<?php
if(isset($_POST['value'])){
$value = $_POST['value'];
echo ($value)?$value:'Empty';
die;}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p class="timer" data-seconds="2"></p>
<button class="get-timer-btn">BTN</button>
<script>
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
</script>
I have created a JavaScript file as a PHP file in my CodeIgniter views so that I can access some of my PHP dynamic variable in JavaScript.
For example:
$.ajax({
url: "<?php echo base_url('loginpage'); ?>",
type: 'POST',
data: {emailId:email1,password:pwd1},
success: function(result){
Is this OK?
It is perfectly alright , I am using this in a professional project
var base_url = '<?php echo base_url(); ?>';
$(document).ready(function(){
$('#searchCategory').change(function(){
var id = $('#searchCategory').val();
$.ajax({
type: "POST",
url: base_url+"home/getSubCategory",
data: {id:id},
success: function(data) {
$("#sub_category").html(data);
}
});
});
});
Yes it is ok.
For Eg:
$.ajax
({
type:"POST",
url:"<?php echo base_url(); ?>staff_activity/date_report",
data:'year='+nep_year+'&month='+nep_month,
success:function(msg)
{
$('#result').html(msg);
},
beforeSend:function(d)
{
$('#result').html("<center style='color:red;'>Please Wait......</center>");
}
});
Here's my java script file:
$('#addSchoolForm').trigger("reset");
//$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen: false,
maxWidth:600,
maxHeight: 350,
width: 500,
height: 300,
});
$("#addSchool").on("click", function() {
$("#dialog").dialog("open");
});
$("#addSchoolForm").submit(function(e) {
e.preventDefault();
$("#dialog").dialog("close")
var postData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "AddSchools.php",
data: postData,
success: function(data){
alert(data); }
});
});
$("#editSchool").submit(function(e) {
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "GetSchoolID.php",
data: editData,
dataType: 'json',
success: function(data){
var schoolID = $.parseJSON(data);
alert("success");
alert(schoolID.name);
//alert(data["json"]);
//alert(data);
//document.addSchoolForm[sname].value = data[0].name;
//document.addSchoolForm[abbrev].value = data[abbrev];
//document.addSchoolForm[abbrev].value = data[0].abbrev;
}
alert(schoolID.name);
});
//$("#dialog").dialog("open");
});
})
And here's my get schoolID php file
<?php
$school_id = $_POST['school_id'];
$db = mysqli_connect("localhost", "root", "imagroup123","mytrack");
if(!$db){
exit("Error in database connection");
echo("couldn't connect to database");
}
else{
$q = "SELECT * FROM `School` WHERE `SchoolID`='$school_id'";
$schoolresults = mysqli_query($db,$q);
$row = mysqli_fetch_assoc($schoolresults);
$school["name"] = $row['SchoolLong'];
$school["abbrev"] = $row['SchoolShort'];
echo json_encode($school);
}
?>
When I just tested the php file with jsonlint.com I get a correct json object but it's not getting carried through the javascript file. I'm fairly new to this so I'm pretty suck with this problem. I also want to add the data to a form values and then open the dialog form after.
Change:
success: function(data){
var schoolID = $.parseJSON(data);
to:
success: function(schoolID){
because $.ajax automatically calls $.parseJSON() when you specify dataType: 'json'.
Here is the php backend structure that I use all the time:
$query = " SELECT *
FROM school
WHERE SchoolID = $school_id;
$result = mysqli_query($cxn, $query) or die ("could not query database 1");
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result);
$variablestopass = array
(
'schoolname' => $row['SchoolLong'],
'schoolabbrev' => $row['SchoolShort'],
);
echo json_encode($variablestopass);}
else
{ echo "Error selection id"; }
And here is some js to call it and read it:
$.ajax({
type: 'POST',
url: 'thenameofyourfile.php';
data: {schoolid: schoolid},
dataType: 'json'
})
.done( function() { alert( "Got it!"" );
Do other stuff here
})
.fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR.responseText, textStatus, errorThrown);
});