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.
}
Related
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 have one issue with ajax when I get echo success on my php. I don't get execute the first if
if(text[0]==="success")
Code inside php
if(count($error)==0)
{
$user = ORM::for_table('usuario')->create();
$user->username = $username;
$user->contrasenia = password_hash($password, PASSWORD_DEFAULT);
$user->email = $email;
$user->admin = $is_admin;
$user->save();
echo "success";
}
else
{
$error = json_encode($error);
echo $error;
}
My code in ajax
[![$("#create-button").on('click', function(event){
//cancels the form submission
event.preventDefault();
submitForm();
});
function submitForm()
{
var dataString = $("#userForm").serialize();;
$.ajax({
dataType: "json",
type: "POST",
url: "/altausers",
data: dataString,
success: function(text)
{
console.log("hola");
console.log(text);
if(text\[0\]==="success")
{
alert("hola");
//$("#error").addClass('hidden');
}
else if(text.length > 0)
{
$("#error").removeClass('hidden');
texterror = "<ol type='disc'>";
$.each(text,function(index,value)
{
texterror+="<li>"+value+"</li>";
});
texterror+="</ol>";
document.getElementById("error").innerHTML = texterror;
}
}
});
}
Image console
What is the problem?
Could say me which it is problem?
I have that convert the message success to json too
Replace the success echo with
echo json_encode(["success"]);
or leave echo the same and replace if in ajax
if(text == "success")
The problem could be that it is an array, so you can try this:
$.ajax({
url: "items.php",
async: false,
type: "POST",
dataType: "JSON",
data: { "command" : "getItems" }
}).success(function( response ) {
alert( response.fruits.apple );
alert(Object.keys(response).length);
});
And if you want to see the results:
Object.keys( response ).forEach(function( key ) {
console.log('key name: ', key);
console.log('value: ', response[key]);
});
I want to set a divs in conditions IN my View but I don't know how to I do it.If the request from controller comes true to him then success div appear otherwise failure div. At the time I am just printing true and false in alert boxes.
Here is my View:
<div class = "success">operation done successfully </div>
<div class = "failiour">operation done successfully </div>
//these are the two divs on which i want to apply a condition
<form>
</form>
<script type="text/javascript">
$('#btn').click(function() { // $("#form").serialize()
var item_name = $('#item_name').val();
var cat_id = $('#selsear').val();
if (!item_name || item_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
item_name: $('#item_name').val(),
cat_id: $('#selsear').val(),
};
$.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);
}
}
});
return false;
});
</script>
my controller
function additems(){
//getting parameters from view
$data = array(
'item_name' => $this->input->post('item_name'),
'cat_id' => $this->input->post('cat_id')
);
//$is_ajax = $this->input->post('ajax'); //or use this line
//$this->input->is_ajax_request();
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query){ //&& any other condition
$result['res'] = 1;//process successful - replace 1 with any message
}
else
{
$result['res'] = 0;//process failed - replace 0 with any message
}
echo json_encode($result);//at the end of the function.
}
}
Set display none through css in your both success and failure div and then do this :
$.ajax({
url: "",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").fadeIn(500).delay(2000).fadeOut(500);
}
else
{
$(".failiour").fadeIn(500).delay(2000).fadeOut(500);
}
}
});
first hide your divs
<div class = "success" style="display:none;">operation done successfully </div>
<div class = "failiour" style="display:none;">operation done successfully </div>
then if you are get reuests multiple times
$.ajax({
url: "",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").show();
$(".failiour").hide();
}
else
{
$(".failiour").show();
$(".success").hide();
}
}
});
In your script,
//supposing you are getting the result in response varible
if(response == true) // simply write: if(response)
{
document.getElementById('success').style.display='block';
document.getElementById('failure').style.display='none';
}
else
{
document.getElementById('success').style.display='none';
document.getElementById('failure').style.display='block';
}
//Add IDs to divs and add style block/none according to your requirement
<div id="success" style="display:block;"></div>
<div id="failure" style="display:none;"></div>
I'm submitting a form via jQuery.ajax()
Now my PHP script is checking if a specific input field is empty, example:
$is_error = $user->is_error;
if($is_error !=0)
{
echo $is_error;
}
Back to my jQuery.ajax() , I'd like to check if the value of $error was true or not, within the sucess: part of the jQuery.ajax() call.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if there is an error message
// like:
// if(is_error) {show specific error message}
// else {show everything positive message}
}
});
Is it possible to check the PHP variable's value in there? Like if/else ?
Best regards!
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
This code will echo the value.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if $error == 0 or $error == 1.
if(data==1)
....
}
});
Then you check what is the returned value.
With your variable data, you can return values from PHP. And after in your scope success you can check.
You have to echo the error so that it can be returned as data.. The ajax only returns what has been created in html..
In instances like this I would use the following:
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(response)
{
if(response == 1){
alert('Error');
}else{
alert('No error');
}
}
});
i think you should try the following in php script
echo $error;
and then in jquery.ajax() do
success: function(data){
//data is $error
}
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.