I expect the controller to return variable's value from efund_2.phtml when the ajax request is made via controller but its returning the initiator's(efund.phtml) entire html.
/**
* Called using AJAX POST method.
*/
public function getEfundAction()
{
// Get post data.
$PostData = $this->getRequest()->getPost();
$Param1 = $PostData['param1'];
$Param2 = $PostData['param2'];
$ModelLayout = new Pteb_System_Model_Layout_Backend();
$ModelLayout->LoadLayout();
$Block = $ModelLayout->SetContentBlock( 'efund-block', 'Pteb_System_Block_Cms' );
$Block->setTemplate('adminpteb/efund/efund_2.phtml');
// Passing parameters to template file.
$Block->setData( 'MyPostData1', $Param1 );
$Block->setData( 'MyPostData2', $Param2 );
$ModelLayout->ShowLayout();//this getting the whole page html. But I just need the value returned by the variables in the page(efund_2.phtml).
}
PHP function in efund.phtml page.
function GetEFund()
{
var url='http://emall.3pteb.my/adminpteb/efund/getEfund';
var DivResult=jQuery('#DivResult');
var data = {
"action": "test"
};
$.ajax({
type:'GET',
url:url,
dataType: "html",
data: data,
success: function(data) {
alert(data);
DivResult.append(data);
}
});
}
And the above function is initiated by :
$('a').bind('click', function(){
GetEFund();
});
I'm getting this error:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
In the network tab (Chrome console), I see the call is made to the
function getEfund(). However when clicked on it, it shows the entire
html of efund.phtml page , in fact that was what returned by the
controller. How can I make efund_2.phtml return its variables?
Seems like you need to set JSON headers in your controller:
// Set our return json.
$sJson = json_encode( $aDataArray, 1 );
// Send it back to our ajax call.
$this->getResponse()->setHeader( 'Content-type', 'application/json' );
$this->getResponse()->setBody( $sJson );
Related
So in my program, i have two tabs i am performing a post ajax request using form.
On load of ajax two different kinds of json will appear
the code is as below:
$('#myForm').submit(function () {
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get formdata
dataType : "json",
//async : false,
//timeout : 55000,
type : $(this).attr('method'), // GET or
// POST
url : url.A, // the file to call
success : function ( json ) {
// on success..
$('.ajaxloader').css("visibility", "hidden");
Graph = json;
draw(Graph);
}
});
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get formdata
dataType : "json",
type : $(this).attr('method'), //POST
url : url.B, // the file to call
success : function ( json ) {
// on success..
table= json;
plot(table);
}
});
}
Now on josn s arrival i am first showing the table, to view my other tab, i am writing a onclick event this way..
$(init);
function init () {
$('body').on('click', 'a.all',function(){
plot(table);
})
.on('click', 'a.domain',function(){
draw(Graph);
});
}
Now my problem is if i click on domain, the json would have still not loaded hence throwing a error,
How do i resolve this..
So far i tried async:false (it works fine but it shows a deprecated warning)
AjaxStop, works well the first time then when switching tabs it just shows no response
I also tried when but since i am new to java script I didn't understand the usage at all
You could try to use an Ajax global event like ajaxComplete().
var ajaxCounter = 0;
$(document).ajaxComplete(function(){
ajaxCounter++;
if(ajaxCounter == 2){
$(init);
}
});
I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );
I have a javascript function that sends to a Controller some information (mostly vars like arrays and ids) to be inserted in a table, the problem is after the insertion is completed I want to return to a different view with a data array and i cant seem to do this (I think its because of the ajax request)
Javascript Code
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
window.location.replace(data.url);
}
});
}); // end form.submit
Function Prepare PostData()
var file_data=$('input:file')[0].files;
var postdata=new FormData();
postdata.append('_token',token);
postdata.append('startFrom',startFrom);
postdata.append('idList',idList);
postdata.append('nomeCampos',nomeCampos);
postdata.append('posicaoCampos',posicaoCampos);
postdata.append('file',file_data[0]);
return postdata;
Controller Expected Code
Do all inserts and functions and in the end
$data = array('listNome' => $listName, 'contacts' => $contacts, 'errors' => $erro);
return view("XPTO", $data);
You should not return a view from an ajax call, because you'd get the view processed code as a parameter to the ajax callback. Think of an ajax call as an async 'behind the scenes' call to the server in which you pass parameters and get some other parameters back
You should instead return a JSON response from the controller with all the parameters you'll need to call the route from JS, and parse it in your success callback. For example:
Controller
//here you should store all the parameters you need in your JS calback
$data = array('status' => 'ok', 'url' => $redirect_url );
JS
success:function(data)
{
//data will contain the parameters you set in the controller, so you can use them to call the route
if ( data.status == 'ok' )
window.location.replace(data.url);
}
Just elaborating previous answer , Ajax call controllers are used to supply some data behind the scenes and standard controllers are used to control the view so best practise is to return data (JSON) form Ajax controller to the same view which requested the data. while the standard controller should be used to control the views.
SOLVED
Not the most elegant solution but what I did was set the array with errors as an session variable and get that session var in the specific controller I need.
Controller
$request->session()->put('importErrors',$erro);
$response = array('status' =>'success','url' => '/ListarContactos/'.$idList);
return response()->json($response);
JavaScript
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
if(data.status=='success'){
window.location.replace(data.url);
}
}
});
}); // end form.submit
XPTOController
$errorArray= $request->session()->get('importErrors');
After using it you can destroy the session variable or keep it(depending if you need it or not).
I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).
HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"
I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)