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.

What is wrong with this syntax? how can i use $.get method inside prepend function?

for(var i=1; i<=num_rows; i++)
{
    $('#question-board').prepend('<div id=myID'+i' class=abc>'+ $.get("forum-data-retrieve.php", {q:i}); +'</div> <hr>');
}

AJAX can't received data to controller MVC

I send data by ajax to mvc controller. I get to the correct method but without data. I tried to get List<string> but its null

js code:

function sendDataCreateMilestone(parameters) {
    $.ajax({
        url: "/QRCNew/create",
        type: "post",
        dataType: "json",
        data: JSON.stringify(parameters)
    });
}

server:

here i revived all the time null

public ActionResult Create (List<string> ids, string collection)
{
    do....
}

add AJAX on custom python browser

I have a custom browser but my AJAX don't work. (work on firefox and others browsers.)

#!/usr/bin/env python
import sys
import gtk
import webkit

DEFAULT_URL = '/var/www/profile.html' # Change this as you Wish
class SimpleBrowser: # needs GTK, Python, Webkit-GTK
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
        self.window.connect('delete_event', self.close_application)
        self.window.set_default_size(1366, 743)
        self.window.set_position(0)
        vbox = gtk.VBox(spacing=0)
        vbox.set_border_width(0)
        self.txt_url = gtk.Entry()
        self.txt_url.connect('activate', self._txt_url_activate)
        self.scrolled_window = gtk.ScrolledWindow()
        self.webview = webkit.WebView()
        self.scrolled_window.add(self.webview)
        vbox.pack_start(self.scrolled_window, fill=True, expand=True)
        self.window.add(vbox)
    def _txt_url_activate(self, entry):
        self._load(entry.get_text())
    def _load(self, url):
        self.webview.open(url)
    def open(self, url):
        self.txt_url.set_text(url)
        self.window.set_title('007WallPaper')
        self._load(url)
    def show(self):
        self.window.show_all()
        #self.window.fullscreen()
    def close_application(self, widget, event, data=None):
        gtk.main_quit()
if __name__ == '__main__':
    if len(sys.argv) > 1:
        url = sys.argv[1]
    else:
        url = DEFAULT_URL
    gtk.gdk.threads_init()  
    browser = SimpleBrowser()
    browser.open(url)
    browser.show()
    gtk.main()

How can I "import" AJAX functionality into it ?

Python, scrapy: Unable to paginate dynamically generated links on website, using the link got from firebug

I am a complete newbie at python, scrapy and web scraping, this being my first learning project. I want to scrape multiple pages from this website using scrapy: http://ift.tt/1C0cyxT

The links seem to be generated using ajax. At the end of the page is the link to next page. Clicking on <2> or and checking the link generated on firebug, shows following request being generated:

GET directory?p=2&category=1&map[disable]=0&map[height]=500&map[list_height]=500&map[span]=5&map[style]=&map[list_show]=0&map[listing_default_zoom]=15&map[options][scrollwheel]=0&map[options][marker_clusters]=1&map[options][force_fit_bounds]=0&distance=0&is_mile=0&zoom=15&perpage=16&scroll_list=0&feature=1&featured_only=0&hide_searchbox=0&hide_nav=0&hide_nav_views=0&hide_pager=0&template=&grid_columns=4&sort=title

So I thought, in my limited understanding, that if i replace p={pagenum} with any page number, that should get me the required page. I tried using the following url to directly request for the page:

http://ift.tt/1CDpnZt

However, this link generates an error page saying "page not found".

Can anyone help me understand what am I doing wrong here?

Thanks for your guidance.

could not get data from file by ajax with jquery datatable

I use the sample here:http://ift.tt/1RK9fwf

Below is my html and jquery code

<html>
<head>
  <link rel="stylesheet" type="text/css" href="jquery-dataTables.css">
  
  <script type="text/javascript" charset="utf8" src="jquery-min.js"></script>
  <script type="text/javascript" charset="utf8" src="jquery-dataTables.js"></script>
  <script>
  
  $(document).ready(function() {
    $('#example').dataTable( {
        "ajax": "data/test.txt",
        "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }
        ]
    } );
} );
  </script>
  
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
 
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Extn.</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </tfoot>
    </table>
</body>
</html>

This is the structure of my file

enter image description here

But it couldn't load data into datatable, anyone can help?

Edit (Attach my test data): this data is used for

"data": [ { "name": "Tiger Nixon", "position": "System Architect", "salary": "$320,800", "start_date": "2011/04/25", "office": "Edinburgh", "extn": "5421" }, { "name": "Garrett Winters", "position": "Accountant", "salary": "$170,750", "start_date": "2011/07/25", "office": "Tokyo", "extn": "8422" }, { "name": "Ashton Cox", "position": "Junior Technical Author", "salary": "$86,000", "start_date": "2009/01/12", "office": "San Francisco", "extn": "1562" }, { "name": "Cedric Kelly", "position": "Senior Javascript Developer", "salary": "$433,060", "start_date": "2012/03/29", "office": "Edinburgh", "extn": "6224" },
{ "name": "Cara Stevens", "position": "Sales Assistant", "salary": "$145,600", "start_date": "2011/12/06", "office": "New York", "extn": "3990" },
{ "name": "Donna Snider", "position": "Customer Support", "salary": "$112,000", "start_date": "2011/01/25", "office": "New York", "extn": "4226" } ]

Thanks

Simple ajax in laravel 4

i have following code

ajax

 //ajax edit button
 $('.edit_button').on('click', function(e) {
    var id_produk = $(this).attr('id');
    $.ajax({
        type : "POST",
        url : "editproduk",
        data : id_produk,
        dataType: 'JSON',
        success : function(data) {
           alert('Success');
           console.log(data);
        },
        error: alert('Errors')
    });
});

i always get messagebox error
and don't know where i'm missing,
because in chrome - inspect element - console not give any clue

my route

Route::post('/account/editproduk', array(
    'as' => 'edit-produk-post',
    'uses' => 'AccountController@postEditProduk'
));

my controller

public function postEditProduk() {
    if (Request::ajax()) {
        return "test test";
    }
}

ajax popup display center in body

I want to load my popup center in body.. i try to do that. but its not work.. here is my link : http://ift.tt/1IER9Hj (click Add to Cart button)

head style

<script src="http://ift.tt/1xDNnh9"></script>
<script src="http://ift.tt/1IER8Tw"></script>
<script src="http://ift.tt/1HpeT5C"></script>

Jquery

<script>
      jQuery(function ($) {

        $('.button').on('click', function () {
            var id = $(this).data('id');

            $.ajax({
                url: '/shopping/ajax.php',
                data: {
                    id: id
                },
                method: 'POST',
                success: function (html) {
                    $('body').append(html);
                    $(html).bPopup();
                },
                error: function (returnValue) {}
            });
        });


    });
</script>

button html

<button type="button" class="button small cart-button" data-id="2222">Add to Cart</button>

ajax.php file

<div id="popup">
  <div class="inner">
  <h2>Item added to your cart!</h2>
  <!-- here some html and php codes -->
  </div>
</div>

Passing multiple JSON ("rows" or object) to a Controller

var POS = {
        AddItem: function (SKU) {
            $.ajax({
                type: 'POST',
                data: '{"code":"itm-0008", "qty":"5"},
                       {"code":"itm-0009", "qty":"1"},
                       {"code":"l1", "qty":"8"}',
                url: '@Url.Action("AddProduct", "POS")',
                success: function (data) {
                   alert("Items Successfully Added!");
                },
                error: function (req, status, errorObj) {
                    alert(errorObj.toString());
                }
            });
        }
};

This is my Controller: (It can only handle one(1) JSON "row" or object)

    [HttpPost]
    public void AddProduct(Item items)
    {
        Inventory inv = new Inventory();

        inv.Add(items.code, items.qty);
        inv.Dispose();
    }

How can i pass this multiple JSON "row" or object to a Controller?

Browser is caching Partial Dom from Ajax

I wrote some ajax that does an infinite scroll which works fine normally. When I scroll to the bottom of the page it update a hidden variable for the page number and appends data to a div. What's weird is that when I hit the back button the DOM retains the old page number, but it does not retain the data appended to the div.

