passing a php array through jquery ajax - php

I want to pass an array through ajax, but not sure how I would do this.
<input type="button" data-array="'.$array.'" id="button" value="click">
I know I cant put arrays in html, but I couldnt think of how else to explain what I am trying to accomplish.
$('#button').click(function(){
array = $(this).attr('data-array');
$.ajax({
type : 'POST',
dataType : 'json',
url : 'ajax.php',
data : 'array='+array,
success : function(data) {
$('#result').html(data);
}
});
});
So I then want to pass that array variable, $array, through to ajax.php. Is this even possible, if so how is it done? I am guess something to do with json?

Instead of storing the array in html you could store it in a session variable and call it later when needed.
$_SESSION['dataArray'] = $array;

Related

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

How can you pass a sql query through ajax?

I have sql query I need pass through to an ajax file.
$qry = mysqli_query($this->con,"SELECT * FROM products");
I have contained the variable in html such as:
<input type="button" data-qry="'.$qry.'" id="button" value="click">
I use the ajax jquery code below to pass it through:
$('#button').click(function(){
array = $(this).attr('data-qry');
$.ajax({
type : 'POST',
dataType : 'json',
url : 'ajax.php',
data : 'qry='+qry,
success : function(data) {
$('#result').html(data);
}
});
});
I want to be able to open ajax.php and perform
$qry = $_POST['qry'];
$row = mysqli_fetch_assoc($qry);
Of course this is not working. How can I pass the query through, does it need to be done through JSON some how?
At the start of your button you assign the value to the variable array
array = $(this).attr('data-qry');
But you send qry with the ajax
data : 'qry='+qry,
The way you fix this is by sending the variable you assign the value to

jquery : pass an array in ajax

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

how to pass the $_SESSION['var'] array to jquery and do ajax?

I have problem here, I need all the stuffs inside this $_SESSION['cart'] thing
and pass it to jQuery to use it in a php-ajax file, my question is, how to do that?
Here's what I have in mind
function myfunc()
{
//save cart to db of logged user
$("a.savecart").click(function(){
//how to assign the $_SESSION['cart'] into a js variable ?
$.ajax({
type: "POST",
url: "classes/ajax.cart.php",
data: //what to put here ?
success: function(data){
alert(data);
location.reload();
}
});
return false;
}
});
}
Just echo it like below (just example):
data: {"cart_id" : <?php echo $_SESSION['cart']; ?>},
Or if your $_SESSION['cart'] is an associative array, you can use json_encode function.
data: <?php echo json_encode($_SESSION['cart']); ?>,
EDIT:
For example, if your $_SESSION['cart'] is an array like below:
array(
'id' => 111;
'num' => 222;
//etc...
)
Then in your php ajax part, you could get the data by $_POST['id'] and $_POST['num'] etc...
I need all the stuffs inside this $_SESSION['cart'] thing and pass it
to jquery to use it in a php-ajax file,
If the data you need is in session, then you can send empty ajax call and use $_SESSION['cart']. No need to pass it again.
OR
You can assign the value to a hidden field and use it in jquery as -
data: $("#session_value").val(),
Use json. If you have php > 5.2 on your server you can use json_decode and json_encode functions, see at manual. In data parameter you can use these trick:
data: 'jsondata={"some_key":"' + some_var + '"}'
attention you should use double quotes in key and value pair. So when it comes to script you can do that:
json_decode($_POST['jsondata']);

Fetch input value from certain class and send with jquery

<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});

Categories