I would like to parse through parameters with ajax... is that at all possible? If so, how could I go about that?
HTML/JS
<script>
function myAjax() {
$.ajax({
type: "POST",
url: '/ajax.php',
data:{action:'follow'},
success: function() {
console.log("called");
}
});
}
</script>
<button type='button' name='follow' id='follow' onclick='myAjax()'>Follow #<?php echo $profile ?></button>
ajax.php:
session_start();
require_once 'init.php';
if($_POST['action'] == 'follow') {
User::follow($conn, $_SESSION["name"], $profile);
// $conn is a db connection, $profile is the param I would like to parse through
} else {
echo 'no req';
}
function myAjax(obj) {
$.ajax({
type: "POST",
url: '/ajax.php',
data:obj,
success: function() { console.log("called"); }
});
}
Use like this:
myAjax({action:" follow",id:1234});
Related
So i have this jQuery:
$("#dropbin").droppable(
{
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
and that includes this url: url: 'deleteNote.php',
in deleteNote.php:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid']))
{
// $noteid2 = $_POST['noteid1'];
echo "You finally hit this bit, congratulations...";
// $stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
// $params = $noteid2;
// $stmt = sqlsrv_query($conn, $stmt, $params);
// if ($stmt === false)
// {
// die( print_r(sqlsrv_errors(), true));
// }
}
else
{
echo "No Data";
}
?>
Now even in the URL if i run /deleteNote.php?noteid=25 it hits the "No Data" part of my PHP.
When i run in debugger it populates the variable noteid with a NoteID so that bit is working but the PHP file is saying its not set?
Let's look in your Ajax call:
$.ajax({
type: 'POST',
data: noteid,
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
Looks nice, but you are sending post data with no id, you're just sending a value. Try this instead.
$.ajax({
type: 'POST',
data: {
noteid: noteid
},
datatype: 'json',
url: 'deleteNote.php',
success: function(result)
{
alert("Success");
}
});
Ok I have a following HTML, AJAX and PHP script below. I want to get the $deduct value to update <span id="mywallet"></div> field when the AJAX request is processed. How can I do so?
Example Form
<form>
<span id="mywallet">$<?php echo $wallet; ?></span>
</form>
Example flip-process.php structure
<?php
if($_POST){
//process everything
$deduct = (something calculated);
if(success){
$msg = "success";
}else{
$msg = "fail";
}
}
echo $msg;
?>
Ajax Script
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
$.ajax({
type: "POST",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#process-flipping").hide();
$(".coin-flip").show();
},
success: function(html){
setTimeout(function(){
$(".message").html(html).fadeIn();
$("#process-flipping").show();
$(".coin-flip").hide();
},3000);
}
});
return false;
});
});
Yes, json is the best solution:
<?php
if($_POST){
//process everything
$deduct = (something calculated);
if(success){
$msg = "success";
}else{
$msg = "fail";
}
echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
and the ajax success:
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$("#process-flipping").show();
$(".coin-flip").hide();
},3000);
if(json.status == 'success')
$('#mywallet').html('$' + json.deduct);
}
The best way to do that is to use json
PHP
<?php
$response = [];
if($_POST){
//process everything
$deduct = (something calculated);
if(success){
$response["deduct"] = $deduct;
}else{
$response["msg"] = "your message here";
}
}
header("Content-type:application/json; charset: UTF-8");
echo json_encode($response);
?>
JS
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
$.ajax({
type: "POST",
dataType : "json",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#process-flipping").hide();
$(".coin-flip").show();
},
success: function(json){
//json.deduct will has the value you want
}
});
return false;
});
});
This is my ajax function
$(function(){
$("#myform").submit(function(){ //i want to get data from my form after submittingit
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
success: function(data){
alert(data);
}
});
return false;
});
});
this is my controller class function
function viewCustomerData(){
if($_POST){
$name = $_POST['name'];
return 'name';
}
else {
return false;
}
}
other thing is i tried to alert data string taken from form serialize, but it also empty. I want to return data set from database after sending key word from javascript file. i tried if the javascript file connect correctly with my controller function. so i tried to return some value and display it using alert box. but it gives empty result.
This is better way to submit a form with ajax
$(document).on("submit", "#myform", function(event)
{
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData"
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
alert(data);
},
error: function (xhr, desc, err)
{
}
});
});
try this
$(function(){
$("#myform").submit(function(){
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
cache: false,
datatype: 'json',
success: function(data){
alert(data.result);
}
});
});
});
in controller
function viewCustomerData(){
if($this->input->post('name'){
$result = $this->input->post('name');
} else {
$result = false;
}
header('Content-Type: application/json');
echo json_encode(array('result' => $result));
}
you cant alert $("#myform").serialize(); because this is an object instead of alert it try console.log($("#myform").serialize();)
then open browser console and see what is printed
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data);
}
});
i am having problems with $_POST["var"] on controller. It seems to be empty. How can i receive the string being typed on my textFiled?
View
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
<script type="text/javascript">
$(document).ready(function(){
$("#hhmm").change(function(){
$.ajax({
url: "<?php echo CController::createUrl('reqTest01Loading'); ?>",
data: $(this).serialize(),
type: "post",
dataType: "json",
success: function(data) {
if (data.status === 'failure') {
$('#impatto').val('Error request failed.');
} else {
$("#impatto").html(data.total);
}
}
});
});
});
</script>
Controller
public function actionReqTest01Loading() {
$result = array("total" => $_POST['hhmm'], "status"=>"OK");
echo CJSON::encode($result);
}
rules on Controller
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('reqTest01Loading','index','view','admin'),
'users'=>array('#'),
),
thanks in advance
This is because you dont tell ajax call to send parameters.
Try:
$.ajax({
url: "<?php echo CController::createUrl('reqTest01Loading'); ?>",
data: {data:$(this).serialize()},
type: "post",
dataType: "json",
success: function(data) {
if (data.status === 'failure') {
$('#impatto').val('Error request failed.');
} else {
$("#impatto").html(data.total);
}
}
});
And it controller:
public function actionReqTest01Loading() {
// var_dump(Yii::app()->request->getPost('data'));
$result = array("total" => Yii::app()->request->getPost('data'), "status"=>"OK");
echo CJSON::encode($result);
}
i have a div that list all the uploaded files
$i = 0;
echo '<div style="float: left;margin-left: 25px;" id="filecontainer">';
echo "<ul>";
foreach($editorderdata['uploadedfiles'] as $row){
echo '<li>';
echo '<a href="'.base_url().'images/userfiles/'.$row['filename'].'" target="_blank">';
echo 'file_'.++$i.'</a>';
echo '<a href="#" data-fileid="'.$row['filename'].'" title="Remove file" class="removefile">';
echo '<img class="cross" src="'.base_url().'images/cross.png">';
echo '</a></li>';
}
echo "</ul>";
echo "</div>";
and this is the code to delete the selected file on pressing the .removefile class element
$(document).ready(function() {
$(".removefile").click(function(e) {
e.preventDefault();
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
$(this).closest("li").remove();
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
return false;
});
});
the code is working fine but what i want is to delete the parent li on ajax success which is not working.. help?
The problem you have is that $(this) in your success handler is not equal to the element which was clicked on. Try this:
$(".removefile").click(function(e) {
e.preventDefault();
var $btn = $(this); // <- save the clicked button to a variable
var fileidvar = $btn.data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data: { fileid: fileidvar },
dataType: 'json',
success: function (data) {
if (data.value) {
alert(data.value);
$btn.closest("li").remove(); // <- use cached selector here
}
},
error: function() {
alert("Something went wrong, please try again.");
}
});
}
return false;
});
Try it like,
if (confirm("Are you sure you want to remove selected file?")) {
var self=this;// make a copy of this to self and use it in ajax function
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
$(self).closest("li").remove();// use self in place of this
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
Try like this.
$(".removefile").click(function(e) {
e.preventDefault();
var this = $(this);
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url:'<?php echo base_url() ?>signup/removefile',
data:{ fileid: fileidvar },
dataType: 'json',
success: function (data) {
if(data.value){
alert(data.value);
this.closest("li").remove();
}
},
error:function(){
alert("Something went wrong, please try again.");
}
});
}
return false;
});
Hope this helps
Problem $(this) is not the element clicked .
so we cache the selector here var this1 = $(this);
$(".removefile").click(function (e) {
var this1 = $(this);
e.preventDefault();
var fileidvar = $(this).data('fileid');
if (confirm("Are you sure you want to remove selected file?")) {
$.ajax({
type: "POST",
url: '<?php echo base_url() ?>signup/removefile',
data: {
fileid: fileidvar
},
dataType: 'json',
success: function (data) {
if (data.value) {
alert(data.value);
this1.closest("li").remove();
}
},
error: function () {
alert("Something went wrong, please try again.");
}
});
}
return false;
});
try changing:
$(this).closest("li").remove();
to
$(this).parent().remove();