I'm trying to do a simple form mail with ajax.
But, I can't grab the data from the form.
My form:
<?php echo $this->Form->create('Page', array('default' => false)); ?>
<?php echo $this->Form->input('texto', array('label' => FALSE, 'type' => 'textarea)); ?>
<?php echo $this->Form->submit('Enviar', array('id' => 'enviar'));
echo $this->Form->end();
My ajax:
$(document).ready(function() {
$('#enviar').click(function(){
$.ajax({
type: 'post',
complete: function(r){
$('div.teste').html('<h4> Enviado!</h4>');
}
})
})
});
The controller:
if($this->request->is('ajax')) {
debug($this->request->data);
App::uses('CakeEmail', 'Network/Email');
$Email = new CakeEmail('gmail');
$Email->to('xxxx#gmail.com');
$Email->subject('Nova Mensagem - Site Althi');
$Email->send($mensagem);
}
}
And my controller send the email.
The e-mail has send sucefull, but the data of this->request->data is a blank array.
I think the problem is the data passed from the ajax.
Can help me please?
You have to set the data value in the ajax function call.
$.ajax(
thecontrollerurl,
{data: $("#theformid").serialize()}
);
more info here: http://api.jquery.com/jQuery.ajax/
$data = $this->Js->get('#YourformORelementID')->serializeForm(array('isForm' => true, 'inline' => true));
And then
$this->Js->get('#enviar');
$this->Js->event('click',
$this->Js->request(
array('controller' => 'someController', 'action' => 'someAction'),
array('async' => true, 'data' => $data, 'update' => 'div.teste')
));
Related
On me web I use ajax to submit data and pjax to reloade list view. On first time when I submit form it work good, save and reloade list view, on the second time, it save data but don't reload list view, it show response from action {"success":true,"id":68} . Can someone look on this?
action
public function actionReply()
{
$model = new ReplyForm();
$response = [];
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->save()) {
$response['success'] = true;
$response['id'] = $model->id;
}
} else {
$response['success'] = false;
}
Yii::$app->response->format = Response::FORMAT_JSON;
return $response;
}
script in view file
$(document).ready(function () {
var $form = $('form#reply-form');
$form.on('beforeSubmit', function (event) {
var data = $form.serialize();
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data,
dataType: 'json',
success: function (d) {
if(d.success === true){
//$.pjax.reload({container: '#comments', async: false});
$.pjax.reload('#comments', {timeout: false});
$form.trigger('reset');
}else {
alert('error');
}
}
});
return false;
});
});
and view form file
<div class="page-form">
<?php $form = ActiveForm::begin([
'id' => 'reply-form',
'action' => ['comment/reply'],
'options' => ['data-pjax' => true],
]); ?>
<?= $form->field($model, 'content')->textarea(['maxlength' => true, 'class' => 'form-control', 'rows' => 3]) ?>
<?= $form->field($model, 'item_id')->hiddenInput()->label(false) ?>
<?= $form->field($model, 'parent_id')->hiddenInput()->label(false) ?>
<div class="form-group">
<?= Html::submitButton('WyĆlij', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
view comments file
<?php Pjax::begin(['id' => 'comments']) ?>
<?= ListView::widget([
'dataProvider' => $commentDataProvider,
'summary' => false,
'itemView' => '_comment',
'options' => [
'tag' => 'div',
'class' => 'block-post-comments',
],
'pager' => [
'class' => LinkPager::class
]
]); ?>
<?php Pjax::end() ?>
I have created a form for making donation when user makes donation he will be viewing an error or if successful will be able to see a form on second page like second form will be loaded up. Now the problem is that when I tested data is properly updating in the database as well as on back end everything is working fine. The problem is that ajax is not getting return data I have placed a loader on success the loader will be hidden and it is not working it's continuously loading but not getting return data can anyone help me out to fix this error for me please here is my code
This is my javascript
$(document).ready(function() {
$('.donate').on('submit', function(e) {
$('.load').fadeIn(500);
var formData = new FormData(this);
console.log(formData);
$.ajax({
url : "http://mydomainname.com/directory/user/makedonation",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
success : function(data) {
$('.load').fadeOut(500);
console.log(data.status);
$('.donation_form').html(data);
}
});
});
});
This is my controller User.php where the data is being processed
public function makedonation() {
$comments = $this->input->post('comments');
$user_data = $this->get_data->user_info($this->session->userdata('uid'));
$class = $this->db->get_where('classes', array('id' => $user_data->row()->membership));
$amount = $class->row()->ammount_pay;
$data = array(
'user_id' => $user_data->row()->uid,
'amount' => $class->row()->ammount_pay,
'rcv_amount' => $class->row()->ammount_receive,
'class_id' => $class->row()->id,
'comments' => $comments
);
$rt_data = $this->data_insert->donate_user($data);
$rcv_data = $this->get_data->user_info($rt_data['receiver_id']);
$name = $rcv_data->row()->first_name . " " . $rcv_data->row()->last_name;
$view_data = array(
'user_id' => $user_data->row()->uid,
'receiver_id' => $rt_data['receiver_id'],
'transaction_id' => $rt_data['transaction_id'],
'comments' => $comments,
'name' => $name,
'amount' => $class->row()->ammount_pay,
'command' => 'Confirm Donation'
);
$this->load->view('user/includes/get_data', $view_data);
}
This is the modal where the data is being inserted into the database
public function donate_user($data) {
$donation_data = array(
'user_id' => $data['user_id'],
'amount' => $data['amount'],
'receive_ammount' => $data['rcv_amount'],
'date_deposit' => date('m-d-Y'),
'time_deposit' => date('h:i A'),
'class' => $data['class_id'],
'status' => 'Submitted'
);
$insert_donation = $this->db->insert('donation', $donation_data);
$transaction_id = $this->db->insert_id();
$rt_data = array(
'message' => 'Success',
'transaction_id' => $transaction_id,
'receiver_id' => $receiver->row()->user_id
);
return $rt_data;
}
Now here is my confusion if the data is inserting correctly into the data base and also when I run this file separately in the browser I am referring to my controller the second page is loading up properly no errors found the why ajax is not returning data
Here is your answer. You have to set your ajax return data to json and do following in your controller.
$(document).ready(function() {
$('.donate').on('submit', function(e) {
$('.load').fadeIn(500);
var formData = new FormData(this);
console.log(formData);
$.ajax({
url : "http://mydomainname.com/directory/user/makedonation",
type : "POST",
data : formData,
contentType : false,
cache : false,
processData : false,
dataType: 'json',
success : function(data) {
$('.load').fadeOut(500);
console.log(data.status);
$('.donation_form').html(data.response);
}
});
});
});
Controller Code
public function makedonation() {
$comments = $this->input->post('comments');
$user_data = $this->get_data->user_info($this->session->userdata('uid'));
$class = $this->db->get_where('classes', array('id' => $user_data->row()->membership));
$amount = $class->row()->ammount_pay;
$data = array(
'user_id' => $user_data->row()->uid,
'amount' => $class->row()->ammount_pay,
'rcv_amount' => $class->row()->ammount_receive,
'class_id' => $class->row()->id,
'comments' => $comments
);
$rt_data = $this->data_insert->donate_user($data);
$rcv_data = $this->get_data->user_info($rt_data['receiver_id']);
$name = $rcv_data->row()->first_name . " " . $rcv_data->row()->last_name;
$view_data = array(
'user_id' => $user_data->row()->uid,
'receiver_id' => $rt_data['receiver_id'],
'transaction_id' => $rt_data['transaction_id'],
'comments' => $comments,
'name' => $name,
'amount' => $class->row()->ammount_pay,
'command' => 'Confirm Donation'
);
$result = $this->load->view('user/includes/get_data', $view_data,true);
$this->output->set_content_type('application/json')->set_output(json_encode(array('response' => $result,'status'=>'success')));
}
You can read https://www.codeigniter.com/userguide3/libraries/output.html for output and return view in variable to set as last parameter as true based on codeigniter feature of views.
I would like to achieve something like these below code. just that the code is making a request from the database, i want to send request to the database
$.post( "/trobay/categories/default/lists?parent_id="+$(this).val(), function( data ) {
how to send request adding attribute name and attribute value to be save in DB
below is my code i have already
<?php
$script = <<< JS
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var \$TitleInput = $('#product-product_title');
//on keyup, start the countdown
\$TitleInput.on('keyup input change paste',function(){
clearTimeout(typingTimer);
if (\$TitleInput.val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: data,
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});
JS;
$this->registerJs($script);
?>
in my controller i have this
public function actionCreate()
{
$model = new Draft();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \time();
if($model->save()){
return draftId;
}else{
return '0';
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
and in my view i have this
<?php $form = ActiveForm::begin(['id'=>$model->formName(),
'enableClientValidation'=> true,
'fieldConfig' => ['template' => '{label}{input}{hint}']]); ?>
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'product_title')->textInput([
'class'=>'title-input',
'placeholder' => 'Give us a title for your items(include size,brand,color,material. e.t.c)',
])->label(false) ?>
</div>
<div class="col-md-12 text-muted">
E.g Men's blue addidas glide running shoes size 11
</div>
</div>
<?= $form->field($model, 'user_id')->textInput() ?>
<?= $form->field($model, 'product_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'category_id')->textInput() ?>
Now my question is I just want to grab the value of each field input and send it to server side for save in the DB without having to submit the whole form
The about JS code works enough to get the value but how do i send this to the server for save up
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: {title: data}
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
});
If you need to send more key value just add those as comma seperated value like
data: {title: data, attr:"value"}
and so on...and you can receive this value as post parameter in your controller.
I have tried searching around for a solution to my problem and I can't find any.
I wondered if anyone could help me out.
Basically I'm trying to let a user type in a variable so that they can see a google chart with the data they specifically request.
The chart is set up to do a ajax json request to another php script, though.
Here is my code. (I've deliberately left out the irrelevant code.)
HTML FORM,
<form id="form" action="http://localhost/query/CHART.php" method="POST">
<div><label for="VARIABLE">Enter Variable or % For All Variables:
<input type="text" name="VARIABLE" id="VARIABLE"/>
</label>
</div>
<br />
<div class="submit-button"><input type="submit" value="Get Data"/></div>
</form>
Google Chart PHP Page
include "C:\wamp\www\includes\header.php";
<div id="content">
<br>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
PHP JSON QUERY (MEAS.PHP)
<?php
$conn = mysqli_connect('***', '***', '***');
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysqli_select_db($conn, "TRACK")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$result = $conn->query("SELECT VARIABLE, var1, var2, var3, var4 FROM MEASTEST WHERE VARIABLE LIKE '$VARIABLE'
");
// creates column nsmes, nothing to do with query //
$table = array();
$table['cols'] = array(
array('id' => "", 'label' => 'VARIABLE', 'pattern' => "", 'type' => 'string'),
array('id' => "", 'label' => 'VAR1', 'pattern' => "", 'type' => 'number'),
array('id' => "", 'label' => 'VAR2', 'pattern' => "", 'type' => 'number'),
array('id' => "", 'label' => 'VAR3', 'pattern' => "", 'type' => 'number'),
array('id' => "", 'label' => 'VAR4', 'pattern' => "", 'type' => 'number'),
);
$rows = array();
while ($nt = $result->fetch_assoc())
{
$temp = array();
$temp[] = array('v' => $nt['VARIABLE'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR1'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR2'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR3'], 'f' =>NULL);
$temp[] = array('v' => $nt['VAR4'], 'f' =>NULL);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysqli_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
?>
The result is that the google chart page doesn't load the chart up, due to the variable not being passed to the query and no json data coming back into the page.
Hope this makes sense!
EDIT: I did delibrately leave code out when posting but its confused people, the full php page is there now.
Thanks
edited:
Your Code Is Not Light, You send Ajax request To "MEAS.php" ??
which Is "MEAS.php"'s Code ??
if "MEAS.php" is:
<?php
$VARIABLE = $_POST['VARIABLE'];
$conn = blah,blah
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysqli_select_db($conn, "TRACK")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$result = $conn->query("SELECT VARIABLE FROM MEASTEST WHERE VARIABLE LIKE '$VARIABLE'
");
You Must Set Response "Content-type" with header function:
header("Content-Type: application/json")
and return a json:
echo json_encode(" your Response Data ")
Your AJAX request is not sending any parameters:
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
dataType:"json",
async: false
}).responseText;
you need to add the parameter to the request:
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
data: {
myParameterName: parameterValue
},
dataType:"json",
async: false
}).responseText;
If this is happening in response to user input, then the drawing should happen inside an event handler in response to whatever needs to trigger the redraw. As an example:
function drawChart() {
var jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
data: {
myParameterName: 'default value'
},
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// create and draw the chart
// ...
/* assumes you have:
* a chart object called "chart"
* an options object called "options"
* a button with the id "myButton" that should trigger a redraw on click
* an input field "myInput" that has the value you want to send to your server
*/
function updateChart () {
jsonData = $.ajax({
type: "POST",
url: "http://localhost/query/MEAS.php",
data: {
myParameterName: document.querySelector('#myInput').value
},
dataType:"json",
async: false
}).responseText;
data = new google.visualization.DataTable(jsonData);
chart.draw(data, options);
}
var btn = document.querySelector('#myButton');
if (document.addEventListener) {
btn.addEventListener('click', updateChart);
}
else if (document.attachEvent) {
btn.attachEvent('onclick', updateChart);
}
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});
I am trying to call ajax in wordpress. It work fine in browser but in mobile device it return response 0 . Here is my wordpress & Jquery code. please suggest where i am doing wrong
The code in functions.php file
function get_nearest_destinations()
{
$data = array();
check_ajax_referer( "getnearestdestinations" );
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
);
$the_query = new WP_Query($args);
if($the_query->have_posts()){
while ( $the_query->have_posts() ) :
$the_query->the_post();
$data[] = array('title'=>get_the_title());
endwhile;
}
echo json_encode($data); exit();
}
add_action( 'wp_ajax_getnearest', 'get_nearest_destinations' );
Below is js code in template file....
<?php $nonce = wp_create_nonce( 'getnearestdestinations' ); ?>
jQuery.ajax({
type: "POST",
url: "<?php echo bloginfo('url').'/wp-admin/admin-ajax.php'; ?>",
data: { action: 'getnearest', _ajax_nonce: '<?php echo $nonce; ?>'},
dataType: "json",
success: function(html){
alert(html)
}
}); //close jQuery.ajax(
May be you have non logged in user issue.Pl use below syntax for non logged in users
add_action('wp_ajax_nopriv_getnearest', 'get_nearest_destinations'); // Not logged in user