Pass Array and String from Javascript to PHP with AJAX - javascript

I have the following ajax call.
My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123
I want to grab the addList in my PHP file as
$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123
But I couldnt convert the POST string into right forms.
I can create arrays/loops in both sides but it didnt feel right.
Whats the convenient way of doing it?
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,
success: function(count){
alert("done");
}
});
Any help will be appreciated. thanks!

try using followig code.
you just neeed to locate your form if and url to pass values to :
var form = new FormData($('#form_id')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
this will pass all form element automatically.
Working and tested code.

When you pass variable with the ajax method from jQuery, you can pass array like this :
jQuery
var myArray = newArray();
myArray.push("data1");
myString = "data2";
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: {array:myArray, param2:myString},
^name ^value
success: function(count){
alert("done");
}
});
PHP
echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2

Change your addList variable to this:
list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]

Related

Can't get jQuery var to PHP

I am trying to get a jQuery var into PHP so I can use it with mysql. I have searched everywhere but nothing seemed to solve it.
I have the following jQuery code:
$('.eventRow').click(function(){
var eventID = this.id;
$.ajax(
{
url: "index.php",
type: "POST",
data: { phpEventId: eventID},
success: function (result) {
console.log('success');
}
});
$('#hiddenBox').html(eventID);
console.log(eventID);
});
If I run this, the ID is shown in both #hiddenBox and in the console.log. The console also says "Succes" from the Ajax.
I am trying to get it in the php file:
$value = $_POST['phpEventId'];
echo "<div class = 'showNumber'>"."Nummer: ".$value."</div>";
It just says: Nummer:
It also gives no error whatsoever.
Thanks for your help!
Try
var eventID = $(this).attr('id');
Where this id comes from in your code ?
Passing it as JSON often gets the results I'm looking for. The server will interpret the JSON object as POST variables:
$.ajax({
url: "index.php",
type: "POST",
data: JSON.stringify({phpEventId: eventID}),
contentType: "application/json; charset=utf-8",
success: function (result) {
console.log(result);
}
});

How to catch array sent by PHP script as Ajax response and use further?

I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});

Image does not update when appending newly inserted row using jquery ajax

I want to insert data using ajax and show that newly inserted data in a div, but the record (i.e. image and name ) does not get updated it.
I don't want to reload page, the newly entered record should be shown without page reload, but it shows only the initial name and image.
I can't understand whats the problem. Please help. Following is the code i am using static data which is stored in a variable as an example:
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
d = new Date();
var img_name='amit.png'+'?'+d.getTime();
var s_name='Ashish';
$('#main').prepend('<img alt="client" id="p_img"><h1>'+s_name+'</h1>');
$('#p_img').attr("src", "image/Amit.png");
},
error: function (error)
{
}
});
Shouldn't the src attribute use the response/variable/generated file name?
Like this:
$('#p_img').attr("src", '/image/' + img_name);
Instead of this:
$('#p_img').attr("src", "image/Amit.png");
It can be two reasons :
the image you are prepending to the DOM is not yet in the DOM when you are trying to add the src
or the src is not existing (should be an absolute or relative path)
Try to prepend the image with the src
$('#main').prepend('<img alt="client" src="ABSOLUTE_OR_RELATIVE_PATH/image/Amit.png"><h1>Amit</h1>');
Also there is no need to create a variable s_name which you only use once.
you can done it easily by returing List of data and populating the div with ajax success result.
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
// in data you are getting your result ...
// now for ease split json format data and store in list
// m not sure about your formate so m assuming at first index it
//should be image URL so..
var res = data.split(",");
var imgSrc = res[0];
$('#main').prepend('<img alt="client" id="p_img"/>');
$('#p_img').attr("src", imgSrc);
},
error: function (error)
{
}
});

Ajax wont retrieve the file from php file

Hi guys this script was working fine when I add a console.log but as soon as I replaced the console.log with the $.ajax() function it wont give me the result back from the php file the ajax function I used was working from my other projects but I cant seem to find out why it wont work on this snippet
Here is my js code :
$(document).ready(function(){
$("#qs").find(".chs").each(function(i,obj){
$(this).addClass("chs"+i);
$(".chs"+i).on("click",function(){
var s = $(this).data("lvs"),carrier= {"vars":s};
$.ajax({
url: aScript.php,
type: "POST",
data: carrier,
dataType: "json"
success: function(data) {
console.log(data) }
});
});
});
});
my php file looks like this
<?php
$json = $_POST['carrier'];
$data = json_decode($json);
$d = $data->vars;
echo $d;
?>
<input type="hidden" id="ss" value="<?=$d?>" />
can someone review this file for me cause I cant seem to find whats wrong please help me find out whats wrong with this script
You should wrap the filename inside quotes, as it is a string variable
$.ajax({
url: 'aScript.php',
type: "POST",
data: carrier,
dataType: "json",
success: function(data) {
console.log(data) }
});
});
There are some issues with your code
in this line url: aScript.php, the url string is not quoted, it should be url: 'aScript.php',
you set dataType: "json" but aScript.php returns html instead of json, remove that line
the data you're passing is not json, it will be serialized into key=value pairs and you'll be able to access it via $d = $_POST['vars'];

Javascript String Var + jQuery Textbox Val

Anyone know why the following code doesn't seem to work? I'm trying to append whatever is in the textbox to the URL string.
$.ajax({
type: 'POST',
url: 'http://myurl.com/something.php?myname='+$('#myname').val(),
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20;
chart.series[0].addPoint(point[0], true, shift);
chart.series[1].addPoint(point[1], true, shift);
setTimeout(requestData, 5000);
},
cache: false
});
You did not let us know what is not working. $('#myname').val() should work if you really have a myname object.
However, I could not help noticing that you are requesting via POST, but at the same time you are building a query string. Try changing the type to GET and see how it goes.
May be the value of the element contains characters that can alter the meaning of query strings, e.g. if the value begins with &asdf, the url becomes http://myurl.com/something.php?myname=&asdf. If so, try this:
$.ajax({
type: 'POST',
url: 'http://myurl.com/something.php?myname=' + encodeURIComponent($('#myname').val()), // pass via GET
// I assume there is no data to pass -- uncomment otherwise
// data: {
// name1: value1,
// name2: value2,
// },
success:
.
.
.
I would recommend using a variable instead of doing it inline like so:
<script type="text/javascript>
$(document).ready(function(){
var name = $("#myname").val();
//any validation would occur here
var posturl = "http://myurl.com/something.php?myname" + name;
$.ajax({
type: 'POST',
url: posturl,
data: data,
success: success
dataType: dataType
});
});
</script>
<body>
<input id="myname" value="John Doe" />
</body>

Categories