JS:
$(function() {
load_custom_topics()
// load_main()
});
function load_custom_topics(){
$.ajax({
type: "POST",
async: false,
url: 'http://rickymason.net/thebump/index.php/ajax/load_custom_topics',
dataType: 'json',
data: { },
success: function(page){
alert(page);
}
});
event.preventDefault()
}
load_custom_topics
public function load_custom_topics()
{
$check = $this->page_model->check_active_topic();
if ($check == FALSE)
{
$page['content'] = 'TEST equals FALSE';
} else {
$page['content'] = 'TRUE';
}
echo json_encode($page);
}
going to the page index.php/ajax/load_custom_topics returns this:
{"content":"TEST equals FALSE"}
The alert is not firing! Any idea why?
Actually, on inspecting a request to your controller, I found that you weren't setting the proper headers the ajax call expects (text/json).
See codeigniter's Output class.
Using
$this->output->set_content_type('application/json')->set_output(json_encode($page));
instead of
echo json_encode($page);
should do the trick.
Related
I check two values with ajax. And if both are correct then i want to make a submit (post-back).
But the post-back doesn't work.
Here is the code:
$('form').submit(function () {
var correctCaptcha = false;
var correctWebcode = false;
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above (for webcode)
});
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
else { return false; }
});
Use Async:false
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
async:false,
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
correctCaptcha = true;
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
This will cause the infinite loop:
if (correctCaptcha == true && correctWebcode == true) {
document.forms['form'].submit();
}
So use use like this here
if (correctCaptcha == true && correctWebcode == true) {
return true;
}
else {return false;}
Since ajax is async in nature you cannot expect those variables to be set right away when ajax call. You can either set async to false or submit the form inside success handler. Try this.
$('form').submit(function () {
$.ajax({
url: '/Competition/CheckForm',
type: "POST",
data: $(this).serialize(),
success: function (data) {
if (data == true) {
$('#recaptcha_response_field').removeClass("captchaError");
$('form')
.unbind('submit')//we dont need any handler to execute now
.submit();
}
else {
Recaptcha.reload();
$('#recaptcha_response_field').addClass("captchaError");
}
}
});
$.ajax({
// like the code above
});
return false;//To prevent the form from being submitted.
});
By default, $.ajax works asynchronously, your way won't submit the form, you should submit the form in the callback function.
I've written an Ajax code, which calls a function in a php file.
queryURL = "http://<?php echo $_SERVER['SERVER_NAME'] ?>/MyPhpFile.php";
params = fromDate+" , "+to_Date;
$.ajax(
{
url: queryURL,
type: "post",
dataType: 'json',
async: false,
data:
{
funcName: "MyFunc",
values: params
},
complete: function (result) {
debugger;
doSth();
}
});
And in my php file:
if ($_POST) {
if (isset($_POST['funcName'])) {
if (function_exists($_POST['funcName'])) {
G::LoadClass('case');
$fName = $_POST['funcName'];
if (isset($_POST['values'])) {
$values = $_POST['values'];
$arrP = explode(",", $values);
echo call_user_func_array($fName, $arrP);
} else {
echo $fName();
}
}
}
}
fucnction MyFunc($fromDate, $toDate){
echo "1";
}
In the Network tab of my browser's debugger section, I can see that the php file just called once. Yet the response is duplicated.
If my function returns 1, the response will be 11.
Why is this happening?
how can I prevent it?
Remove echo from echo call_user_func_array($fName, $arrP);. Just use call_user_func_array($fName, $arrP);
I'm using Yii 2.0 basic version and I need some help.
I created one ajax function like this:
function eliminarColaborador(id) {
$.ajax({
type: "GET",
async: false,
url: "<?= urldecode(Url::toRoute(['colaborador/ajaxEliminarColaborador'])) ?>",
dataType: 'json',
data: {
'id': id
},
complete: function ()
{
},
success: function (data) {
if (data !== null)
{
// SUCCESS
}
else
{
// ERROR
}
}
});
}
My action in controller:
public function actionAjaxEliminarColaborador($id) {
if (Yii::$app->request->isAjax) {
$continuar = false;
if(isset($id) && $id > 0) {
var_dump($model); die;
$continuar = true;
}
echo CJSON::encode(array('continuar'=>$continuar));
Yii::$app->end();
}
}
I'm getting this erro in firebug: Not Found (#404): Page not found.
I tried everything, but i can't figure out what's the problem.
If I change ajax url to urldecode(Url::toRoute(['colaborador/delete'])) the error is gone and all works just fine.
Maybe I need to declare in ColaboradorController my new action ajaxEliminarColaborador, but I don't know how.
What is wrong?
controller
public function actionAjaxEliminarColaborador(){}
ajax
urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador']))
It should be <?= urldecode(Url::toRoute(['colaborador/ajax-eliminar-colaborador'])) ?>. Here you can learn why.
Change the ajax response with:
url: '/colaborador/ajaxEliminarColaborador/$id',
data: {id: $id,_csrf: yii.getCsrfToken()},
Try to remove the word 'ajax' on your url.
The problem is I am getting the dialog box of false but the query is running fine and values are successfully added into the database. It should print true, but it is giving me a false. I checked through Firebug also the value res = 1 is going, but I don't know what is wrong in it.
My View:
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
if(msg.res == 1)
{
alert(true);
}
else
{
alert(false);
}
}
});
Controller:
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query){ //&& any other condition
$result['res'] = 1;
}
else
{
$result['res'] = 0;
}
echo json_encode($result); //At the end of the function.
}
}
Try setting your dataType to json so the data sent back from the server gets parsed as JSON.
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1) {
alert(true);
}
else
{
alert(false);
}
}
});
Notice return.
if ($query){
$result['res'] = 1;
}
else
{
$result['res'] = 0;
}
return json_encode($result);//at the end of the function.
}
I am trying to get the data return from a function called by a jquery ajax call. My function is located in a a php file and it looks liket his
valid_user() {
$id = $_POST('id');
if($id == 'hello'){
return true;
}
else{
return false;
}
}
and here is my ajax call
$.ajax({
type: "POST",
url: path + "valid_user",
sucess: function(msg) {
alert("Data returned: " + msg );
}
});
I have tested everthing and the function is wokring ( has been changed for this example) but I can not the return value of the function valid_id(). How do I get this? the variable msg keeps coming back empty. Thanks
From my understanding, there are several issues.
1) the method valid_user() is not been called.
2) The url doesn't look like it is correct either.
3) The "success" keyword is spelt "sucess".
4) You aren't passing any "data".
Here is an example ajax call tailored to what you may want.
$.ajax({
type: "POST",
url: "validateUser.php",
data: "id=49",
success: function(msg){
alert( "true or false: " + msg );
}
});
It looks like you misspelled sucess----but this may not be in your running code. You should check the second parameter of success:
success:function(data, textStatus)
You need to write PHP server-side code that calls the function and writes its return value to the output stream. For example:
<?php echo valid_user(); ?>
This should work - you might want to put better sanitizing on the POST value just in case.
In the PHP file:
$id = isset($_POST['id']) ? trim($_POST['id']) : '';
$return = 'false';
if($id!=''){
valid_user($id);
}
echo $return;
valid_user($id) {
if($id == 'hello'){
$return = 'true';
}
}
jQuery Call:
<script>
id = 'hello';
$.ajax({
type: "POST",
url: "validateUser.php?id="+id,
success: function(msg) {
alert("Data returned: " + msg );
}
});
</script>
Thank you for your help, I figured out the issue, the reason why it was not working was becuase my function valid_id() was returning true or false, and I needed to return echo "true"; and echo "false"; once I did this the msg variable contained the data true or false.