how to send javascript array to controller in yii - javascript

I have a view having multiple checkboxes.
When I select some textbox, I need to do some operation on them, so they should be passed to the controller.
How can I do this?
My JS function :
function myfun() {
$.ajax({
type : "POST",
url : "http://localhost/newtemplate/index.php/product/dispatchdata/",
dataType : 'json',
data : {
idList : $("input[type=checkbox]:checked").serializeArray()
},
success : function(data) {
alert(data);
},
error : function (data){
alert('Error');
//alert(data);
}
});
}

replace your URL by this:
url: "<?php echo Yii::app()->createUrl('product/dispatchdata'); ?>",
then try to send your json as follow: data: {idList:JSON.stringify(idList)},

Use this :
$.ajax({
url: "<?php echo App::param('siteurl'); ?>products/ZipUpload",
type: "POST",
data: {
idList : $("input[type=checkbox]:checked").serializeArray()
},
success: function(data) {
alert(data)
}
});

As mohammad said: "Replace your url with"
url: "<?php echo Yii::app()->createUrl('product/dispatchdata'); ?>",
Further, if you fail in ajax call, the reason may be that the error is in your code in the controller. if you cant return successfully from controller, then you will get error in ajax... so try debugging step by step your controller action.

Related

How to get return text from php file with ajax?

I am making a call with ajax to a php file. All I want to do is get a value back from the php file to test it with javascript. I have tried many many things, but can only get undefined (from the below code).
How can I get "hello" returned from the php file to my javascript?
jQuery.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = jQuery(data).html();
alert(the_returned_string)
}
});
The PHP file:
<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";
You can change the code inside PHP like this
<?php
$queryResult = '<div id="id-query-result">hello</div>';
echo json_encode(['html' => $queryResult]);
Then, change your ajax call
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
dataType: 'json',
success: function(data) {
var the_returned_string = data.html;
alert(the_returned_string);
}
});
$.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
$('body').append(data);
var text = $('#id-query-result').text();
alert(text);
$('#id-query-result').remove()
}
});
Why not just append the HTML response of your php file then get the text accordingly. You can then remove it after.
There are two changes to be done:
Change the type to "GET" since you directly call the PHP File.
remove the wrapped jQuery method inside the success function and add .html as an attribute
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = data.html
alert(the_returned_string)
}
});

Executing javascript function on AJAX success in WP

I have a function in my Wordpress that regenerate Google Map.
What I want to achieve is to get some markers from my WP, then add them to DIV and generate from them map again.
For regenerating I'm using simple function with magic name "regenerate_map()" :) .
jQuery(".gmaps-button").click(function(){
jQuery.ajax({
type: "POST",
//contentType: "application/json; charset=utf-8",
dataType: "text",
url: myAjax.ajaxurl,
data : {action: "jv_get_map_data", ids : 1},
//data: dataString,
action: 'jv_get_map_data',
beforeSend: function() {
//jQuery('#contact-form #err2').html('').hide();
//jQuery(".submit").html("proszę czekać").addClass('loading');
},
success: function(text) {
jQuery('#gmaps-markers').html(text);
console.log(text);
regenerate_map();
}
});
return false;
});
The main problem is that function regenerate_map() is not working.
I get "ReferenceError: regenerate_map is not defined".
This is not true, because, I have other button, which is a trigger for click() and it uses this function also and it works.
I think that is something wrong with executing other function in AJAX request, but console.log and alert() works.
I thought that problem can be with what I get as "text" but I have checked that even if I get nothing, problem exists too.
Maybe some security issue?
Can somebody tell me why and what to do to achieve what I need?
your regenerate_map() function should be like this.
<script>
jQuery(document).ready(function() {
jQuery("#p_button").click ( function () {
console.log("button got clicked");
var donor_data= [ "12","13","14" ];
var damount = 1234;
var donor_obj = {
id : donor_data,
amnt : damount,
};
jQuery.ajax({
type:"POST",
//dataType : "json",
url: "<?php echo admin_url( 'admin-ajax.php' );?>",
data: { action : "ajx_add_donations",
'donors' : JSON.stringify(donor_obj),
},
success:function(response){
console.log("success " ,response);
//console.log("success " + JSON.parse(response));
//jQuery("#d_amount").val(donor_data[0]);
//jQuery("#p_button").text("brrr");
regenerate_map();
},
error: function(response) {
console.log("error" + response);
},
});
});
});
function regenerate_map(){
alert("test");
}
</script>

JQuery UI Autocomplete Wordpress

