Sending php value to js via ajax - javascript

So, I have the following ajax call:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
Then my php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
As you can see, in the php function, there are two separate thing going on.
Getting tag list passed onto the js as variable.
echo $tag->term_id; shows a number like this "16508164981650616502165031650416505165071650116520." So, somehow I need to put comma in between each term id (not sure how) so it looks like this : "16508,16498,16506,16502,16503,16504,16505,16507,16501,16520"
Then I need to pass these values to js to be used as a variable (not sure how)
another_php file is passed onto js (Works fine).
Questions:
How to do I add "comma" in between the tag term_id?
How do I pass these tag values to js?
EDIT: Using json_encode to pass data
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});

Using json_encode to send an array containing both data that you require front end you then need to make the following changes to your ajax function.
Change the dataType to json
Access the data as data.another_php and data.tag_id
The full ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});

To add the comma in between you could use a variable to store instead of echo'ing immediately. Like this :
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;

Related

Jquery ajax with JSON return can't access to data inside the JSON

So I have this jquery code:
$(function(){
var url = 'template/traitComTest.php';
window.onload = function(e) {
// $(".formCom").ajaxForm({url: 'template/traitComTest.php', type: 'post'});
$.ajax({
type: "POST",
url: url,
data: $( ".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
}
});
}
});
with this php code:
if (isset($_REQUEST)) {
$adresse = $_POST['adresse'];
$com = $_POST['commentaire'];
$sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem ');
$sql->execute(array(
":com" => $com,
":exem" => $adresse
));
$myData1 = array('result' => $sql);
echo json_encode($myData1);
$sql->closeCursor();
$sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp");
$sqlSelect->execute(array(
":exemp" => $adresse
));
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
}
I get this response from ajax on chrome' console =>
{"result":{"queryString":"UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem "}}{"result1":{"queryString":"SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"}}
and my issue is that I can't access to the data inside the json and need your help
Ok so you are basically returning 2 seperate sets of json encodes. It does not work that way. you can only accept a single set of json while reading through ajax. Not two. In your php script i see that you have included that following parts.
$myData1 = array('result' => $sql);
echo json_encode($myData1);
and
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
you should remove both parts and combine them into one single array using array_merge
$myData1 = array('result' => $sql);
$myData = array('result1' => $sqlSelect);
echo json_encode(array_merge(myData1, $myData));
also in your ajax request, set dataType to json
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
});
You have 2 problems:
You are sending back invalid json: Instead of echoing out different json strings, you need to build a data-structure (an array or object) and only at the end encode and echo that once. Now you have concatenated json in your response and that makes it really hard to parse.
You are not parsing the json you get back in your javascript. When you return valid json (see 1.), you can add dataType: 'json' to your ajax call to have jQuery parse the response automatically:
$.ajax({
type: "POST",
dataType: 'json',
url: url,
// etc.
So you have a form and you want to submit and that ajax will return some data after submitting the form. And if you want to access the data of response. You need to add this things
1.) Add type = 'post' in your $.ajax object
2.) And use JSON.parse(response)

Javascript and PHP. Sending Multiple Array to PHP Using Ajax and Convert it to PHP Array

I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code

Ajax change php variable

I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});

Not able to supply right argument to foreach statement

Hello I have 2 html tables. I am using jquery UI to change the position of the table and pass this jquery event arguments through ajax while taking index and item id of the table position so that I can update in the database the current position of the table. Everything is running fine I can pass the parameter. The only mistake I am making is I am not able to take this argument in foreach statement properly. It is generating an error in foreach statement that invalid argument supplied for foreach().Here is my fiddle :demo. I want to pass array but i am passing string in ajax. And not able to do so.I am getting like this when i try to print_r($_POST): Array ( [aktion] => show-widget [widget] => 1 [item] => Fahrzeuge )
Here is my code:
dashboard.js
$("#widget_update").sortable({
update : function(event, ui) {
var widget = $('#widget_update').sortable('serialize');
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {'aktion' : 'show-widget','widget':ui.item.index(),'item':ui.item[0].id},
success: function(data){
$('#widget').html(data.html);
},
error: function(data){
alert('Error');
}
});
}
});
dashboard.php
foreach ($_GET['item'] as $position => $item) :
$sql="Update dashboard_widget_users inner join dashboard_widget on dashboard_widget_users.dsnr_dashboard_widget=dashboard_widget.ID
set dashboard_widget_users.position=".$position."
where dashboard_widget.name='".$item."' and dashboard_widget_users.dsnr_yw_user=10";
$sql_update=mysql_query($sql);
endforeach;
You passed ui.item[0].id to your item property for your data. I think it is passing a string instead of an array that will be used to your foreach.
Try to pass ui.item
Hope that helps.
Answer 2:
Since you already know the position and id, you could loop them and store data in an object before passing to data property. This code may guide you:
$("#widget_update").sortable({
update : function(event, ui) {
var widget = $('#widget_update').sortable('serialize'),
items = [];
for (var i in ui.item) {
item = item[i];
items.push({
position: i,
id: item.id
})
}
$.ajax({
type: "POST",
url: "ajax/dashboard.php",
dataType : 'json',
cache: false,
data: {
'aktion': 'show-widget',
'widget': ui.item.index(), // I'm not sure what is this for
'item': items
},
success: function(data){
$('#widget').html(data.html);
},
error: function(data){
alert('Error');
}
});
}
});
**In your PHP
// print_r($_POST);
foreach ($_POST["item"] as $value) {
// print_r($value);
$id = $value["id"];
$position = $value["position"];
}
These codes are not tested but you can see whats happening in there.

Using ajax to call php and return multiple variables?

I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.
This is my JS.
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
alert(output);
}
});
my PHP
<?php
$fileId = ($_GET['id']);
$num1 = 1;
$num2 = 2;
?>
From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?
also this is a very basic idea of what I have planned to do if I can achieve this.
You can return as many variables as you want with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
You can go for Json in PHP and javascript if you want array in response for a ajax request
PHP Code
<?php
$fileId = isset($_GET['id'])?$_GET['id']:0;
echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
?>
Js Code
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
console.log(response);
alert(response.num1);
}
});
convert json to object
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
item=JSON.parse(response);
console.log(item);
alert(item.num1);
}
});
Use a simply string and explode(split) it further in ajax response. Here is PHP code
<?php
$fileId = ($_GET['id']);
echo $num1."|".$num2;
?>
Now split(explode) the response with JavaScript
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
var my_arr = output.split("|");
console.log(my_arr[0] + "" + my_arr[1]);
}
});
you can simply return it like that
return ['num1'=>$num1,'num2' => $num2];
and also, you can access it as followed,
respone.num1

Categories