Kwaasi Djin
Kwaasi Djin

Reputation: 125

Send array and non array to php using jquery ajax

I'm trying to implement a photo tagging system with jquery and php. I have a form with one input which is known and 6 other inputs that could vary( depends on how many people in the photo the user wants to tag. Maximum is 6 ).

The problem is the first input( Photo title) only has one value an the other possible six inputs have 4 values namely: firstname lastname x position y position

I would like to know the best way to pass all this data to php where I can make a mysql insert. At the moment I have the following code

  html

 <form id="uploadedphotoForm">

<textarea id="phototitle" name="title" maxlength="70" placeholder="Say something about your style."></textarea>
<input type="hidden" value="'foo','bar','10','787'" name="phototags[]" />
<input type="hidden" value="'john','doe','565','434" name="phototags[]" />
</form>

I would like to use jquery serialize to get all the data in the form so that in php I can do something like

    var data = $('#uploadedphotoForm").serialize();

        $.ajax({
     url: 'photo.php',
     type: 'POST',
     data: data,
     cache: false,
     success: function (data) {
         var json = jQuery.parseJSON(data);
         if (json.status == 'uploaded') {

         }

In php

   $title = $_POST['title'];

Ideally I would like to get the tags in an array so I can use a mysql insert like

  INSERT INTO tbl_name (firstname,lastname,xposition,yposition) VALUES("foo","bar",10,787),("john","doe","565","434");

Upvotes: 0

Views: 75

Answers (1)

G&#252;ven Altuntaş
G&#252;ven Altuntaş

Reputation: 253

ajax datatype can help

var request = $.ajax({
                url: "script.php",
                type: "POST",
                data: { id : menuId },
                dataType: "json" /*this line can be usefull for u*/
              });

here is documentation: http://api.jquery.com/jquery.ajax/

Example:

Jquery:

            var phototagsjson = [];
            $("input[name='phototags[]']").each(function(){
                var myval = $(this).val();
                var myarray = myval.split(",");
                var phototgsnode = {};
                phototgsnode["firstname"]=myarray[0];
                phototgsnode["lastname"]=myarray[1];
                phototgsnode["xcor"]=myarray[2];
                phototgsnode["ycor"]=myarray[3];
                phototagsjson.push(phototgsnode );
            });
            $.ajax({
                url: "script.php",
                type: "POST",
                data: { phototitle: $("#phototitle").val(),phototags:phototagsjson},
                dataType: "json" 
              });

on php u will get phototags

Upvotes: 1

Related Questions