passing javascript object array to ajax - php

This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??

Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try

As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.

Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code

Related

Jquery query string type to

i am using serialize()
Some Event trigger(assume click)
var querydata= a=1&b=2&c=3 //jquery printing
$.ajax({
url: "script",
data: querydata,
method: "POST",
dataType: "text",
success: function(data) {
$("#counts").html(data);
}
});
in php do i just use the regular post method
a=htmlspecialchars($_POST["a"]); b=htmlspecialchars($_POST["b"]); and so on
or do i need to use jquery to get the string to variables and then send to data as a object array
if jquery is also an option could you tell me how i would do that im fairly new to jquery and i really want to learn it
Why bother creating a functionality that your browser+PHP provide already??
In your case, if you really have to send a raw string:
var querydata = 'a=1&b=2&c=3';
$.ajax({
url: "script",
data: querydata,
method: "POST",
dataType: "application/x-www-form-urlencoded",
success: function(data) {
$("#counts").html(data);
}
});
You may also want to simplify:
var querydata = {a: 1, b: 2, c: 3};
$.post('url', querydata, function(data){
$("#counts").html(data);
});

Pass Jquery variables to PHP using AJAX

I'm trying to make an app where if you click on a div, the data-id will be put into a variable, which will give PHP the select parameters to look for. Here's my code to better explain it.
HTML:
<div class="box" data-id="caption"></div>
JQuery:
$('.box').click(function () {
var caption = $(this).data('id');
});
After Googling I found the best way to do this is through AJAX, which I then proceeded to try:
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: ({ caption }),
success: function(data){
console.log(data);
}, error: function() {
console.log("error");
}
});
However, this doesn't seem to work. If there's a better way to do what I mentioned above, I'm open to new ideas.
EDIT
Here is my PHP code.
if(isset($_GET['caption'])){
echo $caption;
$select = "SELECT * FROM pics WHERE text = '".$caption."'";
}
?>
Look through the api at jQuery.
Your data key should contain a json object -
$.ajax({
url: 'index.php',
type: 'GET',
dataType: 'json',
data: {caption: caption},
success: function(data){
console.log(data);
}, error: function(error) {
console.log(error);
}
});

read JSON data from PHP with jQuery

I send an array from PHP with json_encode, and I trying to get with AJAX and jQuery.
Every thing is ok.
JSON structure is :
names{"p1":"John","p5":"Smith"}
jQuery code is :
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
$(data.names).each(function(key, txt) {
alert(txt);
});
}
}
this code don't return any thing! I think browser don't enter in each
what should I do ?
instead this:
$(data.names).each(function(key, txt) {
alert(txt);
});
use this:
$.each(data.names, function(key, txt) {
alert(txt);
});
and your json seems to be incorrect as you mentioned: names{"p1":"John","p5":"Smith"}
this should be like this:
{
"names": {
"p1": "John",
"p5": "Smith"
}
}
you can check your json here: http://jsonlint.com/
I'd suggest you use jQuery's $.getJSON(); http://api.jquery.com/jQuery.getJSON/
But to answer your question directly; you didn't close your ajax() function.
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
$(data.names).each(function(key, txt) {
alert(txt);
});
}
});
In your code you could just use parseJSON().
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
var d = jQuery.parseJSON(data);
// ... do stuff
}
});

Ajax passing data to php script

I am trying to send data to my PHP script to handle some stuff and generate some items.
$.ajax({
type: "POST",
url: "test.php",
data: "album="+ this.title,
success: function(response) {
content.html(response);
}
});
In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname is I get nothing, I try to get the album name by $albumname = $_GET['album'];
Though it will say undefined :/
You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.
Try sending the data like this:
var data = {};
data.album = this.title;
Then you can access it like
$_POST['album']
Notice not a 'GET'
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});

JS jquery and ajax problem

Hi i have problem with some things
Here is the code
function get_char_val(merk) {
$.ajax({
type: "POST",
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){return(data);}
});
}
alert(get_char_val("str"));
when alert comes out it's output the undefined please help fast i'm making this two days xC
get_char_val does not return anything. The success callback needs to have alert(data) in it to return the data from AJAX.
$.ajax is asynchronous - meaning it doesn't happen in order with other code, that is why the callback exists.
Your return; statement will return the value to the anonymous function you pass into the success handler. You cannot return a value like this, you need to invoke another callback instead.
function get_char_val(merk, cb) {
$.ajax({
type: "POST",
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){cb.apply(this, data);}
});
}
get_char_val("str", function(data) {
alert(data);
});
You can either set the async:false config parameter in the ajax call options or use the call back.
Using Async:false -
function get_char_val(merk)
{
var returnValue = null;
$.ajax
(
{
type: "POST",
async:false,
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){returnValue = data;}
}
);
return returnValue;
}
alert(get_char_val("str"));
P.S: Note that making ajax calls synchronous is not advisable.
Since you do an asynchronous ajax call, the response of the server is handled in the "success" function. The return in your success function is useless, you should use the "data" parameter directly in the function
This should work. Use it like this.
function get_char_val(merk) {
var myReturnData= "";
$.ajax({
type: "POST",
url: "char_info2.php",
data: { name: merk },
dataType: "html",
success: function(data){myReturnData = data;}
});
return myReturnData;
}
alert(get_char_val("str"));
Just understand the problem with your piece of code. Use the return statement under the right function.

Categories