function scrollListener(url, contentDivSelector, pageNumberSelector, totalNumberOfPages) {
if (parseInt($(pageNumberSelector).val()) <= parseInt(totalNumberOfPages)) {

    //Make sure your not already at the bottom of the page
    ExecuteConditionalScroll(url, contentDivSelector, pageNumberSelector);

    //unbinds itself every time it fires
    $(window).one("scroll", function () {
        ExecuteConditionalScroll(url, contentDivSelector, pageNumberSelector);

        //rebinds itself after 200ms
        setTimeout(function () { scrollListener(url, contentDivSelector, pageNumberSelector, totalNumberOfPages); }, 200);
    });
}
};

function ExecuteConditionalScroll(url, contentDivSelector, pageNumberSelector) {

if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
    $.ajax({
        url: url,
        data: { pageNumber: $(pageNumberSelector).val() },
        traditional: true,
        dataType: 'json',
        type: 'GET',
        success: function (data) {
            var pageCount = parseInt($(pageNumberSelector).val());

            pageCount++;

            $(pageNumberSelector).val(pageCount);

            $(contentDivSelector).append(data.htmldata)
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log("error:" + thrownError.toString())
        }
    });
}
}

Does anyone have a good idea on how to fix this, without using Local-Storage Or Cookies? Also, Does anyone know why this would happen?

Logic for creating a home page for the forum

I am not looking for any code in particular but I am more interested in the logic. So here is the question.

I want to create a forum. The home page shows the top 20 questions that have been asked recently and have been stored in the database. I have used ajax and php to fetch the information from the database. The issue is, how do I display this information?

Should I make 20 identical divs and display the contents of each row in these divs.(this wouldn't make sense if I have to display 300-400 questions at once )

Or, should I use jquery to append child divs in a parent div and display information dynamically? If yes then how can it be done?

My question may be a bit unclear but I am a bit clueless here. Please help

Custom Login form with PHP and Ajax check username and display profile picture

i'm trying to do something "different" with my login page, but i think i'm doing somthing wrong or not understanding the process.

Right now, my users table are like:

user_id, username, password, profile_picture, first_name, last_name

What i want is, when you click in the input text (on focus) you start typing your username, once you click out, the ajax will check this user and return at the top the profile picture for that account.

Here it's an example for this but using gravatars: Example Here

Can someone help me to understand how this request can be done with ajax and php?

Thanks!

Page is showing the PHP code rather than running it

I wrote a simple php script to output the RAM utilization on my server to an HTML page. However when I open the web page I see the php code instead of the expected output.

HTML Document

<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Character set encoding -->
        <meta charset="UTF-8" />
        <!-- Jquery JS files -->
        <script src="js/jquery/jquery-1.11.3.min.js"></script>
        <script src="js/jquery/jquery-2.1.4.min.js"></script>
        <script src="js/jquery/jquery-ui-1.11.4.min.js"></script>
        <!-- AJAX -->
        <script src="ajax.js"></script>
    </head>
    <body>
        <div id="statistics">
            <h1>Memory</h1>
            <table>
                <tr><th>Total</th><th>Free</th><th>Used</th></tr>
                <tr id="mem"><script>memDoc()</script></tr>
            </table>
        </div>
    </body>
</html>

AJAX Document

function memDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
} else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById('mem').innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET", "free.php", true);
xmlhttp.send();
}

setInterval(function() {
    memDoc()
}, 5000);

PHP Document

<?php
$totalMem = exec("free -m | awk '{print $2}' | awk '(NR==2)'");
$freeMem = exec("free -m | awk '{print $4}' | awk '(NR==2)'");
$usedMem = exec("free -m | awk '{print $3}' | awk '(NR==2)'");
echo "<td>" . $totalMem . "</td><td>" . $freeMem . "</td><td>" . $usedMem . "</td>";
?>

I am running Ubuntu Server 15.04 with apache2 (2.4.10-9ubuntu1) and php5 (5.4.6+dfsg-4ubuntu6)This is what the output shows

How to batch multiple google api requests using javascript/jquery?

I want to use google apis in my chrome extension. But I can't get the google javascript client library to work, due to its incompatibility with chrome extensions. Hence I have to resort to using plain ajax requests.

How can I make batch api requests as depicted here using jquery/javascript?

Dynamically reading and writing to a MySQL database?

I'm trying to figure out a way to dynamically load and write things from a MySQL database.

I've tried reading about AJAX, and JSON but both of these things seem to be a way to dynamically deliminate, format and output certain pieces of data from a source of data which has already been acquired using PHP.

I could be wrong, I'm pretty new to this kind of thing.

The only way I can think of to accomplish this task is to use JavaScript (or possibly something else) to simulate "loading" a PHP script over and over on a certain event, and injecting new variable values every time.

Even if this is the way to accomplish what I'm looking for I'm at a loss as to how I would do this.

My first thought was to use angular to repeatably import external PHP files into the current document, but this wouldn't really work either. PHP runs before everything else, so if we've already loaded the page any new PHP we add will be stagnant.

Is what I'm attempting possible? In what way would I accomplish it, and are there any online resources I can use to learn the process?

How should I keep my interface in sync when ajax is in the mix?

I've already come up with a number of different methods to solve this issue in my code, but I'd like to hear how other people do it.

So far here's what I've done:

  • Use lodash.throttle on a method which does an ajax call so that multiple clicks in quick succession don't create multiple calls.
  • Use lodash.debounce on a method so that ajax is only called once a user hasn't done any activity for a bit. This is how I'm doing semi-realtime updates of text fields on change.
  • Dispatch an "is updating" message to stores when the action is first called and then dispatch a "done" message when the ajax call returns. Do stuff like disabling input on the initial message and then re-enable on the second.

The third method seems to be the best in terms of functionality since it allows you to make the user interface reflect exactly what's going on, but it's also SO INCREDIBLY VERBOSE. Like.. holy application constants batman! Plus it clutters absolutely everything up with tons of extra state, handler methods, etc...

So how do you keep your application in sync with ajax calls?

How to organize objects by their attributes in an AJAX function

Please excuse me if this seems elementary ive been stuck on this for weeks. If you are using an AJAX success function to display data dynamically on your html page, and the data you are getting back from the server is in stdclass objects like so

    array( 
       [7] => stdClass Object
        (
       [id] => 3
       [title] => Electrition
       [img] => 
       [description] => 
       [school] => 
       [location] => 1
       [url] => 
       [tablename] => 3
       [votes] => 0
       [name] => John Doe
       [NumJobsdone] => 4
           )

         [8] => stdClass Object
       (
        [id] => 2
        [title] => Electrition
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [url] => 
        [tablename] => 2
        [votes] => 0
        [name] => Tico Marinez
        [NumJobsdone] => 6
        )

        [9] => stdClass Object
        (
        [id] => 2
        [title] => Engineer
        [img] => 
        [description] => 
        [school] => 
        [location] => 1
        [tablename] => 2
        [votes] => 0
        [name] => Jerry Smity
        [NumJobsdone] => 6
       )

     [10] => stdClass Object
       (
       [id] => 2
       [title] => Engineer
       [img] => 
       [description] => 
       [school] => 
       [location] => 1
       [url] => 
       [tablename] => 2
       [votes] => 0
        [name] => Laura Bastian
       [NumJobsdone] => 6
         )
        ) 

how do you write a jquery function that can iterate through the data and create paragraph tags to label the output and an unordered list within a div of the corresponding objects?

ex. you are trying to create two groupings, electritions and engineers, and list the names of the individuals.

it seems simple but when i used a $.each method in my success function, i created a paragraph tag for every object that had the attribute i was organizing the objects by, and when i tried to use the sort method, i could only compare two or three objects at a time and not iterate through a long list of several objects.

say the desired output looked something like this

     <div id="accordion">
        <p> Electrition</p>
        <div>
        <ul>
          <li>jon</li>
          <li>jill</li>         
       </ul>
       </div>

        <p>Engineer</p>
       <div>
        <ul>
          <li>jerry</li>
          <li>laura</li>
       </ul>
      </div>
      </div>

Ajax call to .asmx page method failing with invalid System.InvalidOperationException: Missing parameter

