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.
Related
I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.
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.
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.
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');
nothing is being sent with $.post
function clicked()
{
var $contact_title=$("#contact_title");
var $contact_summary=$("#bbcode");
alert($contact_title.val());// How do I get the contents of the title
alert($contact_summary.val());// How do I get the contents of the textarea
$.post('jquery_send_admin.php',{ title:$contact_title, content:$contact_summary }, function(data){ alert("Message was sent") }, 'html');
}
I get exceptions in my console error..like the following:
UPDATE:
no data is inserted on the next page..why?!?
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
The following error happens:
Error: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js :: <TOP_LEVEL> :: line 16" data: no]
UPDATE:
Thats what I request from the page, which is triggered by jquery:
<?php
echo 'outside';
if( isset($_POST["title"]) && isset($_POST["content"]) )
{
echo 'inside';
$title=mysql_escape_string($_POST["title"]);
$content=mysql_escape_string($_POST["content"]);
$result=mysql_query("INSERT INTO users (query_title,query_message) VALUES(''$title', '$content')") or die(mysql_error());
}
?>
You need to extract the values using the .val() method:
var $contact_title = $('#contact_title').val();
var $contact_summary = $('#bbcode').val();
var dataToPost = { title: $contact_title, content: $contact_summary };
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
var $contact_title=$("#contact_title").text();
var $contact_summary=$("#bbcode").text();
try to get the value/text instead of just the control.
var $contact_title=$("#contact_title").text();
or
var $contact_title=$("#contact_title").val();
Edit:
Not sure how it works in PHP but I use it with vb.net and there I need to give my controller name(aka file) and function so it becomes
$.post('myFile/myJSONFunction', {all-your-parameters});
So maybe thats why it wont post your data.
Something else you might want to look at is that your php might return different data than you are actually expecting him to return.
function clicked() {
var $contact_title = $("#contact_title");
var $contact_summary = $("#bbcode");
alert($contact_title.val()); // with the val
alert($contact_summary.val()); // with the val
$.post('jquery_send_admin.php', { title: $contact_title.val(), content: $contact_summary.val() }, function (data) { alert("Message was sent") }, 'html');
}
Instead of this posted by #Darin
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert('Message was sent');
}, 'html');
use this
$.post('jquery_send_admin.php', dataToPost, function(data) {
alert(data);
});
That will show the result of the echo statements in the alert box which could possibly help you debug the issue.
Oh my. jQuery bugs, PHP debugging bugs. I'll probably get down-rates for this answer... but sometimes, it helps to simply read the manuals if you're that lost that people have to help you cross the street: http://api.jquery.com/ & http://php.net/manual/