Problems with $_POST["var"] in Yii Controller - javascript

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);
}

Related

jQuery AJAX POST not passing data to a PHP script

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");
}
});

Wordpress ajax request return 0

Hello I have a problem with wordpress I can not get an ajax call and I can not find the reason. My query returns me all the time 0.
my javascript code :
updateButton.onclick = function (e) {
var donne = {
'action': 'my_action',
'lodges': updateDeleteArray
};
$(function () {
$.ajax({
type: "POST",
data: donne,
url: ajaxurl,
contentType: "application/json",
dataType: 'json',
success: function (data) {
console.log(data);
},
});
});
};
my php code :
add_action('wp_ajax_my_action', 'my_action');
add_action('wp_ajax_nopriv_my_action', 'my_action');
function my_action() {
echo 'salut';
die();
}
Try deleting contentType and dataType, because you are not returning a JSON into your function.
Or
modify your function like this
function my_action() {
echo json_encode('salut');
die();
}
hope it helps

call php function on button click with ajax and parse through parameters

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});

Create registration with Jquery

I create jquery script
function send_form() {
var data = $('#registration').serialize();
alert(data);
$.ajax({
type: "POST",
url: "{{ path('registrationAction') }}",
data: data,
success: function (data) {
if(data.success == true){
alert("Ok");
window.location.replace("{{ path('userRedirectAction') }}");
}
else
alert("False");
}
}
);
}
It's only part. If i alert(data) i have what i need
My controller
public function registrationAction(Request $request)
{
$response = new JsonResponse();
$form = $this->createForm(new UsersType());
if($request->getMethod() == 'POST')
{
$data = $request->request->get('pyramida_modelbundle_users');
$username = $data['username'];
$password = $data['password'];
$email = $data['email'];
$refer = $data['refer_id'];
$user = new Users();
$user->setUsername($username);
$user->setPassword($password);
$user->setEmail($email);
$user->setReferId($refer);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$response->setData(array("success" => true));
return $response;
}
return $this->render("CoreBundle:Registration:registration.html.twig", array('form' => $form->createView()));
}
I think that something is wrong in my JQuery, because after the registration the user is not redirected to your page . Please help find the error
You missed to add dataType : 'json'
Here is your solution.
$.ajax({
type: "POST",
url: "{{ path('registrationAction') }}",
dataType : 'json',
data: data,
success: function (data) {
if(data.success == true){
alert("Вы успешно зарегистрированы");
window.location.replace("{{ path('userRedirectAction') }}");
}
else
alert("Произошла ошибка при регистрации");
}
}
);

why ajax post method return empty alert box when i tried to return data from controller file in codeigniter

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);
}
});

Categories

Resources