I am trying to use a jquery autocomplete with an ajax call to a webservice method the call works fine on localhost but when published to the dev server it fails everytime and using google chrome to debug i get the following error:

System.InvalidOperationException: Missing parameter: sLookUP. at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()

I am using ASP.NET3.5 with IIS 7.5 where as the dev machine is IIS 6 with ASP.NET 2.0

My ajax call is as follows:

        $("#<%=txtSearch.ClientID %>").autocomplete({
        source: function(request, response) {
                $.ajax({
                url: "http://ift.tt/1GGf9sg",
                data: "{ 'sLookUP': '" + request.term + "' }",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function(data) {

My webmethod in Address.asmx :

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public String[] ShowAddress(string sLookUP)
    {
        List<string> lstAddresses = new List<string>();

        DataTable dtAddresses;
        Address Addr = new Address();
        dtAddresses = Addr.GetLookupAddresses(sLookUP);


        foreach (DataRow row in dtAddresses.Rows)
        {
            lstAddresses.Add(string.Format("{0}-{1}-{2}-{3}-{4}-{5}-{6}-{7}-{8}", row["OrderAddress_name"], row["OrderAddress_id"], row["OrderAddress_1"], row["OrderAddress_2"], row["OrderAddress_town"], row["OrderAddress_county"], row["OrderAddress_postcode"], row["OrderAddress_fulladdress"],row["OrderAddress_ClusterID"]));
        }
        return lstAddresses.ToArray();
    }

web.config settings (there's been suggestions on other questions these should help:

<webServices>

      <protocols>
        <add name="HttpSoap"/>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
        <add name="Documentation"/>
      </protocols>
    </webServices>




<system.webServer>
    <handlers>
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Any suggestion welcome I've tried so many things but as it works on my machine i'm thinking its an iis/web.config setting I've missed or written incorrectly because the dev machine has a different setup. Thanks

2 interlocking questions regarding html helpers

first off some background. i have a web site written in MVC5 and VS 2013. i created the project using the MVC template so i do have the bootstrap navbar at the top which is where all my menu links are. each link corresponds to a different view and each view uses (by default) _Layout.cshtml. i want to do 2 things to the links on the navbar - 1. have the current selected (active) item highlited when selected and 2. have them ajax compliant so that only the content of each view is refreshed not the entire page when a link is clicked. i already have goal 1 done and working but i'm not sure i'm doing it right. after finding a sample on the web i created an html helper extension method in the App_Code directory that looks like this..

public static class MyHelper
{
    public static MvcHtmlString HtmlLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
    {
        var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
        var currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

        var builder = new TagBuilder("li")
        {
            InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToHtmlString()
        };

        if (controllerName == currentController && actionName == currentAction)
            builder.AddCssClass("active");

        return new MvcHtmlString(builder.ToString());
    }
}

i implemented it in _Layout like this..

        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li>@Html.HtmlLink("Home", "Index", "Home")</li>
                <li>@Html.HtmlLink("About Me", "AboutMe", "Home")</li>
                <li>@Html.HtmlLink("Samples", "Samples", "Home")</li>
                <li>@Html.HtmlLink("Links", "Links", "Home")</li>
                <li>@Html.HtmlLink("Contact", "Contact", "Home")</li>
            </ul>
            @*@Html.Partial("_LoginPartial")*@
        </div>

the only question i have with this is how does VS know that HtmlLink is a helper extension? i didn't inherit from anything and both the class and method names were ones i made up. all i had to do was put @Html in front and it knew what it was. just want to understand whats going on. sure it works but i want to know why.

now for the Ajax stuff. i got that working also but i had to change the html helper calls in _Layout to ajax helper calls as so..

                <li>@Ajax.ActionLink("Home", "Index", "Home", new AjaxOptions() { UpdateTargetId = "site_content" })</li>
                <li>@Ajax.ActionLink("About Me", "AboutMe", "Home", new AjaxOptions() { UpdateTargetId = "site_content" })</li>
                <li>@Ajax.ActionLink("Samples", "Samples", "Home", new AjaxOptions() { UpdateTargetId = "site_content" })</li>
                <li>@Ajax.ActionLink("Links", "Links", "Home", new AjaxOptions() { UpdateTargetId = "site_content" })</li>
                <li>@Ajax.ActionLink("Contact", "Contact", "Home", new AjaxOptions() { UpdateTargetId = "site_content" })</li>

but now i'm in a quandary. since in both cases i had to change the same code in _Layout, i can right now only do one or the other not both. is there a way to possibly combine the 2 functionalities into one helper method or maybe there's a better way to do either or both? appreciate any help.

Resizing image client side and uploading via AJAX only works sometimes

I'm having an issue with code to allow a user to submit an image file via a form, resize it client side, upload it via AJAX and PHP to a Wordpress site, and then showing a thumbnail version of the image. The problem is the code only works sometimes and it seems to prefer some files over others. I have one jpeg image that only uploads maybe once out of every 10 attempts and other jpeg images that upload 5 out of 10 times. Also, when an image is uploading and reaches 100%, sometimes the progress bar will go back down to about 85% and then go up to 100% again. I'm thinking this is the cause of my issue, but I haven't been able to figure out how to fix it.

jQuery:

$('#myform-fileinput').change(function() { 
    if ($('#myform-fileinput').length) {

        if (window.File && window.FileReader && window.FileList && window.Blob) {

            var filesToUpload = document.getElementById('myform').files;
            var file = filesToUpload[0];

            var img = document.createElement("img");
            var reader = new FileReader();
            reader.onload = function(e)
            {
                img.src = e.target.result;

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                // Do other manipulations and send via AJAX here
            reader.readAsDataURL(file);
        }
    }
});

Deferred script tags...parallel request limits?

I'm aware there are limits to the number of parallel ajax requests one can make before browsers start a request queue and the performance benefit of parallel requests are lost. Do modern browsers impose similar limits to script tags with the 'defer' attribute? Does this count as an ajax request? I assume there are limits for the same reasons there are ajax limits, but where would I find each browser's specs for this sort of thing?

How to see what ajax request is actually being submitted

I'm making ajax requests to controllers in ASP MVC 5 from JQuery. The requests are failing. However, if I put in the request by hand, for example /Sale/fillVarietiesSelect?speciesId=2, I get the correct response. I must be doing something wrong with my ajax request, but I can't see it. It would help me debug if I could see the actual request being made, but it doesn't show up in the URL bar (it is a GET request). Is there a way I can intercept or view the actual request?

How to check if array is multidimensional? (jQuery)

I have two arrays of AJAX (JSON) response:

One dimension:

[["fili","Chif"],["Bart","deme"],["Bomb","Jyui"],["Joiu","FDPi"],["Doen","abcd"],["drog","MAIC"],["Jasi"
,"abcd"],["Jere","Jibi"]]

Three dimensions:

[[["5","#"],["2","N"],["L","7"],["C","8"],["F","W"],["K","T"],["Q","E"],["Z","\/"]],[["B","O"],["$","P"
],["1","Y"],["H","R"],["3","%"],["I","U"],["M","4"],["A","9"]],[["J","X"],["Bye","G"],["D","V"],["Bye"
,"6"]]]

I try to check if an array is multidimensional but does not work:

if (typeof arr[0][0] != "undefined" && arr[0][0].constructor == Array) {
     return true;
} 

jQuery AJAX response JSON get child node

i am trying to take the responseJSON from an AJAX call and just extract one element to the variable formDigestValue. I have tried about a dozen ways of trying to return the response, using JSON.parse(), $.parseJSON() and some others, but there are 2 main issues that i cant seem to figure out. I put in a check for if (data.lenght > 0){do something}, response.length, responseJSON, jqXHR, XHR, i cant seem to find the variable that holds the data that would end up sent to success function. I've tried just setting the ajax call to a variable (var y = $.ajax()...) and manipulating it that way.

I just keep reading different articles and trying different ways, but nothing seems to quite get it right and it seems to be fairly simple, but i feel like im just missing something simple on this.

    $(document).ready(function () {

        var siteURL = "xxx";
        var formDigestValue = "";

        jQuery.ajax({
                url: siteURL + "/_api/contextinfo",
                type: "POST",
                headers: { 
                    "accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                },
                success: function(){
                    contextHeaders = $.parseJSON(responseJSON);
                    formDigestValue = contextHeaders.FormDigestValue;
                }
            });
...

any advice would be greatly appreciated. For reference, the JSON returned looks like the below. i am trying to figure out if i also need anything extra to get at child nodes, as it looks like it comes back buried a bit (i broke it out with indents just to show the depth):

{
    "d":
    {
        "GetContextWebInformation":
        {
            "__metadata":
            {
                "type":"SP.ContextWebInformation"
            },
            "FormDigestTimeoutSeconds":1800,
            "FormDigestValue":"0xADC9732A0652EF933F4dfg1EF9C1B75131456123492CFFB91233261B46F58FD40FF980C475529B663CC654629826ECBACA761558591785D7BA7F3B8C62E2CB72,26 Jun 2015 21:20:10 -0000",
            "LibraryVersion":"15.0.4631.1000",
            "SiteFullUrl":"http://example.com/",
            "SupportedSchemaVersions":
            {
                "__metadata":
                {
                    "type":"Collection(Edm.String)"
                },
                "results":["14.0.0.0","15.0.0.0"]
            },
            "WebFullUrl":"http://www.example.cm"
        }
    }
}

edit 6/27

Alright, I think between the comment on accessing the child nodes and the rest on passing the argument to success function, ive almost go it. My main thing is, I cannot seem to pass it as an argument. I tried to say it initially, but dont think I write the explanation properly. I tried:

Success: function(responseJSON)...

As well as

Success: function(data)...

But the data never seems to actually enter the function, its null values. I know the json returned, but having issues passing it into success function

Here is a look at firebug when this runs: Function Error

Ajax pass values from view to controller

so I'm trying to pass some values from my view to the controller, the controller gets a list and returns it.

when I try to get the values from my textboxes etc. they are all undefined... not sure what exactly I'm doing wrong here. pretty new to javascript..

here's the js code

<script type="text/javascript">
$(document).ready(function () {
    $("#getFreeApartements").on('click', function () {

        var amounta = $('#amounta').val();
        var amountc = $('#amountc').val();
        var amountan = $('#animals').val();
        var arr = $('#arrival').val();
        var dep = $('#departure').val();
        var atype = $('#atype').val();


        $.ajax({
            type: 'GET',
            data: { 'amountp': amounta, 'amountc': amountc, 'amountanimals': amountan, 'arrival': arr, 'departure': dep, 'apartmentType': atype },
            url: '@Url.Action("GetFreeApartements", "Bookings")',
            success: function (result) {
                $('freeAp').html(result);
            }
        });
        alert(amounta); // --> return undefined

    });
});

textboxinput field

    <div class="form-group">
        @Html.LabelFor(model => model.Adult, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10" id="amountp" name="amountp">
            @Html.EditorFor(model => model.Adult, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Adult, "", new { @class = "text-danger" })
        </div>
    </div>

controller:

        public ActionResult GetFreeApartements(int ap, int ac, int aa, DateTime arr, DateTime dep, ApartmentType type)
    {
 //do some stuff with received values here...
        var freeApartements = db.Apartments.ToList();
        return Json(freeApartements, JsonRequestBehavior.AllowGet);

    }

I also tried serializeArray without any success... I'm not getting any errors in the explorer console.. the function gets called, but values are null.. --> undefined should be the error.

any ideas?

Joomla Ajax Request Error

I got following error

Method get_slotsAjax does not exist

my call in healper file

 xmlhttp.open("GET","?option=com_ajax&module=quickcontact&method=get_slots&format=json",true);

my function call

public function get_slots()
{
 ....
}

Went by this documentation.

What am I Missing?

ajax checkbox filtering in codeigniter

I try to filter data in my view using select box. I'm using codeigniter and I want to filter it using ajax. I already test the code and look at the console, and ajax post return result. The problem is, i don't know how to display the result in my view. I mean, how i suppose to write in 'success: function(){}'

this is my ajax

  <script>
$(document).ready(function() {
$("#selectBerdasar").change(function() {
    var key = $(this).val();
    console.log(key);
    var postdata = {key: key};
    var url = '<?php echo site_url('produk/filter/GetFilterJson');?>';
    $.post(url, postdata, function(result) {
        console.log(result);
        if (result) {
            var obj = JSON.parse(result);
            $('col-item').empty();
            $.each(obj, function(key, line) {

             });
        } else {

        }
    });
});

});

this is my view

<div class="row">

  <div class="col-md-4 pull-right">
    <select class="form-control" id="selectBerdasar">
     <!--  <option>Produk Terbaru</option>
      <option>Produk Terpopuler</option> -->
      <option value="termahal">Harga Termahal</option>
      <option value="termurah">Harga Termurah</option>
      <option value="alfabet">Alfabet A-Z</option>
    </select>
  </div>
</div>


  <div class="row">
    <?php foreach ($produk as $data) {?>
  <div class="col-xs-6 col-sm-4 col-md-4">
    <div class="col-item">
<a href="<?php echo base_url('produk/item/detail/' . $data['id_produk']);?>">
<div class="photo">
    <img src="<?php echo base_url();?>asset/user/img/produk/<?php echo $data['gambar'];?>" class="img-responsive" alt="" />
</div>
<div class="info">
    <div class="row">
        <div class="price col-md-12">
        <h5><?php echo $data['nama_produk'];?></h5>
        <h5 class="price-text-color">Rp.<?=number_format($data['harga_produk'], 0, ',', '.')?></h5>
    </div>

</div>
    <div class="clearfix">
    </div>
</div>
</a>
</div>
  </div>
   <?php }

?>

 </div>

I just don't know how to display the result in my view.

Google Maps v3 API: use first user location to center the map

I am building a Google Maps based web app on which I plot a moving dot of the user location. I am fetching continuously the user location from a server and would like to use the current user location when loading the map to center the window around it, meaning, when the user loads the site, the map will be centered around the first lat/long fetched from the server but enable the user to pan the map afterwards without re-centering it around where the user is. I was able to keep the map centered constantly around the user location but can't figure out how to use the first fetched location to center the map during initialization. My code is below, any help would be greatly appreciated. Thanks!

 <script>

          var locations = [
                ['location a', 37.771678, -122.469357],
                ['location b', 37.768557, -122.438458],
                ['location c', 37.755121, -122.438973],
                 ['location d', 37.786127, -122.433223]
              ];
          var map;
          var i;
          var marker; 
          var google_lat = 37.722066;
          var google_long = -122.478541;
          var myLatlng = new google.maps.LatLng(google_lat, google_long);
          var image_dot = new google.maps.MarkerImage(
              'images/red_dot.png',
              null, // size
              null, // origin
              new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
              new google.maps.Size( 8, 8 ) // scaled size (required for Retina display icon)
          );

          function initialize() {

            var mapOptions = {
              zoom: 12,
              center: myLatlng,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

            setMarkers(map, locations);
          } //initialize();


          function setMarkers(map, locations) {

              for (var i = 0; i < locations.length; i++) {
              var beach = locations[i];
              var myLatLng1 = new google.maps.LatLng(beach[1], beach[2]);
              marker = new google.maps.Marker({
                position: myLatLng1,
                icon: image_dot,
                map: map
              });
            }
          }

          google.maps.event.addDomListener(window, 'load', initialize);

    </script>

    <script type="text/javascript">

            var Tdata;
             var image = new google.maps.MarkerImage(
              'images/bluedot_retina.png',
              null, // size
              null, // origin
              new google.maps.Point( 8, 8 ), // anchor (move to center of marker)
              new google.maps.Size( 17, 17 ) // scaled size (required for Retina display icon)
           );
            var userMarker = new google.maps.Marker({icon: image});

            $.ajax({
                    method : "GET",
                    url: "get_location.php",
                    success : function(data){
                        Tdata=JSON.parse(data);
                        myFunction();
                    }
            });

            function myFunction(){
                    var interval = setInterval(function() { 
                        $.get("get_location.php", function(Tdata) {
                            var JsonObject= JSON.parse(Tdata);
                            google_lat = JsonObject.lat;
                            google_long = JsonObject.long;
                            myLatlng = new google.maps.LatLng(google_lat, google_long);
                            userMarker.setPosition(myLatlng);
                            userMarker.setMap(map);
                            //map.setCenter(myLatlng); --> this is not what I want since it will always keep the map centerd around the user 
                        });
                    }, 1000);
            }

     </script>

Close image on modelpopup doesn't work after postback

I have ajax modelpopup extender in my webform with CancelControlID set to an image imgClose. When I click on imgClose after popup has been displayed it closes the popup. But if I click on any controls or select some controls that require postback, clicking the image wouldn't do nothing at all. Previously I had a button as CancelControlID for same modelpopup. It also had the same problem. I got around it with OnClick="btnClose_Click"codebehind method and hiding modelpopup.

For the imgClose I tried using client-side method but it doesn't work. Any ideas?

Here's my modelpopup extender image control and javascript

<img id="imgClose" alt="Close" src="image/close-button-red.png" runat="server" onclick="closeModelPopup()" />


<ajx:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnTest"
                BackgroundCssClass="modalBackground" PopupControlID="divPreview" DropShadow="true"
                CancelControlID="imgClose">


<script type="text/javascript">
    function closeModelPopUp() {
        $find('ModalPopupExtender1').hide();           
    }
</script>

Simple AJAX Note Taking App to record same notes written through out every / any page

I want to use the Simple AJAX Note Taking App for my website but it looks like they have coded it for the user to create notes PER WEBPAGE (I'll explain how I worked this out later) which isn't exactly what I want.

I want users to be able to create their own notes using this script but for their entire session surfing my website. So in other words, it doesn't matter what webpage they are on, the notes they they've written down is recorded / saved 'globally' and they can refer to those SAME notes that they've written down regardless what page they're on.

***Just so you know, I intend to use this script in a global php include for all my pages. The PHP include looks like this: **

<?php include( $_SERVER['DOCUMENT_ROOT'] . '/test/inc/noteapp.php' ); ?>

(Please understand that I suck a php and javascript)

So to show you how their demo works (I've uploaded the demo onto my domain name): Click here PAGE 1 ... Now quickly write down some notes on that page and then go to my other page that also uses this script PAGE 2

You'll notice that the notes that you've written down on PAGE 1 aren't showing up on PAGE 2.

I want the notes that you've written down on PAGE 1 to show up on PAGE 2, PAGE 3, page 4 (doesn't matter what directories they're on) etc etc ...

Let me show you their code and explain to you how it works:

Here is their PHP code for the script:

<?php

$note_name = 'note.txt';
$uniqueNotePerIP = true;

if($uniqueNotePerIP){

// Use the user's IP as the name of the note.
// This is useful when you have many people
// using the app simultaneously.

if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $note_name = 'notes/'.md5($_SERVER['HTTP_X_FORWARDED_FOR']).'.txt';
}
else{
    $note_name = 'notes/'.md5($_SERVER['REMOTE_ADDR']).'.txt';
}
}


if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
// This is an AJAX request

if(isset($_POST['note'])){
    // Write the file to disk
    file_put_contents($note_name, $_POST['note']);
    echo '{"saved":1}';
}

exit;
}

$note_content = '

            Write your note here.
';

if( file_exists($note_name) ){
$note_content = htmlspecialchars( file_get_contents($note_name) );
}

?>

In the PHP code above, notice the directory notes/ ... this is the directory where the users written notes will be saved (in a txt file). Now as mentioned above, I will be putting this php code into a php include which will be put on every page of my website. My website will have many directories / sub directories which means that this notes/ directory (which I want in the root of my domain) needs to be pathed correctly so that it always finds the notes/ directory in the root.

How would I path it?

That's my first problem ... now moving onto the second problem (not a crucial issue) - take a look at their javascript:

$(function(){

var note = $('#note');

var saveTimer,
    lineHeight = parseInt(note.css('line-height')),
    minHeight = parseInt(note.css('min-height')),
    lastHeight = minHeight,
    newHeight = 0,
    newLines = 0;

var countLinesRegex = new RegExp('\n','g');

// The input event is triggered on key press-es,
// cut/paste and even on undo/redo.

note.on('input',function(e){

    // Clearing the timeout prevents
    // saving on every key press
    clearTimeout(saveTimer);
    saveTimer = setTimeout(ajaxSaveNote, 2000);

    // Count the number of new lines
    newLines = note.val().match(countLinesRegex);

    if(!newLines){
        newLines = [];
    }

    // Increase the height of the note (if needed)
    newHeight = Math.max((newLines.length + 1)*lineHeight, minHeight);

    // This will increase/decrease the height only once per change
    if(newHeight != lastHeight){
        note.height(newHeight);
        lastHeight = newHeight;
    }
}).trigger('input');    // This line will resize the note on page load

function ajaxSaveNote(){

    // Trigger an AJAX POST request to save the note
    $.post('index.php', { 'note' : note.val() });
}

});

Notice at the bottom of this code index.php ... I'm guessing that's the webpage that the ajax must work on? Generally I like to put most (if not all) of my javacript into a combined js file which is included on every page. So if I do that with the javascript above, then I've got a problem with index.php being index.php because a lot of my web page won't all be called index.php (eg: about.php etc) ... so is their any way to change index.php to be something else to automatically refer to the page the user is on regardless what it's called?

If this cannot possibly be done, then I suppose I'd have to put this javascript on each page (and not in my combined javascript file) and amend index.php to whatever page it's on.

I'd appreciate your help and I hope I've explained well enough.

How to get information in jquery function from the php file

Hello guys my question is how to get an db information (in my case points just a number) from the php file to the jquery ajax script so here is my jquery:

function rate_down(id) { 
    var id = id;
//submit data to php script

    var data = {
      "id": id,
    };

    $.ajax({
      type: "POST",
      url: "rating.php",
      data: data,
      success: function(response) {

      var currentValue = /* here i want to put the db number */
      var newValue = +currentValue - 1;
      $("#points_"+id).text(newValue);




      },
      error: function(jqXHR, textStatus, errorThrown){
        alert(errorThrown);
      } 
    });
};

And i want my raiting.php im not sure if i shoud post it becouse its usless but here is my mysql query in raiting.php:

$pic_id = (int) $_REQUEST['id'];
mysql_query = mysql_query"SELECT points FROM `photos` WHERE `id` = '$pic_id'";

Executing Angular.js-controller method on element shown

How to execute controllers method on element shown. I have a tabs, and i want load data when user open a tab, if i using ng-init, information loads after page loading.

var systemSettingsController = manageApp.controller("SystemSettingsController", [ "$scope", function($scope) { $scope.tab = 1; $scope.initTab = function(tab) { $scope.tab = tab; }; } ]); var emailManagementController = manageApp.controller("EmailManagementController", function($scope, $http) { $scope.smtpServer = ""; $scope.smtpLogin = ""; $scope.smtpPassword = ""; this.init = function() { $http.get("/api/EmailSettings") .then(function(res) { var obj = angular.fromJson(res.data); $scope.smtpServer = obj["Email.SmtpServer"]; $scope.smtpLogin = obj["Email.SenderAddress"]; $scope.smtpPassword = obj["Email.SenderPassword"]; }); }; ...

I want execute method init (EmailManagementController) without using ng-init, and at the moment when this element is displayed on the screen, that is, its display will change to a property different from none.

Not sending mail AJAX/PHP with modal no page refresh

I'm new. I have been searching and researching to make my AJAX send my form after submit and making a modal appear, I have figured out the modal to appear and make the page not refresh, and at one point I made the form send to my mail, but now I don't know what I did and I am so confuse, so if somebody can help or share a link and read it I would appreciate it :D. I'm using bootstrap. Thanks very much for reading. :D

Here is my HTML in the body (I have the javascripts all linked)

<div class="row">
        <div class="col-lg-6 col-md-6 col-sm-12">
            <form id="miformulariopers" method="post" action="php/sendmail.php" role="form">
            <div class="form-group">
                <label for="nombre">Nombre</label>
                <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Tu nombre">
            </div>
            <div class="form-group">
                <label for="apellido">Apellido</label>
                <input type="text" class="form-control" id="apellido" name="apellido" placeholder="Tu apellido">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail1">Email</label>
                <input type="email" class="form-control" id="exampleInputEmail1" name="mail"placeholder="Tu correo">
            </div>
            <div class="form-group">
                <label for="InputMessage">Mensaje</label>
                <textarea class="form-control" rows="3" placeholder="Tu mensaje" id="InputMessage" name="mensaje"></textarea>
            </div>
            <div class="form-group">
                <button id="buttonright" type="submit" class="btn btn-default" data-toggle="modal">Submit</button>
            </div>
            </form>
        </div>

This is my PHP:

<?php
$destinatario = 'mymail@gmail.com';
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$mail = $_POST['mail'];
$asunto = 'Correo de la web';
$mensaje = $_POST['mensaje'];
$cabeceras = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
?>
<?php
$success = mail($destinatario, $asunto, $nombre, $apellido, $mail, $mensaje, $cabeceras);
if ($success) {
    echo '<h1>Envío realizado</h1>';
    echo '<p>Personaliza tu mensaje aquí. Respetando las etiquetas "p"</p>';
} else {
    echo '<p><strong>Error al enviar el mensaje. Inténtelo de nuevo.</strong></p>';
}
?>

And my JS and AJAX:

$("#miformulariopers").submit(function () {
  event.preventDefault();
  $("#message").modal('show');

});
$("#buttonright").click(function () {
$.ajax({
        type : "POST",
        url : "php/sendmail.php",
        data: '#miformulariopers'.serialize(),
        dataType: "json",

        });
        });

AJAX Parsing HTML returns [object Object]

I'm trying to load a page in with AJAX using a method I found here.

Everything goes well until I get to the parse_html function. The correct values from the elements on the next webpage are assigned to the body variable (that is, a string of the HTML code from the body tag). But when it turns that into the jQuery object, $body ends up being equal to Object (which I think is maybe correct? I THINK this is a DOM object that has all the HTML from the body tags in it).

Finally, the jQuery object "$content" is made equal to the contents of the first "#content" element. However, response.$content ends up being equal to "[object Object]".

How do I make it so that when I use $content.html(response.$content) the #content div is filled with the HTML from the new page instead of [object Object].

function find_all($html, selector) {
  return $html.filter(selector).add($html.find(selector));
}

function parse_html(html) {
  return $($.parseHTML(html, document, true));
}

// Convert page contents to jQuery objects
function parse_response(html) {

  // 'body' is equal to the strings of text in between the body tags
  var body = /<body[^>]*>([\s\S]+)<\/body>/.exec(html),

  $body = body ? parse_html(body[1]) : $(),

  // '$content' is equal to the contents of the first #content element
  $content = $.trim(find_all($body, '#content').first().contents());

  // Output the variable "$content"
  return {
    '$content': $content
  }
}

For context, here is where I call these functions inline:

url = History.getState().url,
rel = url.replace(root, "/");
$.get(rel).done(function (data) {

    var response = parse_response(data);

    var $content = $("#content");

    $content
        .slideUp(500) // Get it off screen to start
        .promise()
        .done(function () {
            $content
                .html(response.$content)
                .slideDown(500);
        });
}).fail(function () {
            document.location.href = url;
            return false;
});

unable to reload the page after ajax success

I am trying to login using facebook JS, I am using the following code :

function FBLogin() {
  FB.login(function(response) {
    if (response.authResponse) {
      FB.api('/me', function(response) {
        //alert(response);
        jQuery.ajax({
          url: 'someurl.php',
          type: 'POST',
          data: 'id=' + response.id + '&firstname=' + response.first_name + '&last_name=' + response.last_name + "&email=" + response.email,
          dataType: 'json',
          success: function(data, textStatus, xhr) {
            $(document).ajaxStop(function() {
              setTimeout("window.location = 'otherpage.html'", 100);
            });
          },
          error: function(xhr, textStatus, errorThrown) {
            alert(textStatus.reponseText);
          }
        });
        //window.alert(response.last_name + ', ' + response.first_name + ", " + response.email);
      });
    }
  }, {
    scope: 'email'
  });
}

In this I have a ajax call, I want to reload the page after the ajax success. In someurl.php, I am just echo some text, I want to reload the page after the ajax success.

I have tried

success: function(data, textStatus, xhr) {
  $(document).ajaxStop(function(){
    setTimeout("window.location = 'otherpage.html'",100);
    });
},

and

success: function(data, textStatus, xhr) {
  window.location.reload();
},

but none of code is working. Please help me. How can I reload the page when the ajax is successful?

create a jquery function that adds points into total-points column in MySQL table based on comparion

jquery comparison of rows from a user prediction table and a result a results table. If the values are identical i want to award 3 point to user and add to total points.

$('#pred_table tr').each(function(){

            var currentRowHTML=$(this['Home_Score']&&this['Away_Score']).html();

            $('#fixure tr').each(function(){
                if($(this['Home_Score']&&this['Away_Score']).html()===currentRowHTML){


    //not sure where to begin with the doCalculation function

                    $(this).doCalculation("award 3 points into total points in another
                    table in database");

            }
        });
    });

ajax get request in node js express

I'm working a litlle bit on my Node js Skills.

I would like to add some data to mongodb using a button click.

Client side code looks like this:

        $(function() {
        $('#add').click(function(){
            $.ajax({
                type: "GET",
                url: "/item/<%= products._id %>/add"
            }).done (function (data) {
                alert(data);
                console.log(data);
            });
        });
    });

  <button type="submit" id="add" class="btn btn-primary">Interessted</button>

Server side code like this:

    app.get('/item/:id/add', function(req, res) {

    Listing.findByIdAndUpdate(
        { _id : req.params.id},
        { $push : {"product.interessteduser": req.user._id }},
        {  safe: true, upsert: true},
        function(err, model) {
            if(err){
                console.log(err);
            }

        });
});

The code works perfectly for me, but if I wait a little bit I get another request in my console.

Looks like this:

GET /item/557eec02aa1046b805190207/add 200 120001ms
GET /item/557eeb82aa1046b805190206/add 200 120000ms

So every time request /item/:id/add and wait for 120000ms I get another request. How to stop this?

I would like to hit the button once do the /item/557eeb82aa1046b805190206/add Get request and that's all.

JSONP issue with Cordova and WebAPI Error: Unexpected token :

I'm having an issue with a some cross site communication in a cordova app I'm toying with, the error is on the ajax call below.

Error in browser

Uncaught SyntaxError: Unexpected token :

The interesting part is that in the response the JSON is there, it just don't arrive to the success.

The WebAPI method

public JsonResult Search(string query)
{
    query = query.ToLower();
    RPAS_Operator op = new RPAS_Operator();
    SearchResultModel sm = SearchSupport.ParseData(op.RPAS_Operators.Where(a =>
    a.Name.ToLower().Contains(query)));
    return Json(sm, JsonRequestBehavior.AllowGet);
}

The jQuery

function Search(query) {
    var url = baseURI + "Search/Search/?query=" + query;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'jsonp',
        cache: false,
        jsonp: 'callback',
        success: function (data) {
            console.log(data);
            document.getElementById("testOutput").innerText = data;
        }
    });
}

How to write php code inside jquery to update database table

I am working in Banking project .I want to write php code to update table upon successful Transaction using ajax . suppose i am sending request from fundtransfer.php to external API and the External API is also responding correctly .Now upon successful API respond i want to update my database table field name status from pending to completed .

    <script>
        $(document).ready(function()
        {
            $.ajax(
            {
            url:"http://ift.tt/1HoFteZ",
            type:"post",
            data:"variable="+value,
            success:function(result)
            {
                if(result==100)
                {
                    $("#message").html(successful transaction);
                    //Now i want to update my database tabale status saying Successful Transation 
                    //where to write these all php mysql code to update my database table
                   // without loading and redirecting page
                }   

                else
                {
                    $("#message").html(some thing gone wrong);
                }

            }
            });
        });
    </script>

redirect not work properly in codeigniter

Halo, i'm using ajax to post form into controller codeigniter. I want to redirect after ajax post, but controller doesn't redirect.

This is my ajax

    $.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(){

         },
        error: function(){
        alert("failure");
        }
    });
  });
});

this is my controller

public function checkout_data(){
    $this->account_model->checkout_simpan();
    redirect('produk/payment/last_steps');
}

this is my form

<form class="form-horizontal col-md-offset-3" id="form-checkout" action="<?php echo base_url('produk/payment/checkout_data');?>">

What wrong with my code ?

Uncaught Error: Error: An invalid exception was thrown

I am trying to use ExternalInterface to call a Flash Function from javascript.

My JS:

function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
    return window[movieName]
}
else {
    return document[movieName]
}
}

function DoThis() {
$.ajax({
    url: 'POSTINGURLHERE',
    type: 'POST',
    dataType: 'json',
    data: { 'at': 1 },
    success: function(result) {
        thisMovie("ID").Lol(result['xD']);
    }
});
}

This code works perfectly on Localhost, just not on my public webhost? I am getting on Google Dev Tools: http://ift.tt/1IDt7fE

I have the flash callbacks set in the swf, perfect for Localhost as mentioned. So why is it not working on my webhost?

AJAX PHP response interpretation

I noticed that there are several ways for an AJAX call made by jQuery to interpret data. I had a look at json, but maybe it is an over complication for what I am trying to do.

My php script ALWAYS returns a 1 integer string SOMETIMES followed by a 1 integer int OR a 2 integer int.

So it can either return

x or xy or xyz

where x, y, and z are real single numbers.

How could I decode this response and assign jQuery var to the reply. I was thinking something like.

var code = firstNumberOf response
var value = secondNumberOf and thirdNumberOff response

But var value can also just be the second number if there is only a second number and not a third one.

Thanks in advance, I have been dwelling on this for ages.

Make indexable an ajax based webpage

I want to make indexable my ajax based website.

I have read this doc: http://ift.tt/PGKKpZ But I don't understand it at all.

I think I need to do it:

  1. Write this tag in a webpage, for example: www.myweb.com/mypage

    <meta name="fragment" content="!">
    
    
  2. I'm using UrlRewriteFilter for my Tomcat Server (http://ift.tt/L066wZ), so I think I could redirect the urls with the substring: "?_escaped_fragment_=" to a html snapshot (which I can build manually, writing my custom meta-description, title and content???)

    <rule>
       <from>^/mypage\?_escaped_fragment_=</from>
       <to type="forward">/snapshots/mypage.html</to>
    </rule>
    
    
  3. Write the URLs (without the escaped fragment) into the sitemap.xml

    ...
    <url>
    <loc>http://ift.tt/1ed3v19;
    ...
    </url>
    ...
    
    

Is it right? I need to do something more?

php ajax contact form http_response_code() on line 17

I've tried to get this contact form to work, and I've followed the example http://ift.tt/PtDpvh . I only get the Fatal error: Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom/spirit/mailer.php on line 17 above my contact form. I do not know php at all, but having this contact form is kick-ass! Here are the relevant files:

Here is the html:

<!DOCTYPE html>
<div id="form-messages"></div>
                <form id="ajax-contact" method="post" action="mailer.php">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="exampleInputEmail1">Name</label>
                                <input type="text" id="name" class="form-control" name="name" required placeholder="Name...">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="exampleInputPassword1">E-mail</label>
                                <input type="name" class="form-control" id="email" placeholder="E-mail" required>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Message</label>
                        <textarea class="form-control" rows="3" id="message" name="message" placeholder="Your Message Here" required></textarea>
                    </div>

                    <button type="submit" class="btn tf-btn btn-default">Submit</button>
                </form>

Here is the js file:

$(function() {

// Get the form.
var form = $('#ajax-contact');

// Get the messages div.
var formMessages = $('#form-messages');

// Set up an event listener for the contact form.
$(form).submit(function(e) {
    // Stop the browser from submitting the form.
    event.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: formData
    })
    .done(function(response) {
        // Make sure that the formMessages div has the 'success' class.
        $(formMessages).removeClass('error');
        $(formMessages).addClass('success');

        // Set the message text.
        $(formMessages).text(response);

        // Clear the form.
        $('#name').val('');
        $('#email').val('');
        $('#message').val('');
    })
    .fail(function(data) {
        // Make sure that the formMessages div has the 'error' class.
        $(formMessages).removeClass('success');
        $(formMessages).addClass('error');

        // Set the message text.
        if (data.responseText !== '') {
            $(formMessages).text(data.responseText);
        } else {
            $(formMessages).text('Oops! An error occured and your message could not be sent.');
        }
    });

});

});

and here is the mailer.php

<?php
// My modifications to mailer script from:
// http://ift.tt/PtDpvh
// Added input sanitizing to prevent injection

// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the form fields and remove whitespace.
    $name = strip_tags(trim($_POST["name"]));
            $name = str_replace(array("\r","\n"),array(" "," "),$name);
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = trim($_POST["message"]);

    // Check that data was sent to the mailer.
    if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Set a 400 (bad request) response code and exit.
        http_response_code(200);
        echo "Oops! There was a problem with your submission. Please complete the form and try again.";
        exit;
    }

    // Set the recipient email address.
    // FIXME: Update this to your desired email address.
    $recipient = "myemail@gmail.com";

    // Set the email subject.
    $subject = "New contact from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    // Send the email.
    if (mail($recipient, $subject, $email_content, $email_headers)) {
        // Set a 200 (okay) response code.
//            http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        // Set a 500 (internal server error) response code.
        http_response_code(500);
        echo "Oops! Something went wrong and we couldn't send your     message.";
    }

} else {
    // Not a POST request, set a 403 (forbidden) response code.
    http_response_code(403);
    echo "There was a problem with your submission, please try again.";
}

?>

I know this is not the best way of asking for help. But any help is much appreciated. If I could, I would, buy the person a coffee if it was physically possible :).

Many thanks!

PHP and AJAX login Script secure enough?

I want to create a dynamic login on my website using ajax (with jquery). Now everything is done, and everything works well. My problem is, that i dont know, if everything works secure (enough) to use it, like it's now.

My ajax script:

//LOGIN
$(function(){
  var mail;
  var password;
  $("body").on("click", ".sign-in", function(event){
    mail = $('#login-mail').val();
    password = $('#login-password').val();
    //ajax
    $.ajax({
      type: "POST",
      async: true,
      url: '/index.php',
      data:  { 'mail': mail,'password': password},
      success: function (msg)
        {

          if($(msg).filter('.logged-in').html() == 'success'){
            window.location.replace('/timeline.php')
          }else{
            $('input').css('border','0.1rem solid #EB5757');
            $('.login-failed').html('Falsche E-Mail oder / und Passwort !');
          }
        },
      error: function (err)
      { alert(err.responseText)}
    });
  });
});

The logic behind this: Ajax sends the user and pass to a PhP page:

if(isset($_POST["mail"]) && isset($_POST["password"])){
  //$mU->hashPassword($_POST['password']);
  if($mU->loginUser($_POST["mail"],$_POST["password"]) == true)
  echo '<div class="logged-in">success</div>';
}

$mU->loginUser($_POST["mail"],$_POST["password"]) == true when true, everything is fine. Then the Script "echos" success. In my ajax success function, jquery checks the content of the div.

I hope you know what i mean, because its very hard to explain my "problem". Is my Script secure ? What can I do better (security) ?

jquery Select2 4.0 trigger('change') does not work

var $element = $("#genre").select2({
            placeholder: "select genre",
            maximumSelectionLength: 3,
            ajax: {
                url: function (params) {
                    return "/score/search_genre/"+params.term
            },
            dataType: 'json',
            delay: 250,
            processResults: function (data) {
                var select2Data = $.map(data.genre, function (obj) {
                    obj.id = obj.code;
                    return obj;
                });
                return {
                results: data.genre
              };
            },
            cache: false
            },
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 1,
            templateResult: genreSelectFormat, // omitted for brevity, see the source of this page
            templateSelection: function (data) { return data.genre_kr; }
        });

$element.trigger('change');


<select name="genre[]" id="genre" style="width:70%" multiple>
  <?php foreach($genres as $genre) { ?>
     <option selected="selected" value="<?=$genre?>"><?=get_genre_nm($genre)?></option>
  <?php } ?>
</select>

I'm using select two multiple selection with ajax

there's no problem when I does not use with ajax

but with ajax initial option's text does not show up like below

now : ([ⓧ] [ⓧ] [ⓧ] ) <-- options without text

i want : ( [default1ⓧ] [default2ⓧ] [default3ⓧ] ) <-- proper result

php foreach loop prints result well

I don't know what I did wrong

How to attach multiple scroll events on different divs in JavaScript / jQuery?

I need to load dynamically data on scroll event but my data is grouped in different tables. If the number of rows returned from AJAX call is grater than some limit, overflow and height is added to that table.

At document loading I only fetch and populate table title which represent different groups. On first click on a group title a chunk of data (table rows <tr>) is loaded and displayed on the page.

So I need to keep track if the cursor is over some table and than to trigger the scroll event. Here is some code and structure :

// allGroups holds the ids of all the groups
allGroups = [435,56,34,23,452];

$(document).ready(function () {

$.each(allGroups, function(ind, value){

    var item = $('#POI_data_' + value);

    item.on('mouseenter',function(){

        item.on('scroll',function(){
            // fetch new data
        });

    });
    item.on('mouseleave', function(){

        item.off('scroll');
    });
});
});

table structure:

<div id="POI_data_<?php echo $poiRow['id'] ?>">
    <table >
        <!-- FETCH NEW DATA -->
    </table>
</div>

My problem is when mouseenter event triggers on another table, the scroll event is not properly triggered.

Sending a integer value to php with javascript and returning values

I have this div area in my index and I want to use it as a button (for graphical issues) and when this button is cliked I want it to send this value to php file and I want to return some values according to this value. Here is what I've done this far but it didn't work at all.

this is my output.php (index)

<script src="http://ift.tt/1APuVEV"></script>
<script type="text/javascript"> 
        int sayac = 1;
        $(document).delegate("#klikme", "click", function() {
                $.post('sayac.php',{"komut": sayac }, function(data){
                        $('#output').html(data);
                });
                sayac = sayac + 1;
        });

</script>
<div id = "klikme">
        KLİK ME!
</div>

<div id = "output">
<?php include 'sayac.php'?>

</div>

sayac.php

<?php 
        if(isset($_POST["komut"]))
        {
                switch($_POST["komut"])
                {
                        case "1":
                                echo "This is one";
                                break;
                        case "2":
                                echo "This is two";
                        default:
                                echo "Something is wrong";
                                break;
                }
        }
        return false;
?>

AJAX can't received data to controller MVC

I send data by ajax to mvc controller.
i got to correct method but without data.
i tried to get List or strong all the time null

js code:

function sendDataCreateMilestone(parameters) {
    $.ajax({
        url: "/QRCNew/create",
        type: "post",
        dataType: "json",
        data: JSON.stringify(parameters)
    });
}

server:

here i revived all the time null 
 public ActionResult Create (List<string> ids, string collection)
        {
          do....
          }

jQuery: dynamic insert in won't work properly

I'm writing a page in jQuery Mobile and I have an Unordered List which contains elements like these:

<ul id="ul1" data-role="listview" data-theme="d">
            <li>
                <a>
                <h1>Who wants to live forever</h1>
                    <p>Queen</p>
                </a>
            </li>
            <li>
                <a>
                <h1>Personal Jesus</h1>
                    <p>Depeche Mode</p>
                </a>
            </li>
        </ul>

But I want to insert elements DYNAMICALLY, searching in a MySQL database. It works, but the elements that are inserted in the UL DON'T look like the default LI in jQuery Mobile: they appear as simple text thrown in the UL. The jQuery Mobile's "Graphic" is not represented. Here's the codes:

Ajax function for searching through php:

<script>
function ricerca() {
    str = document.getElementById("search").value;
    if (str == "") {
        document.getElementById("ul1").innerHTML = "Nulla";
        return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("ul1").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","cerca.php?ricerca="+str+"&tipo="+document.getElementById("select-choice-0").value,true);
        xmlhttp.send();

    }

Here's the lines of code (in the PHP) that writes the contents in the UL:

// output data of each row
    while($row = $result->fetch_assoc()) {
        if($inizio == 0)
        {if ($row['CodISWC'] != $prev_iswc) {
           echo "<li>
                <a>
                <h1>". $row["NomeCanzone"]. "</h1>
                    <p>". $row["NomeArtista"];
           $prev_iswc = $row['CodISWC']; 
        }
        else{
            echo ", ". $row["NomeArtista"];   
        }

         $inizio = 1;
        }
        else{
            if ($row['CodISWC'] != $prev_iswc) {
           echo "</p>
                </a>
            </li><li>
                <a>
                <h1>". $row["NomeCanzone"]. "</h1>
                    <p>". $row["NomeArtista"];
           $prev_iswc = $row['CodISWC']; 
        }
        else{
            echo ", ". $row["NomeArtista"];   
        }


        }

    }

Asynchronous PHP call to send email

I need to send an email (email.php) which should process asynchronously with main execution. Any echo, error etc happens in the email should not come in play in the main execution. Also the main execution should proceed without having to wait for email to send or fail to send.

Currently an ajax call is made to process.php file which end like the one below. But sendProcessEmail() gets executed first before jumping to next line of code, which is normal. But how could i make sendProcessEmail() asynchronous?

$processdata($sid);
sendProcessEmail($data_email, $data_displayname);// asynchronous 
$form_data = $getLatestData(); // this line should execute right after sendProcessEmail() is called
echo json_encode($form_data);

Spoofing xmlhttprequest (greasemonkey)

I am blocking an XMLHttpRequest from greasemonkey but the page bugs when it gets no response. So i tried spoofing as if the response is recieved. Unforunetly it seems XMLHttpRequest has fields read-only. So i created a fake object :

fakeresponse = "for (;;);"+JSON.stringify(fakeresponse);


var xhr2 = {};
xhr2.readyState = 0;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.readyState = 1;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.readyState = 2;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.readyState = 3;
if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);
xhr2.response = fakeresponse;
xhr2.responseText = fakeresponse;
xhr2.responseXML = fakeresponse;
xhr2.status = 200;
xhr2.readyState = 4;

if(xhr.onreadystatechange!==undefined) xhr.onreadystatechange.call(xhr2);

the object is :

Object {response: "for (;;);{"__ar":1,"payload":{"actions":[{"..."},"bootloadable":{},"ixData":{},"lid":"0"}", responseText: "for (;;);...", responseXML: "for (;;);....", status: 200, readyState: 4}

but nothing happens.. is there any other way i can simulate this or do i have to dive in deep with a debugger ? also the page uses a library rather than pure xhr object, can that be an issue ?

ajax code with echo

i have this ajax code

                   <script>
                  $(document).ready(function(){
                      $('ul#tab li:first').html('<?php echo $channel;?>');
                      $('ul#tabs li').on("click",function(){
                          //        $('ul#tab li.active').html($(this).html());
                          $('ul#tab li').html("");
                          //$('ul#tab li.active').html($(this).html());
                          var index = $( "ul#tabs li" ).index( $(this) );
                          $.post("../admin/ajax/ch1.php", {index: index}, function(result){
                              $('ul#tab li.active').html(result);
                          });
                      });
                  });
              </script>

and in the php ch1.php is

<?php
$ch1tab1= file_get_contents("../channels/ch1tab1.html");
$ch1tab2= file_get_contents("../channels/ch1tab2.html");
$ch1tab3= file_get_contents("../channels/ch1tab3.html");
$ch1tab4= file_get_contents("../channels/ch1tab4.html");
$ch1tab5= file_get_contents("../channels/ch1tab5.html");
$channel = $_POST['index'];
if ($_POST['index'] == 0 ){ $channel = $ch1tab1;}
else if ($_POST['index'] == 1){ $channel = $ch1tab2;}
else if ($_POST['index'] == 2 ){ $channel= $ch1tab3;}
else if ($_POST['index'] == 3 ) {$channel = $ch1tab4;}
else if ($_POST['index'] == 4 ) {$channel = $ch1tab5;}
echo $channel; ?>

the varible ch1tab4 have a code , and it is not work , echo blank what i should to do plz ?