dimanche 28 juin 2015

Ajax Append Multiple Value Array to formData

Project

Overall: I've built large form that includes a section for building dynamic sequences to demonstrate how to do some activity. This form currently submits all input data via ajax formData.

Focus: I'm trying to append a dynamic array for sequences, each to include an image ID & <textarea> description to an Ajax formData.

Problem

Not sure how to write my array to get both indexed items combined in the same array to send to server to create a comma:

'ajax_seq_image[0]':'1',
'ajax_seq_desc[0]':"This is the value from textarea description for sequence[0]",
'ajax_seq_image[1]':'22',
'ajax_seq_desc[1]':"This is the value from textarea description for sequence[1]",
...

I have searced and tested a number of diffent approaches I've discovered, but none of these are getting me the result I'm looking for.

Current JSFiddle

I've built a jsfiddle for basic testing. So far I've been able to get the alerts (notice: they are commented out) to successfully show me the variables for each index [i], however I'm not able to append the new items to formData.

jsFiddle

Additional Info

To give idea of the input data that has been sent successfully & working correctly already...

// General Data
'ajax_unit_id'  : $('input[name =   unit_id]').val(),
'ajax_title'    : $('input[name =   title]').val(),
'ajax_status'   : $('select[name    =   status]').val(),
'ajax_access'   : $('select[name    =   access]').val(),
...

Django - AJAX Request returns 500 INTERNAL SERVER ERROR

I am trying to simply update a boolean form value by using an ajax function to update it, because why would I want it to reload, but anyways, I have checked that I am passing the csrf_token, and made sure that's not a problem. I was thinking it was a problem with my urls.py, but I'm not sure exactly what it is.

What can I do to fix this error?

heres my views.py for the ajax form, note: project_complete is a booleanfield in my model

@login_required
def ProjectDetailToDoCForm(request):
    form = ProjectToDoCForm(request.POST or None)
    if form.is_valid() and request.is_ajax():
        args = {}
        args.update(csrf(request))
        ajaxVal = request.POST.get('booleanValue')
        args['doneBool'] = ajaxVal.project_complete
        return HttpResponse(json.dumps(args), content_type="application/json")

javascript

<script type="text/javascript">
    $(document).on("submit", "#project_edit_date", function(e){
        e.preventDefault();
        updateForm();
    });

    function updateForm() {

        function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }  

        $.ajaxSetup({
            beforeSend: function(xhr, settings) {
                if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
                    // Only send the token to relative URLs i.e. locally.
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                }
            }
        });

        $.ajax({
            url: "{% url 'projects:todoc_form' %}",
            type: "POST",
            datatype: "json",
            data: {booleanValue : $("#id_project_complete").val()},

            "beforeSend": function(xhr, settings) {
                console.log("Before Send");
                $.ajaxSettings.beforeSend(xhr, settings);
            },

            success: function(json){
              console.log(json);
              console.log("success");
            },

            error:function(xhr,errmsg,err){
                console.log(err);
            }
        });
    }
</script>

form

<form action="" method="post" id="project_edit_date">{% csrf_token %}
   <label for="todoc">Task Done?</label>
   <span name="todoc" id="check_done">   {{todocform.project_complete}}</span>
   <button type="submit" id="project_edit_button">
        <span>Update</span>
   </button>
</form>   

urls.py

urlpatterns = patterns('',
    url(r'^$', views.ProjectView.as_view() , name='project'),
    url(r'^create/$', views.createproject, name='create'),
    url(r'^edit/(?P<slug>[\w-]+)/$', views.ProjectDetail.as_view(), name='indproject'),
    url(r'^view/(?P<slug>[\w-]+)/$', views.ProjectDetailPublic.as_view(), name='pproject'),
    url(r'^form/(?P<slug>[\w-]+)/$', require_POST(ProjectDetailForm.as_view()), name='indproject_form'),
    url(r'^update/(?P<slug>[\w-]+)/$', require_POST(ProjectDetailToDoForm.as_view()), name='todo_form'),
    url(r'^complete/$', ProjectDetailToDoCForm, name='todoc_form'),
)

Understanding ajax gallery and categories

I'm trying to make category based gallery with ajax/php/mysql. On the index page are loaded bunch of images. They have href link to the page where user can see only selected image from that category. Now I want to make two buttons for next and prev links so the user can navigate to next image from that category.

The problem is that I'm not sure that I understand it how exactly work the ajax part and how I can "give" the category ID.

This is the link from the index page

<a href="test.php?image_id='.$row['image_id'].'"></a>

This is on the test.php

<head>
<script type="text/javascript">
$(document).ready(function() {

   $.post( "getpicture.php", { img_category: "1"}, function( data ) {
     $(".main-post").html( data );
   });

   $(".main-post").on("click",".get_pic", function(e){
       var image_id = $(this).attr('data-id');
     $(".main-post").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
     $.post( "getpicture.php", {  img_category: 1 }, function( data ) {
     $(".main-post").html( data );
   });
   return false;
   });

});
</script>
</head>
<body>
   <article class="main-post">
     // HERE THE IMAGE IS LOADED
   </article>
</body>

This is the source in getpicture.php

//get pic id from ajax request
if(isset($_POST["img_category"]) && is_numeric($_POST["img_category"]))
{
    $current_picture = filter_var($_POST["img_category"], FILTER_SANITIZE_NUMBER_INT);
}else{
    $current_picture=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);

