I have made a custom module in magento. I am using ajax in it(prototype.js).i can find the post variable on ajax page. But I am unable to find the file array on ajax page.
I am using following code for this.Please let me know where i am wrong?
//Ajax code on phtml page
new Ajax.Request(
reloadurl,
{
method: 'post',
parameters: $('use-credit-Form').serialize(),
onComplete: function(data)
{
alert(data.responseText);
}
});
//Php code on ajaxpage
public function ajaxAction()
{
$fileData = $_FILES;
echo '<pre>';
print_r($fileData);die;
}
It always print blank. but when I added this line
"VarienForm.prototype.submit.bind(usecreditForm)();"
I can get the value of file array. but draw back now page starts refreshing.
Please give me some suggestion.
Try this:
Event.observe('use-credit-Form', 'submit', function (event) {
$('use-credit-Form').request({
onFailure: function () {
alert('fail.');
},
onSuccess: function (data) {
alert(data.responseText);
}
});
Event.stop(event); // stop the form from submitting
});
Credit: submit a form via Ajax using prototype and update a result div
Related
Ajax works well for pre-existing forms. But if I add a new form using it and submit it, then I get to the method page.
Added a new form, filled in the field and clicked Submit: http://joxi.ru/DmBOW4KUzep962
I get to the method page, instead of displaying the result in the console: http://joxi.ru/EA4P710TOekbOA
After reloading the page, everything works well.
What could be the matter, tell me please.
Front:
$('.add-answer-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: `/admin/courses/48/lessons/96/answerAdd`,
data: $(this).serialize(),
success: function (data) {
console.log('!!!!!', data);
}
});
});
Back:
public function answerAdd(Request $request, Course $course, Lesson $lesson, Test $test, Answer $answer){
$this->answer->fill($request->all())->save();
return response ()->json ($this);
}
I solved this issue as follows:
Instead of this:
$ ('.add-answer-form').on('submit', function (e) {
Added this:
$ ('#quest-add-form').on('submit', '.add-answer-form', function (e) {
This is suitable in cases where you need to work with the form that was added by Ajax.
i need to fetch data from database from controller file and display into element file and ajax value showing in inspect element and also when i alert in ajax it is showing that value is going to controller.
but problem is that how can i echo or print ajax value in controller to fetch data from database and display it into element file?
how can i render custom element file in controller function?
ajax script
<script>
$('#categories .accordion .tablist .tablistitem').on('click', function () {
event.preventDefault();
$(".accordion li").removeClass("active");
var $li = $(this);
$liid = $li.attr('id');
$slug = $li.data('slug');
$li.addClass("active");
$('#wrapper').append('<span id="load">LOADING...</span>');
$('#categories_info').show();
$.ajax({
type: 'POST',
url: '/reviews/getsubcategories',
data: {"selectid":$liid },
dataType:"text",
success: function(data, textStatus, xhr) {
alert(data);
},
error: function(xhr, textStatus, error) {
alert(textStatus);
}
});
});
</script>
controller function
function getsubcategories()
{
echo $selectid= $_POST['selectid'];
return $selectid;
}
element file
$SubCategoryObj = cri('Reviews');
$selectid = $SubCategoryObj->getMainCategories();
echo $selectid;
What you have done so far is mostly right, however in the past I have just created the view as normal in the View/Reviews folder.
In the controller set your data:
/app/Controller/ReviewsController.php
public function getsubcategories()
{
$this->layout = 'ajax';
$data = /**code to get data**/
$this->set('data', $data);
}
/app/View/Reviews/getsubcategories.ctp
<?php echo json_encode($data); ?>
another option is to create the same view above but put it in file app/View/Ajax/json.ctp
And then inside the controller the last thing you call in the getsubcategories action is.
$this->render('Ajax/json');
In my experience elements are used inside views and not as replacements of views
whenever I send a post request to 'tasks/add' i want the user to return to a new page, but all I get is plain html text in a popup.
Route.php code
Route::post('tasks/add', function() {
return view('secrets');
});
this is my ajax request :
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=customer]").val();
var details = $("input[name=details]").val();
var dataString = 'customer='+customer+'&details='+details;
$.ajax({
url: "tasks/add",
type:"POST",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data : dataString,
success:function(data){
console.log(dataString);
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
});
Anybody has had this issue before?
You are using Ajax to call your Route method. So when Route::post(...) returns the view 'secrets', it returns it to the Ajax method and becomes held by the data variable. Saying return in your Routes file doesn't magically mean redirect to a certain view, it is just like any other function that returns a value.
You currently have alert(data) which just says make an alert with whatever is held by data which in this case is the html text of your view.
Instead, take out the alert() and put
window.location.replace('<path/to/secrets>')
to redirect to the page you want upon success.
Assuming your Routes file has something like :
Route::get('/secrets', function() {
return view('secrets');
});
You could say
window.location.replace('/secrets')
I am using Ajax function to add product in cart in MVC 3
In Ajax i have a function for adding product, inside that function i want to call a another function but its not working..
My Ajax function is
var AjaxCart = {
addproductvarianttocart: function (urladd, formselector) {
if (this.loadWaiting != false) {
return;
}
this.setLoadWaiting(true);
$.ajax({
cache: false,
url: urladd,
data: $(formselector).serialize(),
type: 'post',
success: this.successprocess,
complete: this.resetLoadWaiting,
error: this.ajaxFailure
});
refreshPage();
},
refreshPage: function () {
$.post('/ShoppingCart/OrderSummaryChild', function (data) {
alert("Inside2");
// Update the ItemList html element
$('#CartUpdatePanel').html(data);
alert("Out");
});
}
};
The link is from where i am calling addproductvarianttocart function
<a onclick="AjaxCart.addproductvarianttocart( '/addproductvarianttocart/25/1/');return false;">
The ajax call is asynchronous. You should put the function refreshPage inside the success or complete function. This way the refreshPage function will be called right after the ajax call is finished and the page is ready to be refreshed with the new data.
Extracted from jQuery api:
Description: Perform an asynchronous HTTP (Ajax) request.
I'm trying to use Ajax in CakePHP, and not really getting anywhere!
I have a page with a series of buttons - clicking one of these should show specific content on the current page. It's important that the page doesn't reload, because it'll be displaying a movie, and I don't want the movie to reset.
There are a few different buttons with different content for each; this content is potentially quite large, so I don't want to have to load it in until it's needed.
Normally I would do this via jQuery, but I can't get it to work in CakePHP.
So far I have:
In the view, the button control is like this:
$this->Html->link($this->Html->image('FilmViewer/notes_link.png', array('alt' => __('LinkNotes', true), 'onclick' => 'showNotebook("filmNotebook");')), array(), array('escape' => false));
Below this there is a div called "filmNotebook" which is where I'd like the new content to show.
In my functions.js file (in webroot/scripts) I have this function:
function showNotebook(divId) {
// Find div to load content to
var bookDiv = document.getElementById(divId);
if(!bookDiv) return false;
$.ajax({
url: "ajax/getgrammar",
type: "POST",
success: function(data) {
bookDiv.innerHTML = data;
}
});
return true;
}
In order to generate plain content which would get shown in the div, I set the following in routes.php:
Router::connect('/ajax/getgrammar', array('controller' => 'films', 'action' => 'getgrammar'));
In films_controller.php, the function getgrammar is:
function getgrammar() {
$this->layout = 'ajax';
$this->render('ajax');
}
The layout file just has:
and currently the view ajax.ctp is just:
<div id="grammarBook">
Here's the result
</div>
The problem is that when I click the button, I get the default layout (so it's like a page appears within my page), with the films index page in it. It's as if it's not finding the correct action in films_controller.php
I've done everything suggested in the CakePHP manual (http://book.cakephp.org/view/1594/Using-a-specific-Javascript-engine).
What am I doing wrong? I'm open to suggestions of better ways to do this, but I'd also like to know how the Ajax should work, for future reference.
everything you show seems fine. Double check that the ajax layout is there, because if it's not there, the default layout will be used. Use firebug and log function in cake to check if things go as you plan.
A few more suggestions: why do you need to POST to 'ajax/getgrammar' then redirect it to 'films/getgrammar'? And then render ajax.ctp view? It seems redundant to me. You can make the ajax call to 'films/getgrammar', and you don't need the Router rule. You can change ajax.ctp to getgrammar.ctp, and you won't need $this->render('ajax');
this is ajax call
$(function() {
$( "#element", this ).keyup(function( event ) {
if( $(this).val().length >= 4 ) {
$.ajax({
url: '/clients/index/' + escape( $(this).val() ),
cache: false,
type: 'GET',
dataType: 'HTML',
success: function (clients) {
$('#clients').html(clients);
}
});
}
});
});
This the action called by ajax
public function index($searchterm=NULL) {
if ( $this->RequestHandler->isAjax() ) {
$clients=$this->Client->find('list', array(
'conditions'=>array('LOWER(Client.lname) LIKE \''.$searchterm.'%\''),
'limit'=>500
));
$this->set('clients', $clients);
}
}
This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.
$('#myForm').submit(function(e) {
// Catch form submit
e.preventDefault();
$form = $(this);
// console.log($form);
// Get form data
$form_data = $form.serialize();
$form_action = $form.attr('action') + '.json';
// Do ajax post to cake add function instead
$.ajax({
type : "PUT",
url : $form_action,
data : $form_data,
success: function(data) {
swal({
title: "Updated!",
text: "Your entity was updated successfully",
type: "success"
},
function(){
location.reload(true);
});
}
});
});