Call Dialog.Modal with error - php

I think I'm missing something here.
in Script:
$('#dialog:ui-dialog').dialog('destroy');
$('#dialog-modal').dialog({ width:150, height:150, resizable:false, draggable:false, autoOpen:true, modal:true });
I use AJAX to call for Data, when the pull detect an error, I want it to pop up an dialog.modal, but it just won't do so. I think I'm missing something here.
in PHP:
case ($amt > $total_storage):
echo "<div id='dialog-modal' class='ui-dialog-content ui-widget-content' title='Error!'><p>Not enough Storage!</p></div>"; (this one don't work)
echo "Test Error"; (this one works)
break;
I tested with echo and it does display "Error" but not the dialog.modal. I just want it to autoOpen when it detects an error.
New Workable Version:
PHP:
case ($amt > $total_storage):
echo ":err:<p>Not enough Storage!</p></div>";
break;
JS:
function CitySell(a){
$.ajax({
beforeSend: function(){ $(".Bags").attr("disabled", "disabled"); },
url: "DataPull.php?get=CitySell&SSIDD="+$('.SDI_'+a).val()+"&SSAmD="+$('.STS_'+a).val(),
success: function(data){
$('#Listing').html(parseScript(data));
if(data.substr(0,5) === ':err:'){
$('<div id="dialog-modal" class="ui-dialog-content ui-widget-content" title="Error!">').html(data.substr(5)).dialog({width:250, height:150, resizable:false, draggable:false, autoOpen:true, modal:true});
$('.Bags').removeAttr("disabled");
} else {
Listing();
CommonUpdates();
}
}
})
}

Wrap you js code into a function
function open_dialog(error_text)
{
$('#dialog:ui-dialog').dialog('destroy');
$('#dialog-modal')
.html(error_text)
.dialog({ width:150, height:150, resizable:false, draggable:false, autoOpen:true, modal:true });
}
and make a function call at the onSuccess method
$.get(url, function(result){ open_dialog(data); })
Though you'll have to distinguish between cases when the response indicates an error and when it's not. You could add some characters to the response to see whether it's an error or not:
case ($amt > $total_storage):
echo ":err:<p>Not enough Storage!</p></div>";
break;
$.get(url, function(result){ if(data.substr(0,5) === ':err:') open_dialog(data); else alert(data); })

You are trying to return the html for the dialog which is what is likely causing problems, since it doesn't exist when you try to initiate the dialog
If you return your data as json it makes it much simpler
echo json_encode( array('status'=>'error', 'message'=>'Your error message') );
Then in success callback of ajax:
$.get( url, function(data){
if( data.status=='error'){
$('<div id="dialog-modal">').html( data.message).dialog( // dialog options)
}
},'json');

Related

if else condition in jquery ajax response

I have one Ajax function which is running properly.but i want when my Ajax response is
<h3>No Couriers found near by you.please select another location</h3>
i want to display some error message else i want to display another map div in else condition.
but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when
<h3>No Couriers found near by you.please select another location</h3>
but still it not comes in if condition..can anyone help me to do this....
<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
var checked = $(this).is(':checked');
if($(this).is(":checked")) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
data: {
frmlat: $("#PoolLatitude").val(),
frmlong: $("#PoolLongitude").val(),
mylocation: $("#PoolLocation").val()
},
dataType: "html",
success: function(response) {
alert(response);
if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
alert(thanks);
} else {
$('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
$("#load_map").html(response);
}
},
complete: function() {
$('.spinicon').hide();
}
});
} else {
$("#secretcode").val("");
}
});
</script>
In your php script, return a boolean flag instead of a string :
<?php
if (some_condition) {
$return = true;
} else {
$return = false;
}
die(json_encode(array('return' => $return)));
And in the ajax success :
...
dataType: 'json',
success: function(data) {
if (data.return) {
alert("return is true");
} else {
alert("return is false");
}
},
...
Hope it helps.
PS : use Json Encode to parse the response and access values easily.
First of all, i suggest you to use status for ajax response something like:
1 for success
0 for failure
Than, as per your statement, your are getting the correct response in:
alert(response);
Than, you must need to check either response having <h3></h3> tags or not.
In your code, the main issue is that, you are using string without quotes in alert alert(thanks); this will return undefined thanks in console and treated as a variable.
This should be alert("thanks");
One more suggestion, it's always better to check browser console when you are not getting success in Ajax or any other script, this will help you to find the errors.

ajax callback not working