if ($mysqli->connect_error){  
    die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

//get next picture id
$result = $mysqli->query("SELECT image_id FROM images WHERE image_id > $current_picture ORDER BY image_id ASC LIMIT 1")->fetch_object();

if($result){
   $next_id = $result->image_id;
}

//get previous picture id
$result = $mysqli->query("SELECT image_id FROM images WHERE image_id < $current_picture ORDER BY image_id DESC LIMIT 1")->fetch_object();
if($result){
   $prev_id = $result->image_id;
}

//get details of current from database
$result = $mysqli->query("SELECT image_name, image_title, image_hits FROM images WHERE img_category =  $current_picture LIMIT 1")->fetch_object();
if($result){

  //construct next/previous button
  $prev_button = (isset($prev_id) && $prev_id>0)?'<a href="#" data-id="'.$prev_id.'" class="get_pic"><img src="prev.png" border="0" /></a>':'';
  $next_button = (isset($next_id) && $next_id>0)?'<a href="#" data-id="'.$next_id.'" class="get_pic"><img src="next.png" border="0" /></a>':'';

//output html
echo '
      <h1><a href="#">'.$result->image_title.'</a></h1>
        <div class="pull-right">
         '.$prev_button.'
         '.$next_button.'
        </div>
        <div class="article-content">
           <img  src="upload/'.$result->image_name.'" alt=""/>            
        </div>';    
}    

It's clear that I'm kind of new in this field and still learning but can't understand this.

Right now I click on image with ID=431 on test.php is loaded first row from database id=1 and when I click on next button doesn't change anything.. just refreshing the image that is current.

UPDATE: image table structure

image_id
image_name
image_type
image_size
image_alt
image_path
img_category

image_category table

category_id
category_name

Ajax calls in an interval slows down map

I am building a tracking app that takes locations from a database that is updated frequently and put the last updated data as the marker..I use a ajax call in an interval that is called in every second to retrieve live updating data..

 $.ajax({
     type: "POST",
     async:false,
     dataType: "json",
     url: "{{ url('/tracking_mysql/bt6pmSWHTfnOAjfJMlSvRQ==') }}",
     success: function(data)
     {
      @foreach($eventUsers as $eventUser)
        markers['marker' + '{{$eventUser->userId}}'] = null ;
      @endforeach
      $.each(data,function(u,v){
      markers['marker' + v['user_id']] = new google.maps.LatLng(v['Location'].split(' ')[0],v['Location'].split(' ')[1]);
     lastUpdatedTimes['lastUpdatedTime' + v['user_id']] = v['time'];
   });
  }
});

and the controller that passes the current locations is :

 public function get_locations($eventid)
    {
            $eventId = $event_group_Idarray[0];
            $locations = DB::table('locations')
                ->select('time', 'Location','user_id')
                ->join(DB::raw('( SELECT MAX(id) as Id FROM locations GROUP BY user_id ) AS newest'), function($join)
                {
                    $join->on('locations.id', '=', 'newest.id');
                })
                ->where('event_id',$eventId)
                ->get();

            print_r(json_encode($locations));
    }

the problem is during each ajax call the map updation freezes for a moment.I am sure the problem is using ajax calls in an interval..I commented the ajax call and passed random markers in an interval,the map was smooth..is there any solution that can be used for my purpose ?

How to use JSON.parse in react.js

I want to pass the JSON data in "about" as html:

   "bacon": {
        "image": "bacon.jpg",
        "about":"<div>Bacon ipsum dolor amet frankfurter prosciutto kevin pork loin filet mignon pastrami bacon biltong. <strong>Cupim spare ribs alcatra kevin sausage beef ribs shankle meatloaf rump beef.<\/strong> Meatball tri-tip ground round bresaola. Pastrami boudin corned beef beef kielbasa</div>",
        "title":"About Me:"
    }

I am using React.js and here is my code:

var Bacon = React.createClass({
    getInitialState: function() {
        return {data: []}
    },
    componentWillMount: function() {
        $.ajax({
            url: 'data/data.json',
            dataType: 'json',
            success: function(data) {
                this.setState({data: data.bacon});
            }.bind(this),
            error: function(xhr, status, error) {
                var err = JSON.parse(xhr.responseText);
                console.log(err.Message);
            }
        });
    },
    render: function() {
        return (
            <p className="bacon">{this.state.data ? JSON.parse(this.state.data.bacon) : " "}</p>
        )
    }
});

This fails with

"Uncaught SyntaxError: Unexpected token u"

If I remove JSON.parse() from the data state, then the data is retrieved but all of the html is output as a string.

I think that maybe JSON.parse is still attempting to execute before the data is set in state, but I am using the ternary to check if data is loaded. So "p" should have one empty space until the data loads.

Does anyone know what I am doing wrong here?

jquery mobile going back to previous page becomes blank for seconds

From page1, ajax load page2, then change to page2, slide effect works fine.

$(":mobile-pagecontainer").pagecontainer("change",  "#page2", {transition : "slide"} );

From page2, ajax load page3, then change to page3, slide effect works fine. From page3, call $.mobile.back(); slide back to page2, works fine.

However from page2, call $.mobile.back(); the screen will become blank for about 1 or 2 seconds before going back to the page1. (there is no slide effect).

Any idea? thanks.

How can I change the maximum upload file size in document manager in telerik editor

I have customize the telerik editor which is build on asp.net ajax shown in image.enter image description here

currently the document upload size in 10.00 MB so how can i increase upload document size to 50.00 MB.