I am trying to Pass a comma separated Id values to PHP using Jquery Post. I have below code in my Jquery
var values = [];
$('tr#trdata td:nth-child(1)').each(function () {
values.push("'"+$(this).html()+"'");
});
Above code is out putting value like this '238','239','240','241','242','243','244','245','246'
I am then Trying to post above value using below code
$.ajax({
url : "mypage.php",
method:"POST",
dataType:"text",
cache:false,
data:{page_no:values, type: type, keyword: keyword},
success:function(data){
}
});
And in my php I am trying to get the value with below code
if (isset($_POST['page_no'])) {
$page = $_POST['page_no'];
}else{
$page = 0;
}
I am getting the comma separated values in console correctly but in php it is always empty
what is the wrong I am doing?
Related
My experience with jQuery is very limited, and im on a very steep learning cure.
I have a dynamic form which is generated based on main and sub menu, placing marker points in each row which has an inputfield, I have managed to create a loop which looks for all the marker points and return the field_name and the field_value of any input field.
$('td[edit="1"]').each(function(i, el) {
field_name = $(el).attr('fieldname');
field_val = $('#'+field_name).val();
alert(field_name + " = " + field_val);
});
What I am having trouble with now, is converting this in to an array or JSON and pushing it to a PHP file which can then pick up the results.
Here is an example of how I currently submit a forms data to a PHP file, however is not dynamic as I have to specify which fields and values I want to send.
$.ajax({
type: "POST",
url: "form.php",
data: {
title : title,
age : age
}).done(function(data) {
results = $(data).find('data').html();
}).fail(function() {
alert("error");
}
);
If i have clearly understand your problem then You will have to use serialize method of jquery to send fields to php file. You can do like
data:$('form').serialize(),
It will send all the fields to php file.
As data you can user Jquery on the form to create an array of all the data:
https://api.jquery.com/serializeArray/
$.ajax({
type: "POST",
url: "form.php",
data: $('#idOfForm').serializeArray()
}).done(function(data) {
results = $(data).find('data').html();
}).fail(function() {
alert("error");
});
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: text,
dataType: "text"
});
insertGroupData.done(function(msg){
alert(msg);
});
This is the first half, I'm stuck in the 1st line of my backend.php
I think it should be catch the POST value, but what should I catch?
<?php
if(isset($_POST["_____??_____"])){
echo "test";
}
Jquery: if your data should be like
data: {test:text},
Then in PHP you can use to get like below,
if(isset($_POST["test"])){
echo "test";
}
Explanation about data:
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting .
Ref: http://api.jquery.com/jQuery.ajax/
change your code to this
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: {text:text},
dataType: "text"
});
in backend page you can check it like
echo $_REQUEST['text];
or
echo $_POST['text];
A lesson in jQuery
$(function () {
var
url = 'your/target/script.php',
data,
fn = function (text) {alert(text);},
// fn will expect text, so set return as text
dataType = 'text';
// this POST data will populate $_POST as $_POST[key] = 'value'
data = {
ajax : 1,
key : 'value',
key2 : 'another value'
};
// shorthand notation is convenient sometimes
$.post(url,data,fn,dataType);
});
Your php now has access to your key value pairs
<?php
// in my example the 3 are set
if (isset($_POST['ajax'])) {
$_POST['key'];
$_POST['key2'];
}
Happy coding
I have a form with several identical fields:
<input type="text" id="qte" value="" name="qte[]">
How transmetre the array in my file processing?
I noticed that the array sent ajax became a string.
$("#form_commande").submit(function(event){
var qte = $("#qte").val();
if(qte== '')
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
return false;
}
Get value in jquery like:
$("#form_commande").submit(function(event){
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
if(qte_array.length== 0)
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: {qte:qte_array},
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
});
and get it in php like:
$qte = $_POST["qte"];
here qte an array
This returns the input textbox object:
$("#qte");
This returns the value of the input textbox object:
$("#qte").val();
Remember you asked for DOM object by id, and this by definition returns only one.
Please read this topic:
JQuery - Reading an array of form values and displaying it?
In short you should iterate with tag name="qte[]" instead of using ids. In DOM you cannot have two different objects with different ids.
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
After this you have all the values of qte[] array in one object - qte_array. You can later serialize this array to JSON and then pass it as a string.
ALTHOUGH - you shouldn't need to do all those things. You can send ajax request directly with your form, all those data in these inputs will be transferred anyway. You just need to handle them correctly server-side.
id is unique, you can't have more fields with the same ID.
By the way you should convert values to JSON and pass them to Ajax
Below is my AJAX code. I've written the questions in the comments.
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
success: function(arrayphp) {
//here one by one text is being received from php from within a loop
//each text item is getting displayed as link here
//it is OK that text is getting displayed as link
//BUT the problem is that all the text returned from php are getting displayed as
//one link i.e between one "<a></a>"
//I WANT THAT EACH TEXT SHOULD BE DISPLAYED AS SEPERATE LINKS
//AS EACH TEXT IS GETTING RETURNED FROM WITHIN SEPARATE ITERATIONS OF PHP LOOP
var link = $('<font color="red">' + arrayphp + '</font>');
linkclass = link.attr("class");
$(".searchby .searchlist").append(link);
}
});
What to do?
Php throws everything at once to the ajax success function... You need to use json_encode on the php array and echo it to pass it as json array.
<?php
$return = array();
foreach($array as $key=>$value){
//Do your processing of $value here
$processed_value = $value;
array_push($return, $processed_value);
}
echo json_encode($return);
?>
In the ajax call set the dataType as "json" for it to parse the data passed from php as json array. Loop across the array received by using jquery each.
$.ajax({
type: "POST",
url: "dbtryout2_2.php",
data: datastr,
dataType: "json",
success: function(arrayjson) {
$.each(function(arrayjson, function(i, processed_value) {
var link = $('<font color="red">' + processed_value + '</font>');
linkclass = link.attr("class");
$(".searchby .searchlist").append(link);
});
}
});
In Javascript I'm creating an array for a user side list
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
alert(dataArr[0]);
This is working as expected and will alert the first item in the list. "Frank" or whatever it may be.
$.ajax({
url: "fiddle.php",
type: "POST",
data: "dataArr="+dataArr,
success: function(response) {
alert(response);}
I send this array over to PHP and the ajax test confirms its retrieved from a var_dump on the other side.
echo ($_POST['dataArr'][1]);
The problem occurs here when trying to output a particular item, in this case the 2nd item which may be "John" it'll instead output the 2nd character in the first item "r". This is appearing in the Ajax test window. I'm looking for the whole word instead.
Is it a syntax error or a problem with how the data is passed?
I think the problem is related to how you are sending your data in the ajax call.
Try this:
JS
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
$.ajax({
url: "fiddle.php",
type: "POST",
data: dataArr, //Send just the array
success: function(response) {
alert(response);
}
});
PHP
var_dump($_POST['dataArr']);
It is because your array is getting converted to string form.
do JSON.stringify() at client side and json_decode at server side
like
in the ajax call
data: "dataArr="+JSON.stringify(dataArr),
and in the php code
$dataArr = json_encode($_POST['dataArr']);
var_dump($dataArr);