I want to add autocompletion in a nickname search bar. I do not understand why it does not work. My code is correct ?
In my file liste.php
global $wpdb;
$name = $_POST['code_postal'];
$sql = $wpdb->get_results("SELECT * FROM membres WHERE pseudo LIKE '$name%' ");
$titles = array();
foreach($sql as $key=> $value){
echo $value->pseudo;
}
echo json_encode($titles); //encode into JSON format and output
In my global.js
$('#recherche').autocomplete({
source: function(name, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-content/themes/ARLIANE/liste.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
In my index.php
<form>
<input type="text" name="term" id="recherche"/>
</form>
You can try to log ajax errors to console for more informations about the problem , something like this :
$.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-content/themes/ARLIANE/liste.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
Try to change the URL in your js code by adding a page and to associate the file liste.php as a custom page Type and Than add the page URL :
url: '<?php echo get_permalink(page_id); ?>',
If I do a include of liset.php this returns me well a table json.
But when I make my ajax call it returns a Error 500.
I think the problem comes from the jquery call with the autocomplete function.

Ajax: Posting dynamic ajaxed content

I am trying to write the content of a div to a new html file. The content of the div is being generated by ajax itself, so when I try to post the contents to a new file, all that is being written to the file is the raw html. Is there a way to write the div contents of the 'ajaxed in' content?
This is my ajax code:
$("#getSource").on('click', function(){
headerURL = $(".header-code").attr('data-url');
$.ajax({
url: headerURL,
data: "function=showCode",
success: function(data){
$('code #mainCode').append(data);
}
});
var bufferId =$("#mainCode").html();
$.ajax({
type : "POST",
url : "postCode.php",
data: {id : bufferId},
dataType: "html",
success: function(data){
alert("ok");
}
});
});
my php code:
$handle = fopen("test.html", 'w+');
$data = $_POST['id'];
if($handle) {
if(!fwrite($handle, $data )) {
echo "ok";
}
}
the end result of whats being written in test.html:
<div id="mainCode"></div>
when I really need:
<div id="mainCode">
[dynamic content that is added by the user via ajax]
</div>
You also can use a deffered object returned by $.ajax to run second ajax request after the first one:
headerURL = $(".header-code").attr('data-url');
$.ajax({
url: headerURL,
data: "function=showCode",
success: function(data){
$('code #mainCode').append(data);
}
}).done(
function() {
var bufferId =$("#mainCode").html();
$.ajax({
type : "POST",
url : "postCode.php",
data: {id : bufferId},
dataType: "html",
success: function(data){
alert("ok");
}
});
}
)
Issue second AJAX call after first call appends content. Change JavaScritp code to:
$("#getSource").on('click', function(){
headerURL = $(".header-code").attr('data-url');
$.ajax({
url: headerURL,
data: "function=showCode",
success: function(data){
$('code #mainCode').append(data);
// second ajax call
var bufferId =$("#mainCode").html();
$.ajax({
type : "POST",
url : "postCode.php",
data: {id : bufferId},
dataType: "html",
success: function(data){
alert("ok");
}
});
}
});
});

Passing this javascript object from jQuery to PHP?

This question stems from this thread.
I've followed the answer below but am having trouble with passing the object into PHP. I think it's only a minor problem but I can't find it.
My ajax call
$('.actResult').click(function() {
var result = {};
$('.actResult tr').each(function(){
var $tds = $(this).find('td');
result[$tds.eq(0).html()] = $tds.eq(1).text();
});
console.log(result);
$.ajax({
type: 'get',
url: 'userpage.php',
data: result
});
$('.FindResults').dialog("close");
});
In userpage.php, I'm using this:
echo '<div id="data"><pre>', var_dump($_GET), '</pre></div>';
Possibly I might need to use stringify or json_decode, but this source tells me it's enough to do an ajax call.
The output is giving me an
array(0){
}
Which is strange. The array prints into the console so it's generated properly. The console also tells me the ajax is executed successfully. I'm using $_GET just because $_POST already has so many variables, it's easier to inspect $_GET for this request.
UPDATE:
From the comments below, the ajax call doesn't do anything when the query is successful. So I changed the call:
$.ajax({
type: 'get',
url: 'userpage.php',
data: result,
success: function(){
$('#data').text( data );
}
});
And the PHP
echo '<input type="text" id="data" /><pre>', var_dump($_GET), '</pre>';
I tried it with a div instead of a textbox. The result still is array(0){}
$.ajax({
type : "GET",
data : { result : JSON.stringify(result) },
dataType : "html",
url : "userpage.php",
beforeSend : function(){ },
success : function(data){ console.log( data ) },
error : function(jqXHR, textStatus, errorThrown) { }
});
in your php
echo '<div id="data"><pre>'. $_GET["result"] .'</pre></div>';
$.ajax({
type: 'GET',
url: 'userpage.php',
data: result,
dataType : 'json',
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus){
console.log(jqXHR);
console.log(textStatus);
}
});
look at the console log and check the problem...
ahh another thing on the userpage use like this:
echo json_encode($_GET);
You know what, I'm going out on a limb here, and taking a wild guess.
I think you're lying to us.
Based on this sentence in your question: I'm using $_GET just because $_POST already has so many variables.
You're doing a POST, not a GET. Why would $_POST contain anything if you're sending a GET?
Change your ajax from this
$.ajax({
type: 'post',
url: 'userpage.php',
data: result
});
to this
$.ajax({
type: 'get',
url: 'userpage.php',
data: result
});

Categories