Asked  2 Years ago    Answers:  5   Viewed   104 times

When I'm trying to make an AJAX call from php (localhost) to django (localhost:8000), it throws the following error.

XMLHttpRequest cannot load http://localhost:8000/project/login/uid=bimt;token=KAMWMS151UWP67Q. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

$(document).on('click', '.login', function(event) {
    var username = $('#username').val();
    var token = $('#token').val();
    $.ajax({
       type: "POST",
       url: "http://localhost:8000/project/login/uid=" + username + ";token=" + token,
       success: function (html) {
         alert(html);
        }
     });
});

 Answers

4

Because the port is not the same, it's considered a cross origin request. You must set a Access-Control-Allow-Origin header in the script you are requesting.

Learn more:

http://enable-cors.org/server.html

or, specifically for django:

http://chase-seibert.github.io/blog/2012/01/27/using-access-control-allow-origin-to-make-cross-domain-post-requests-from-javsacript.html

Saturday, November 19, 2022
 
rewind
 
3

you have to use the SQL Server native driver for php at first place, then you can do something like:

$serverName = "tcp:sample.database.windows.net, 1433";

$connectionOptions = array("Database" => "sampleInit", 

                           "UID" => "[email protected]",

                           "PWD" => "samplePass",

                           "MultipleActiveResultSets" => false);

$conn = sqlsrv_connect($serverName, $connectionOptions);

if($conn === false)

{

     die(print_r(sqlsrv_errors(), true));

}

You can read more on PHP and SQL Azure at following blog post:
http://blogs.msdn.com/b/brian_swan/archive/2010/02/12/getting-started-with-php-and-sql-azure.aspx

Tuesday, October 4, 2022
1

Ok, there is a kind of solution, I do not really like it, but it is something instead of nothing.

The idea is to use more smart "sleep", there is a method waitUntil() which takes an anonymous function and timeout in milliseconds. What is does - runs this passed function in loop until timeout hits or your function return True. So you can run something and wait until context is changed:

$this->waitUntil(function () {
    if ($this->byCssSelector('h1')) {
        return true;
    }
    return null;
}, 5000);

I still will be glad if somebody give better solution.

Saturday, October 15, 2022
5

See below for how I changed your code. The csrf_token is assigned to a variable with Django templating. You can produce this variable in any of your Javascript code.

The token is then included in the header

 <script>
    var token = '{{csrf_token}}';

    $("#id_username").change(function () {
      console.log($(this).val());
      var form = $(this).closest("form");
      $.ajax({
        headers: { "X-CSRFToken": token },
        url: form.attr("data-validate-username-url"),
        data: form.serialize(),
        dataType: 'json',
        success: function (data) {
          if (data.is_taken) {
            alert(data.error_message);
          }
        }
      });

    });
  </script>
Friday, August 26, 2022
1

The problem is that your custom property descriptor is bound to a concrete instance. Which works when you use single item data binding (like TextBox to your object property or selecting your object in a PropertyGrid control). However, when you use a control that requires list data binding (like DataGridView, ListView, ListBox, ComboBox list etc.) this technique doesn't work. In order to auto populate the columns, DataGridView needs a set of properties that are common to all items. In order to do that, it tries several ways to obtain that information (a good explanation can be found here DataGridView not showing properites of objects which implement ICustomTypeDescriptor), and one of them is to take the first item of the list and ask for properties (hence your debugging experience). Anyway, in order to make this work in a list binding scenarios, your property descriptor needs to be implemented differently.

Notice the signature of the PropertyDescriptors GetValue/SetValue methods. Both they have an argument object component. This is the object instance you need to return or set the value. You can think of property descriptor being an inverse of what we usually use in a programming language. So instead of

var val = obj.Property;
obj.Property = val;

we have

var val = propertyDescriptor.GetValue(obj);
propertyDescriptor.SetValue(obj, val);

In other words, you should not "embed" your object instance inside the property descriptor, but use the passed argument.

Here is a sample generic implementation of a property descriptor doing just that:

public class SimplePropertyDescriptor<TComponent, TValue> : PropertyDescriptor
    where TComponent : class
{
    private readonly Func<TComponent, TValue> getValue;
    private readonly Action<TComponent, TValue> setValue;
    private readonly string displayName;
    public SimplePropertyDescriptor(string name, Attribute[] attrs, Func<TComponent, TValue> getValue, Action<TComponent, TValue> setValue = null, string displayName = null)
        : base(name, attrs)
    {
        Debug.Assert(getValue != null);
        this.getValue = getValue;
        this.setValue = setValue;
        this.displayName = displayName;
    }
    public override string DisplayName { get { return displayName ?? base.DisplayName; } }
    public override Type ComponentType { get { return typeof(TComponent); } }
    public override bool IsReadOnly { get { return setValue == null; } }
    public override Type PropertyType { get { return typeof(TValue); } }
    public override bool CanResetValue(object component) { return false; }
    public override bool ShouldSerializeValue(object component) { return false; }
    public override void ResetValue(object component) { }
    public override object GetValue(object component) { return getValue((TComponent)component); }
    public override void SetValue(object component, object value) { setValue((TComponent)component, (TValue)value); }
}

sample usage with your stuff:

public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    var properties = base.GetProperties(attributes);
    // Custom name property
    properties.Add(new SimplePropertyDescriptor<FeaturePropertyPresentation, string>("FeatureName", attributes,
        getValue: component => component.m_feature.m_name,
        setValue: (component, value) => component.m_feature.m_name = value, // remove this line to make it readonly
        displayName: "Feature Name"
    ));
    return properties;
}

