Viewed   334 times

I have a div which contains some text for the database:

<div id="summary">Here is summary of movie</div>

And list of links:

<a href="?id=1" class="movie">Name of movie</a>
<a href="?id=2" class="movie">Name of movie</a>
..

The process should be something like this:

  1. Click on the link
  2. Ajax using the url of the link to pass data via GET to php file / same page
  3. PHP returns string
  4. The div is changed to this string

 Answers

1
<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>
Thursday, August 18, 2022
5
data: { activitiesArray: activities },

That's it! Now you can access it in PHP:

<?php $myArray = $_REQUEST['activitiesArray']; ?>
Wednesday, October 19, 2022
4

You are not able to see content loaded by AJAX because the page is reloading as soon as you click the anchor. Disable the anchor event by using preventDefault() and this should fix it.

<script type="text/javascript">
    var page = 1;
    $(document).on('click','.BlogButton',function(e){

        // stop page from reloading
        e.preventDefault();

        $("#posts").load("miniBlog.php", function(response, status, xhr) {
            if (status == "error") {
                var msg = "Error!: ";
                alert(msg);
            }
        });
        page++;
    });
</script>
Saturday, September 17, 2022
2

you problem that selector ('#services') takes only first input value. You should remove id and just serialize form as below.

If all you need to pass is all values from form you can use

data: $('form#my-form').serialize() // this code puts all of the inputs into passable and readable for PHP, way.

And then in $_POST['service'] will be an array of inputs values.

For example:

<form action="save.php" method="post" id="services">
    <input type="text" name="service[0]" value="1st Service" />
    <input type="text" name="service[1]" value="2nd Service" />
    <input type="text" name="service[2]" value="3rd Service" />
    <input type="text" name="service[..]" value=".. Service" />
    <input type="text" name="service[N]" value="N Service" />
</form>

In your JS:

$.post($('form#services').attr('action'), $('form#services').serialize(), function(response) {});

And then in save.php you can get an array in $_POST:

var_dump($_POST['service']);

Hope that's is exactly what you need.

Monday, October 31, 2022
 
r2d2
 
2

Try utilizing json to upload , process file object

html

<div id="drop" class="drop-area ui-widget-header">
  <div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
  <input type="file" name="file" id="file" multiple="true" accepts="image/*" />
  <ul class="gallery-image-list" id="uploads">
    <!-- The file uploads will be shown here -->
  </ul>
</form>
<div id="listTable"></div>

css

  #uploads {
      display:block;
      position:relative;
  } 

  #uploads li {
      list-style:none;
  }

  #drop {
      width: 90%;
      height: 100px;
      padding: 0.5em;
      float: left;
      margin: 10px;
      border: 8px dotted grey;
  }

  #drop.hover {
      border: 8px dotted green;
  }

  #drop.err {
      border: 8px dotted orangered;
  }

js

var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
    context: display,
    contentType: "application/json",
    dataType: "json",
    beforeSend: function (jqxhr, settings) {
        // pre-process `file`
        var file = JSON.parse(
                   decodeURIComponent(settings.data.split(/=/)[1])
                   );
        // add `progress` element for each `file`
        var progress = $("<progress />", {
                "class": "file-" + (!!$("progress").length 
                         ? $("progress").length 
                         : "0"),
                "min": 0,
                "max": 0,
                "value": 0,
                "data-name": file.name
        });
        this.append(progress, file.name + "<br />");
        jqxhr.name = progress.attr("class"); 
    }
});

var processFiles = function processFiles(event) {
    event.preventDefault();
    // process `input[type=file]`, `droppable` `file`
    var files = event.target.files || event.dataTransfer.files;
    var images = $.map(files, function (file, i) {
        var reader = new FileReader();
        var dfd = new $.Deferred();
        reader.onload = function (e) {
            dfd.resolveWith(file, [e.target.result])
        };
        reader.readAsDataURL(new Blob([file], {
            "type": file.type
        }));
        return dfd.then(function (data) {
            return $.ajax({
                type: "POST",
                url: "/echo/json/",
                data: {
                    "file": JSON.stringify({
                            "file": data,
                            "name": this.name,
                            "size": this.size,
                            "type": this.type
                    })
                },
                xhr: function () {
                    // do `progress` event stuff
                    var uploads = this.context;
                    var progress = this.context.find("progress:last");
                    var xhrUpload = $.ajaxSettings.xhr();
                    if (xhrUpload.upload) {
                        xhrUpload.upload.onprogress = function (evt) {
                            progress.attr({
                                    "max": evt.total,
                                    "value": evt.loaded
                            })
                        };
                        xhrUpload.upload.onloadend = function (evt) {
                            var progressData = progress.eq(-1);
                            console.log(progressData.data("name")
                                    + " upload complete...");
                            var img = new Image;
                            $(img).addClass(progressData.eq(-1)
                            .attr("class"));
                            img.onload = function () {
                                if (this.complete) {
                                  console.log(
                                      progressData.data("name")
                                      + " preview loading..."
                                  );
                                };

                            };
                        uploads.append("<br /><li>", img, "</li><br />");
                        };
                    }
                    return xhrUpload;
                }
            })
            .then(function (data, textStatus, jqxhr) {
                console.log(data)
                this.find("img[class=" + jqxhr.name + "]")
                .attr("src", data.file)
                .before("<span>" + data.name + "</span><br />");
                return data
            }, function (jqxhr, textStatus, errorThrown) {
                console.log(errorThrown);
                return errorThrown
            });
        })
    });
    $.when.apply(display, images).then(function () {
        var result = $.makeArray(arguments);
        console.log(result.length, "uploads complete");
    }, function err(jqxhr, textStatus, errorThrown) {
        console.log(jqxhr, textStatus, errorThrown)
    })
};

$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
    $(this).addClass("hover");
    return false;
};

droppable.ondragend = function () {
    $(this).removeClass("hover")
    return false;
};

droppable.ondrop = function (e) {
    $(this).removeClass("hover");
    var image = Array.prototype.slice.call(e.dataTransfer.files)
        .every(function (img, i) {
        return /^image/.test(img.type)
    });
    e.preventDefault();
    // if `file`, file type `image` , process `file`
    if (!!e.dataTransfer.files.length && image) {
            $(this).find(".drop-area-label")
            .css("color", "blue")
            .html(function (i, html) {
            $(this).delay(3000, "msg").queue("msg", function () {
                $(this).css("color", "initial").html(html)
            }).dequeue("msg");
            return "File dropped, processing file upload...";
        });
        processFiles(e);
    } else {
            // if dropped `file` _not_ `image`
            $(this)
            .removeClass("hover")
            .addClass("err")
            .find(".drop-area-label")
            .css("color", "darkred")
            .html(function (i, html) {
            $(this).delay(3000, "msg").queue("msg", function () {
                $(this).css("color", "initial").html(html)
                .parent("#drop").removeClass("err")
            }).dequeue("msg");
            return "Please drop image file...";
        });
    };
};

php

<?php
  if (isset($_POST["file"])) {
    // do php stuff
    // call `json_encode` on `file` object
    $file = json_encode($_POST["file"]);
    // return `file` as `json` string
    echo $file;
  };

jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

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