Use result of AJAX call for FullCalendarEvents? - javascript

I currently have this in my event drop:
$.ajax({
type: "POST",
url: "CalendarServices.aspx/UpdateDrop",
data: 'id=' + event.realid + '&start=' + $.fullCalendar.formatDate(event.start, 'yyyy-MM-dd') + '&resource=' + event.resource,
success: function(data) {
$('#calendar').fullCalendar('refetchEvents');
},
error: function() {
$('#calendar').fullCalendar('refetchEvents');
}
});
This is effectively 2 ajax calls. I could easily return events in my first ajax call and populate the calendar with them. Is there some way I could do that?
Thanks

This is what I used and it worked:
eventDrop: function(event,dayDelta,minuteDelta,allDay) {
var id = event.id.toString();
var start = $.fullCalendar.formatDate(event.start, "yyyy-MM-dd");
url = 'updateevent.php';
alert (url);
$.ajax({
type: "POST",
url: url,
data: {id:id, startDate:start},
success: function(){
$('#calendar').fullCalendar( 'refetchEvents' );
alert( "Success!" );
},
error: function(){
$('#calendar').fullCalendar( 'refetchEvents' );
alert( "Failed!" );
}
});
and this is my updateevent.php
<?php
//..... connection up top
$r = mysql_connect($host, $user, $pass);
$r2 = mysql_select_db($db);
$id = $_POST['id'];
$startDate = $_POST['startDate'];
mysql_query("UPDATE ecc_events SET startDate= '$startDate' WHERE id= '$id' LIMIT 1; ");
?>

Related

PHP not catching data from Ajax Jquery

Im trying to pass data from using Ajax and PHP on server side. the php file is not catching the data sent through Ajax.
the code gets the values with jquery and make a long string called data
the jquery code looks like this:
var data = 'ppemail=' + $('#email').val()
+ '&monto_enviar=' + montoEnviarDisp
+ '&monto_pub=' + montoPubDisp
+ '&tasa=' + tasaDisp
+ '&monto_recibir=' + monto_recibirDisp
+ '&banco=' + $('#banco').val()
+ '&receptor=' + $('#receptor').val()
+ '&cuenta=' + $('#cuenta').val()
+ '&cedula=' + $('#cedula').val();
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: ({data}),
success: function (response) {
alert(response);
}
});
the php file is this:
<?php
session_start();
require_once 'dbconfig3.php';
var_dump($_POST);
try {
$userID = $_SESSION['userSession'];
$ppemail = $_POST['ppemail'];
$monto_e = $_POST['monto_enviar'];
$monto_p = $_POST['monto_pub'];
$tasa = $_POST['tasa'];
$monto_rec = $_POST['monto_recibir'];
$banco = ($_POST['banco']);
$receptor = ($_POST['receptor']);
$cuenta = ($_POST['cuenta']);
$cedula = ($_POST['cedula']);
/// luego de confirmar hacer el try e insertar
//if(isset($_POST['btnferta'])){
//$password = md5($upass);
$bid_date = date('Y-m-d H:i:s');
$stmt = $db_con->prepare("INSERT INTO ofertas(uid,email_pp,nombre_receptor,banco_receptor,cuenta_receptor,cedula_receptor,monto_enviar,monto_publicar,tasa,monto_recibir,fecha)
VALUES(:userid, :emailpp, :nombre, :banco, :cuenta, :cedula, :monto_e, :monto_p, :tasa, :monto_r, :fecha)");
$stmt->bindParam(":userid", $userID);
$stmt->bindParam(":emailpp", $ppemail);
$stmt->bindParam(":nombre", $receptor);
$stmt->bindParam(":banco", $banco);
$stmt->bindParam(":cuenta", $cuenta);
$stmt->bindParam(":cedula", $cedula);
$stmt->bindParam(":monto_e", $monto_e);
$stmt->bindParam(":monto_p", $monto_p);
$stmt->bindParam(":tasa", $tasa);
$stmt->bindParam(":monto_r", $monto_rec);
$stmt->bindParam(":fecha", $bid_date);
$stmt->execute();
echo 'ok';
} catch (PDOException $ex) {
echo $ex->getMessage();
}
?>
why the $_POST is not getting any data? Thanks for the help!
You should set data to an object. This ensures that the URL parameters will be properly encoded; otherwise, you need to call encodeURIComponent on any parameter that could contain special characters.
var data = {
'ppemail': $('#email').val(),
'monto_enviar': montoEnviarDisp,
'monto_pub': montoPubDisp,
'tasa': tasaDisp,
'monto_recibir': monto_recibirDisp,
'banco': $('#banco').val(),
'receptor': $('#receptor').val(),
'cuenta': $('#cuenta').val(),
'cedula': $('#cedula').val()
};
Then you shouldn't wrap it in another object when calling $.ajax:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});
It looks like you're trying to pass a string as an object property. Change your $.ajax options:
$.ajax({
type: "POST",
url: 'crear_oferta.php',
data: data,
success: function(response) {
alert(response);
}
});

favorite button ajax

i have problem with my ajax code it didn't work i don't know why.
here is my code:
this php code is in other page that named favourite.php
i have problem with my ajax code it didn't work i don't know why.
here is my code:
this php code is in other page that named favourite.php
$test = $_SESSION['ww'];
$x = $_SESSION['x'];
$SelectQry2 = "select * from favorites where User_Id = ".$test." and User_Post = ".$x."";
$slc = mysqli_query($link , $SelectQry2);
if (mysqli_num_rows($slc)> 0){
$DeleteQry = "DELETE from favorites where User_Post = ".$x."";
$del = mysqli_query($link , $DeleteQry);
}else{
$url = $_SERVER['REQUEST_URI'];
$InsertQry = "insert into favorites";
$InsertQry .="(`User_Id` ,`User_post`, `url`) VALUES";
$InsertQry .=" ('$test' ,'$x', '$url')";
$fav = mysqli_query($link, $InsertQry);
}
$(document).ready(function(e){
e.preventDefault();
$("button").on("click", function(){
var data = $(this).serialize();
$.ajax({
type: "POST",
data: data,
url: "favourite.php",
success: function(data){
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
});
<button>favorite</button>

Retrieving each variable posted by AJAX

I am storing my checkbox selections in an array then splitting each array and posting them using AJAX so my PHP function can use the posted id/ids to query my MySQL database.
First part of my JavaScript
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
This first part works as intended, where every time I click a checkbox the value is alerted.
AJAX post
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
Finally my PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
I don't get any vlaues of tbl even if I choose just one option. Why is this????
EDIT
My Checkbox
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
SECOND EDIT
After suggestions I have amended my code but now have a new problem where the page doesn't load #dbdisplay Below is my full JS code
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
The old function
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
How do I fix this??
In ajax call, data has to be object data: {'tbl': tbl}
This should to the job
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
See here for documentation
First thing in your ajax call, data has to be object
data: {'tbl': tbl}
Secondly Ajax can't call php function directly
so your index.php file should be something like this without function
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
You should use "{ }" with data
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
or
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});

Ajax result show undefined

I want to ues ajax polling for show user update by followers like facebook.
So I collect this code and apply in my page, Which append only 'undefined' one after one.
What is my wrong here in my code please.
At below I give my full polling script and related file
my Table name: updateside
id - work_id - parent_id - from_id - to_id - sub - detail - img - created
..........................................................................
AI - work_id, parent_id etc. all data submit by user post form
My JavaScript
function waitForMsg(){
$.ajax({
type: "GET",
url: "upsidenew.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
if(data) {
$("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
}
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
upsidenew.php
$parent = //collect from other query
date_default_timezone_set('Asia/Dhaka');
$timestamp = date("M j, y; g:i a", time() - 2592000);
$u = mysqli_query($dbh,"SELECT * FROM updateside WHERE `parent_id`='".$parent."' AND `created` > '".$timestamp."' ORDER BY created DESC") or die(mysqli_error($dbh));
$response = array();
while ($row = mysqli_fetch_array($u)) {
$response['from_id'] = $row['from_id'];
$response['parent_id'] = $row['parent_id'];
$response['to_id'] = $row['to_id'];
$response['sub'] = $row['sub'];
$response['detail'] = $row['detail'];
$response['img'] = $row['img'];
$response['time'] = $row['created'];
?><script><?php echo '(Content-Type: application/json)';?></script><?php
echo json_encode($response);
exit;
}
Add your ajax request dataType as "dataType: 'json'"
$.ajax({
type: "GET",
url: "upsidenew.php",
async: true,
cache: false,
timeout:50000,
dataType: 'json'
success: function(data){
if(data) {
$("#updatetime").append('<div class="upbox1">' + data.detail + '</div>');
}
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
if you don't set the datatype of your ajax call explicity to json you need to parse the result with:
jsondata = $.parseJSON(data);
alert(jsondata.detail);
as shown in
http://api.jquery.com/jquery.ajax/
If you're returning JSON, you shouldn't output anything other than echo json_encode($response). This line:
?><script><?php echo '(Content-Type: application/json)';?></script><?php
should be:
header('Content-type: application/json');

return object get into a variable

I need to get object array into a variable which is return from controller,to the success function in the ajax function,I need to concatenate id to the site_url,
here is my code
view
<div id="abc"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> //no need to specify the language
$(document).ready(function() {
$('#myForm1').on("submit",function(e) {
//var form = $(this);
//dataString = $("#myForm1").serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('form_controller/insert_into_db'); ?>",
data: $(this).serialize(),
//dataType: "html",
success: function(data){
// top.location.href = "<?php echo site_url('form_controller/callform'); ?>";
//$.each(data.results, function(){
// $("#abc").append('<div><b>' + id.id + '</b></div><hr />');
//});
/*var site_url = "<?php// echo site_url('form_controller/callform/') ?>";
site_url = site_url +"/" + id;
$("#abc").load(site_url);*/
<?php //foreach(): ?>
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
site_url = site_url +"/" + "mydata" ;
//alert(mydata);
$("#abc").load(site_url);
$('#abc').html(data);
alert(data);
}//,
//error: function() { alert("Error posting feed."); }
});
});
});
</script>
here is my alert output
here I need to concatenate data as id for the site_url. here is my alert
[{"id":"215"}]
I need to get this as :
var id=215;
You can use JQuery for a parse JSON.
...
success: function(data){
...
var site_url = "<?php echo site_url('form_controller/callform'); ?>";
var mydata=window.JSON.stringify(data.trim());
var jobj=jQuery.parseJSON(data.responseText); //<---JSON to object
site_url = site_url +"/" + jobj.id ; //<--- jobj.id - your id
....
Set datatype to "json" and use data.id
dataType
Type: String
The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, text, html).

Categories