i cannot seem to get a callback to work from this but it gets a response its a simple test. anyone know why it dosnt do as i want
<script type="text/javascript">
$(document).ready(function(e) {
$("button").click(function() {
var msg = $("#txt").val();
$.post(
"http://localhost/bot.php",
{msg: msg},
function(data,status) {
$("p").text(data);
}
);
});
});
</script>
The PHP, and could anyone suggest a good JavaScript tool to help me find errors?
<?php
class ai
{
private $msg;
public function __construct($msg)
{
$this->msg = $msg;
}
public function respond()
{
switch($this->msg)
{
case "hi":
echo "Hello Mr Brown How are You";
break;
case "fine":
echo "Good to hear Did you know Zanda hard Coded me?";
break;
case "im fine":
echo "Good to hear Did you know Zanda hard Coded me?";
break;
default:
echo "??????????????????????????????" .
"That means i was extra rush prototype.......i cant answer that";
}
}
}
$talk = new ai($_POST['msg']);
$talk->respond();
?>
<div class="box">
<p>text</p>
<textarea id="txt"></textarea>
<button>click</button>
</div>
there is the html made it as short as can be
Something to try here too is to change your $.post for $.ajax so you can specify an error callback. $.get, $.post etc are just shorthands for $.ajax anyhow. Try something like this:
("button").click(function() {
var msg = $("#txt").val();
$.ajax(
url: "http://localhost/bot.php",
data: {msg: msg},
dataType: 'jsonp',
success: function(data,status) {
console.log(data, "returned with status:", status);
},
error: function(obj, status, error){
console.log("Error!", obj, status, error);
}
);
});
Just because you're getting a 200 response doesn't mean everything's working correctly. All that's saying is that the POST was successful. You need to check the response text to see if any errors are being returned.
EDIT: added in dataType: 'jsonp' to request.
It seems like it is due to the Same Origin Policy and from the MDN documentation
The port number is kept separately by the browser. Any call to the setter, including document.domain = document.domain causes the port number to be overwritten with null. Therefore one can not make company.com:8080 talk to company.com by only setting document.domain = "company.com" in the first. It has to be set in both so that port numbers are both null.
So that is the reason you are getting null as you said in your responses
Try adding datatype:"jsonp". It shoudl work like this.
$(document).ready(function(e) {
$("button").click(function() {
var msg = $("#txt").val();
$.post(
"http://localhost/bot.php",
{msg: msg},
function(data,status) {
$("p").text(data);
},
dataType:"jsonp"
);
});
});
Further reading here.
Hope that helps.

ajaxFileUpload on xhr.setRequestHeader is not a function

In my footer.php I have this code which i needed for my api references
<script type="text/javascript">
/** Override ajaxSend so we can add the api key for every call **/
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
});
</script>
It works fine in my project without any error but when I started working on file upload and I'm using ajaxfileupload to upload file, I got this error whenever i upload the file.
TypeError: xhr.setRequestHeader is not a function
xhr.setRequestHeader("KEY", "123456POIUMSSD");
Here is my ajaxfileuplod program code:
<script type="text/javascript">
$(document).ready(function() {
var DocsMasterView = Backbone.View.extend({
el: $("#documents-info"),
initialize: function () {
},
events: {
'submit' : 'test'
},
test: function (e) {
e.preventDefault();
var request = $.ajaxFileUpload({
url :'./crew-upload-file',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
request.abort();
return false;
}
});
var x = new DocsMasterView();
});
</script>
Can anyone here fix my problem. Any suggestion/advice in order to solve my problem.
As I understand from your comments, setRequestHeaders works fine with regular ajax calls. At the same time it is not available when ajaxFileUpload is used. Most likely that is because transport method does not allow to set headers (for instance, in case when iframe is used to emulate upload of files in ajax style) . So, possible solution is to place a key into your form data:
$(document).ajaxSend(function(e, xhr, options)
{
if(xhr.setRequestHeader) {
xhr.setRequestHeader("<?php echo $this->config->item('rest_key_name');?>", "<?php echo $this->session->userdata('api_key')?>");
else
options.data["<?php echo $this->config->item('rest_key_name');?>"] = "<?php echo $this->session->userdata('api_key')?>";
});
Note: I'm not sure if options.data is a correct statement, just do not remember structure of options object. If proposed code does not work - try to do console.log(options) and how
to get an object with data that should be posted (it might be something like options.formData, I just do not remember exactly)
And on server side you will just need to check for key in headers or form data.

jQuery $.post Callback Function (data) is Undefined

I submit a form using jQuery to a php file on my server.
Everything works... (the php file gets the right post variables, makes a database entry etc.)
But on the response, sometimes 'data' goes wacky.
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
if ( data.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
}, "json");
});
php script returns (on success)
$response['status'] = 1;
$response['message'] = 'worked';
echo json_encode($response);
exit();
I'm getting a whole lot of crap, and not enough awesome sauce.
Does anyone have an idea why sometimes 'data.status' is undefined, and sometimes it isn't?
Try it like this>
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize(), function(data) {
var obj = jQuery.parseJSON(data);
if ( obj.status == 1 ) {
alert('awesome sauce');
} else {
alert('crap');
}
});
});
How does exit() behave with regards to output buffering? Does it flush the output buffer?
try this one:
$('#form_submit').click( function() {
$.post("path/to/script.php", $('#form').serialize())
.success(function(){
alert('awesome sauce');
}).error(function(){
alert('crap');
});
});

livevalidation.js custom username check function

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

Categories