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.
Related
Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.
I have used ajax as below:
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var valueSelected = valueSelected.replace(/ /gi,"%20");
var valueSelected = encodeURIComponent(valueSelected);
//alert(valueSelected);
$.ajax({
type: 'post',
encoding:"UTF-8",
url: "<?php echo base_url();?>Search/cities_of_province/"+valueSelected,
data: '',
contentType: "charset=utf-8",
success: function (result) {
//alert(result);
$('.city').html(result);
return false;
}
});
return false;
});
valueSelected in above url is a persion statement with space in it. for example it is استان آذربایجان شرقی.
when it is post to the url, just first part(استان) is recieved.
I aslo removed valueSelected.replace(/ /gi,"%20") and encodeURIComponent(valueSelected) but nothing happend.
what is the solution?
I faced no issue like that.. I used no encodeURIComponent no encoding:"UTF-8" no contentType: "charset=utf-8"
Nothing needed. And it works simply perfect. I tested it with following code
I have Html
<input id='yourInputId' value='استان آذربایجان شرقی' />
JavaScript
<script>
var valueSelected = $('#yourInputId').val();
//before ajax request
alert(valueSelected ); // it gives me here =>استان آذربایجان شرقی
//before making ajax reuest plz confirm you get above value correctly here
alert(<?php echo base_url();?>); //it must be valid as well
$.ajax
({
type: "POST",
url: "<?php echo base_url();?>Search/cities_of_province", //should be valid
data: { province : valueSelected },
success: function (result) {
alert(result); //it gives => استان آذربایجان شرقی
},
error:function(a)
{
alert(a.responseText);
}
});
</script>
PHP
<?php
if(isset($_POST['province']))
$v = $_POST['province'];
else
$v = 'Province value not provided from client side';
echo $v;
?>
So it looks like you are using a select input here. If that is the case, you should use alphanumeric/ASCII value key in your options and not the human readable labels. That might look like:
<option value="some_ascii_key">استان آذربایجان شرقی</option>
You can then have a reliable key to use in your AJAX request.
I also think your request should be a GET and not a POST since you are just reading values from API rather than trying to create/update records via API.
Putting it all together, you might have something like this:
// note values for each property/ley may not be important here
// as they are not really needed to validate that the province key
// in option value has not been modified by client,
// which is really what you are using this for.
// If you need to have option label text available in
// javascript you can store that here as shown.
var provinceConfiguration = {
'key1': 'استان آذربایجان شرق';
'key2': 'some other Persian string';
// and so on...
}
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
// perhaps validate that value provided is amongst expected keys
// this used the provinceConfiguration object proposed in this example
if(typeof provinceConfiguration[valueSelected] === 'undefined') {
console.log('Unexpected province key passed');
e.stopPropagation();
return false;
}
// probably can drop this line if defined keys do not need encoding
var valueSelected = encodeURIComponent(valueSelected);
// since you can use default GET setting you can use this shorthand
$.get(
'<?php echo base_url();>Search/cities_of_province/' +
valueSelected,
function(result) {
// console.log(result);
$('.city').html(result);
return false;
}
);
/*
Or more verbose option
$.ajax({
type: 'GET',
// not valid setting key -> encoding:"UTF-8",
url: '<?php echo base_url();>Search/cities_of_province/' + valueSelected,
// default is fine here so not needed -> contentType: "charset=utf-8",
success: function (result) {
// console.log(result);
$('.city').html(result);
return false;
}
});
*/
return false;
});
Note that you should be using console.log() to debug code rather than alert(), as alert actually blocks code execution and may make some debugging more problematic as your debugging mechanism changes how your code executes. This can problem can be exacerbated when debugging asynchronous code.
Your server-side code would obviously need to be updated to understand the province keys as well.
Please take a look at this javascript library. That can be of help to you.
Fix Persian zero-width non-joiner(Replace spaces by half-space)
import { halfSpace } from "persian-tools2";
halfSpace("نمی خواهی درخت ها را ببینیم؟") // "نمیخواهی درختها را ببینیم؟"
Fix Persian characters in URL.
import { isPersian, toPersianChars } from "persian-tools2";
URLfix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
URLfix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
URLfix("Sample Text"); // "Sample Text"
I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.
$(document).ready(function() {
$('#username').keyup(function() {
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
})
})
})
I'm using the old $.ajax function and make sure you have a data keyed taken (as example) with boolean type on adm/chk_uname_avail.php and notice that you should return JSON data type from it.
Example of adm/chk_uname_avail.php
<?php
//return response as JSON
header('Content-type:application/json;charset=utf-8');
....
....
....
$data['taken'] = true; //show this response to ajax
echo json_encode($data);
?>
Ajax
$(document).ready(function() {
$('#username').on('keyup', function() {
$.ajax({
type: 'POST',
url: 'adm/chk_uname_avail.php',
data: {uname : changeuser.username.value},
success: function(result) {
var $btn = $('#submiButton');
if (result.taken) {
$btn.prop('disabled', true);
} else {
$btn.prop('disabled', false);
}
//As #Mikey notice, You can just use this as simply as
//$('#submiButton').prop('disabled', result.taken);
}
});
});
});
Use .attr() method of jQuery to make the submit disabled on certain condition.
So you can update your jQuery like this,
$.post('adm/chk_uname_avail.php', {
uname : changeuser.username.value
}, function(result){
$('#available').html(result);
if(/* CHECK FOR CERTAIN CONDITION */) {
$('#submit_btn').attr('disabled','disabled');
}
});
To remove the disabled attribute you can use removeAttr() method of jQuery. Like this,
$('#submit_btn').removeAttr('disabled');
http://api.jquery.com/attr/
https://api.jquery.com/removeAttr/
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.
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/