Jump to content

jquery/ajax post array data


ma201dq

Recommended Posts

Hi Guys,

 

I have a php page, where I generate a form dynamically like this:

while($result = mysql_fetch_object($run)){
//dynamically generate input
<input type="text" name="id[]" id="id" class="input" value="1" />
<input type="text" name="price[]" id="price" class="input" value="2.00" />
} 

 

this form posts an array of id[] and prices[] when submitted and uses jquery/ajax to grab the data and post to another php page for processing.

 

my jquery/ajax:

$(".button").click(function() {

    

         var price = $("input#price").val();

        var id = $("input#id").val();

        

        var dataString = {price: price, id: id};

        //var dataString = '&price=' + price + '&id=' + id;

                

        $.ajax({

      type: "POST",

      url: "../web20forms/edit_template_1.php",

      data: dataString.serialize(),

      dataType: "json",

      success: function(data) {

        $('#editpriceoflessondiv').html("<div id='message_1'></div>");

        $('#message_1').html(data)

        

        .hide()

        .fadeIn(1500, function() {

        

        });

      }

     });

    return false;

    }); 

 

my issue is that I dont know how to loop through my data in the jquery/ajax so that it post an array of the data to other php page.  this is the bit of jquery/ajax i need to loop and post:

var dataString = {price: price, id: id};

 

at the moment only one set of data is posted:

array(2) { ["price"]=> string(5) "12.00" ["id"]=> string(1) "6" }

 

but this needs post like this:

array(2) { ["price"]=> string(5) "12.00" ["id"]=> string(1) "6" }

array(3) { ["price"]=> string(6) "13.00" ["id"]=> string(2) "7" }

 

hope you get the picture

etc

 

any help much appriciated

 

Link to comment
Share on other sites

I suggest you create an object with all the values you wish to post and pass that with the data arguement.

Also look at the $.each method in jquery with which you can easily loop through objects/arrays

 

// First create an object
var yourData = {};

// loop through your price var
$.each(price, function(index, val) {
  // do something with yourData var
});

// pass it as arguement
$.ajax({
    data: yourData
})

Link to comment
Share on other sites

dj, thanks for the reply.

 

please will you care to show me how I pass it as an argument to data?

 

I made these edits:

 

var datastring = {price: price, id: id, };

$.each(datastring, function(key, value) {  
// do something with yourData var

});

$.ajax({
      type: "POST",
      url: "../web20forms/edit_template_1.php",
      data: datastring,
      success: function(data) {
        $('#editpriceoflessondiv').html("<div id='message_1'></div>");
        $('#message_1').html(data)

        .hide()
        .fadeIn(1500, function() {
        
        });
      }
     });

 

thanks

Link to comment
Share on other sites

I don't follow.

 

right now the data passed on to my php is this:

array(2) { ["id"]=> string(1) "6" ["price"]=> string(5) "12.00" } 

 

this is correct, but its not passing the entier array of data.

 

this is done without any changes you suggested:

var submit_tmp_x = $("image#submit_tmp_lessons_x").val();

	var price = $("input#price").val();
	var id = $("input#id").val();

	var datastring = {id: id, price: price};

	$.ajax({
      		
      		url: "../web20forms/edit_template_1.php",
      		data: datastring,
		type: "POST",
  		success: function(data) {
			$('#editpriceoflessondiv').html("<div id='message_1'></div>");
			$('#message_1').html(data)
			.hide()
			.fadeIn(1500, function() {
        
        });
      }
     });

 

so My problem is that i need to post the entire array

Link to comment
Share on other sites

here you go DJ:

 


foreach($_POST['id'] as $key=>$value) {

	$id=mysql_real_escape_string($_POST['id'][$key]);
	$price=mysql_real_escape_string($_POST['price'][$key]);

	//$this->date_t=date("Y-m-d H:i:s");

			if(!$query="UPDATE 
			   				client_boroughs 
						SET
							price = '".$price."'

						WHERE
							idClient_Boroughs = '".$id."' "){


				echo mysql_error();
			}

			if(!mysql_query($query)){

				echo mysql_error();
			}

Link to comment
Share on other sites

while($result = mysql_fetch_object($run)){
//dynamically generate input
<input type="text" name="id[]" id="id" class="input" value="1" />
<input type="text" name="price[]" id="price" class="input" value="2.00" />
} 

var price = $("input#price").val();
var id = $("input#id").val();

I see your using the id selector where it wouldn't be unique in this loop. I suggest you remove the id and use a css selector instead.

 

 

You can select the prices with a css selector like so:

// get input elements where the name starts with price
var priceInputElements = $('input[name^=price]');

 

 

Here is an example how you could make your script work. It's not complete and you'll have to finish it by yourself. I added comments to explain how it works

var priceInputElements = $('input[name^=price]');

// create an new object with properties id and price
var postData = {
	id: [] // the id is an array
	price: [], // the price is an array
};

// loop over the price input elements and place the value in the postData object
$.each(priceInputElements, function(index, el) {
	// push the value in the price array
	postData.price.push($(el).val());
});

// @todo do the same loop thing for id here

$.ajax({
	url : 'response.php',
	data : postData, // post the created object here
	type : 'POST',
	dataType : 'json',
	success : function(response) {
		console.log(response);
	}
});	
});

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.