and, putting it all together, a small example equivalent to yours:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace Samples
{
    // Generic implemenation of a property descriptor
    public class SimplePropertyDescriptor<TComponent, TValue> : PropertyDescriptor
        where TComponent : class
    {
        private readonly Func<TComponent, TValue> getValue;
        private readonly Action<TComponent, TValue> setValue;
        private readonly string displayName;
        public SimplePropertyDescriptor(string name, Attribute[] attrs, Func<TComponent, TValue> getValue, Action<TComponent, TValue> setValue = null, string displayName = null)
            : base(name, attrs)
        {
            Debug.Assert(getValue != null);
            this.getValue = getValue;
            this.setValue = setValue;
            this.displayName = displayName;
        }
        public override string DisplayName { get { return displayName ?? base.DisplayName; } }
        public override Type ComponentType { get { return typeof(TComponent); } }
        public override bool IsReadOnly { get { return setValue == null; } }
        public override Type PropertyType { get { return typeof(TValue); } }
        public override bool CanResetValue(object component) { return false; }
        public override bool ShouldSerializeValue(object component) { return false; }
        public override void ResetValue(object component) { }
        public override object GetValue(object component) { return getValue((TComponent)component); }
        public override void SetValue(object component, object value) { setValue((TComponent)component, (TValue)value); }
    }
    // Your stuff
    public abstract class PropertyPresentationSubBase : ICustomTypeDescriptor
    {
        public string GetClassName()
        {
            return TypeDescriptor.GetClassName(this, true);
        }

        public AttributeCollection GetAttributes()
        {
            return TypeDescriptor.GetAttributes(this, true);
        }

        public String GetComponentName()
        {
            return TypeDescriptor.GetComponentName(this, true);
        }

        public TypeConverter GetConverter()
        {
            return TypeDescriptor.GetConverter(this, true);
        }

        public EventDescriptor GetDefaultEvent()
        {
            return TypeDescriptor.GetDefaultEvent(this, true);
        }

        public PropertyDescriptor GetDefaultProperty()
        {
            return TypeDescriptor.GetDefaultProperty(this, true);
        }

        public object GetEditor(Type editorBaseType)
        {
            return TypeDescriptor.GetEditor(this, editorBaseType, true);
        }

        public EventDescriptorCollection GetEvents(Attribute[] attributes)
        {
            return TypeDescriptor.GetEvents(this, attributes, true);
        }

        public EventDescriptorCollection GetEvents()
        {
            return TypeDescriptor.GetEvents(this, true);
        }

        public virtual PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            PropertyDescriptorCollection rtn = TypeDescriptor.GetProperties(this);

            //rtn = FilterReadonly(rtn, attributes);

            return new PropertyDescriptorCollection(rtn.Cast<PropertyDescriptor>().ToArray());
        }

        public virtual PropertyDescriptorCollection GetProperties()
        {

            return TypeDescriptor.GetProperties(this, true);

        }


        public object GetPropertyOwner(PropertyDescriptor pd)
        {
            return this;
        }

        [Browsable(false)]
        public PropertyPresentationSubBase Parent
        {
            get
            {
                return m_Parent;
            }
            set
            {
                m_Parent = value;
            }
        }

        PropertyPresentationSubBase m_Parent = null;

        [Browsable(false)]
        public Type ValueType
        {
            get
            {
                return valueType;
            }
            set
            {
                valueType = value;
            }
        }

        private Type valueType = null;

        [Browsable(false)]
        public string Name
        {
            get
            {
                return sName;
            }
            set
            {
                sName = value;
            }
        }



        public abstract object GetValue();

        private string sName = string.Empty;

        public abstract void Change(object value);
    }
    public class QuadriFeatureItem
    {
        public QuadriFeatureItem(int featureId, string name)
        {
            m_featureId = featureId;
            m_name = name;

        }
        public int m_featureId;

        public string m_name;
    }
    class FeaturePropertyPresentation : PropertyPresentationSubBase
    {

        public int FeatureId
        {
            get
            {
                return m_feature.m_featureId;

            }
            set { m_feature.m_featureId = value; }
        }

        public FeaturePropertyPresentation(QuadriFeatureItem item)
        {
            m_feature = item;
        }

        private QuadriFeatureItem m_feature;

        public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            var properties = base.GetProperties(attributes);
            // Custom name property
            properties.Add(new SimplePropertyDescriptor<FeaturePropertyPresentation, string>("FeatureName", attributes,
                getValue: component => component.m_feature.m_name,
                setValue: (component, value) => component.m_feature.m_name = value, // remove this line to make it readonly
                displayName: "Feature Name"
            ));
            return properties;
        }
        public override void Change(object value)
        {
            throw new NotImplementedException();
        }

        public override object GetValue()
        {
            return this;
        }

    }
    // Test
    static class Test
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var dataSet = Enumerable.Range(1, 10).Select(n => new FeaturePropertyPresentation(new QuadriFeatureItem(n, "Nummer" + n))).ToList();
            var form = new Form();
            var dg = new DataGridView { Dock = DockStyle.Fill, Parent = form };
            dg.DataSource = dataSet;
            Application.Run(form);
        }
    }
}

result:

Saturday, September 17, 2022
 
vaidas
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 

Browse Other Code Languages