Pass PHP array to external jQuery $.ajax - javascript

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax

in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});

Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Related

How can I pass Javascript array to a PHP array on button click?

I am having trouble passing a Javascript array to a PHP array on the same page when the submit button is pressed. I have seen discussion of JSON.stringify and json_encode on other posts, but I am not sure how to use those functions with my code.
JS:
<script>
var kegs = [];
var textarea = document.getElementById("your_textarea");
$("#kegId").on('keyup', function (e) {
if (e.keyCode == 13) {
kegs.push($(this).val());
$("#kegId").val("");
textarea.value = kegs.join("\n");
};
});
</script>
PHP:
if (!isset($_POST['btn-addkegs'])) {
//I want to set the Javascript array 'kegs' to a php variable here
Using Ajax will do it for you! I wrote this code that sends an array to PHP on the same page. Once you get the array in PHP you can do whatever you want with it :).Just copy and paste this file and called it index.php to see the result. This will totally help you!
<?php
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'You array is: ' . $_POST['myArray'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "random"></div>
<script type = "text/javascript">
$(document).ready(function() {
var arr = [2,4,5,6,7];
var myArray = JSON.stringify(arr);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("result: " + result);
console.log(result);
$("#random").html(result);
}
});
});
</script>
</body>
</html>
This can be achieved by using ajax(), its syntax is:
$.ajax({
url: 'process.php', // file where data processing is done
type: 'POST',
data: {
var1 :val1,
var2 :val2
// parameter set
},
success: function(response){ // response from process.php
// do your stuff here
}
});
Read more about ajax
As you are using the jquery
var jsArray = makeJavascriptArrayhere //
$.ajax({
url: urlToPhpFile, // file where data processing is done
type: Method,
data:jsArray,
success: function(response){ // response from process.php
// do your stuff here
}
});
now in your php file
var_dump($_POST); //see on network liner tabs

Not sending data into controller with onclick function

I use this button in jason.
<button id="bid" type="button" class="button" onclick="connect()">Save</button>
It show altert when I use alert after document.getElementById. But it not works in ajax function. Here is my connect function
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
//**alert(BID + REF + POU);**
var url ='<?php echo base_url()."index.php/main/transacIn/" ?>';
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
}
alert(BID + REF + POU); this alert works but not works alert in success. And it don't sent any data into controller. Help me about it. Thanks in advance.
try this
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
var site_url = document.getElementById('site_url').value;
var url = site_url+'main/transacIn';
$.ajax({
type: "POST",
url: url,
data: {
BID : BID ,
REF: REF,
POU:POU
},
success: function(data) {
//$("#bid").hide();
alert(BID);
},
error: function(err) {
console.log(err);
}
});
}
you should a hidden field in your corresponding page <input id="site_url" type="hidden" value="<?php echo site_url(); ?>"/>
You cannot inject the php syntax into javascript file. Either you define the script in codeigniter template file as
<script type="text/javascript">
// Your javascript function
</script>
...or you can define a javascript variable in the template file which actually get the path to your controller:
var url = <?php echo base_url()."index.php/main/transacIn/" ?>';
Then on your javascript file on ajax post you are pointing to the variable defined in the template file:
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
Hope you got the idea.
Anyway you need to be careful defining global variables. It's a good practice to guard the variables by using namespaces.
Try this solution. It will work:
$.post(url , {BID: BID, REF: REF, POU:POU },
function(data){
alert(BID);
});

php - pass an array from php to jquery ajax and then again pass the same array from jquery to php

I am in a situation where i am passing an array from php to jquery ajax using json_encode and saving it in an empty array i declared in jquery script var myarr = [], and later on in the same script i am sending the same array i-e, myarr to php script through $.ajax using JSON.stringify function and receiving the array in php script like this json_decode($_POST['myarr'], true), but the problem is it is not converting back into an array. I want to receive an array so that i can use foreach loop to read that array.
Here is the code below.
First I am declaring an array in jquery script
var imgArr = [];
Then fetching all the images from php script and saving it in above declared array
PHP Script:
$getProfileId = $users->getPrfId($photoId);
$getImages = array();
$getImages = $users->getTypeImage($getProfileId);
//echo json_encode($getImages);
foreach($getImages as $value){
echo json_encode($value);
}
JQuery
$.ajax({
type: 'POST',
url: 'fetchAllImages.php',
data: {'photoId': photoId},
success: function(data){
imgArr = data;
}
});
Now in the same script on other button click i am sending this array imgArr to php Script using $.ajax. Here is the code:
JQuery:
$('#right_arrow').live('click', function(e){
var photoId = $(this).siblings('#o_popup_post').children('#o_post_box').children("#o_complete_post_image").children("img").attr("id");
$.ajax({
type: 'POST',
url: 'nextImage.php',
data: {'photoId': photoId, 'imgArr' : JSON.stringify(imgArr)},
beforeSend: function(){
$('#o_popup_post').fadeOut("normal").remove();
$('.o_background_popup').append("<div id='o_popup_post'></div>");
},
success: function(response){
$('#o_popup_post').append(response);
// alert(imgArr);
}
});
});
PHP Script:
$photoId = $_POST['photoId'];
$imageArray = array();
$imageArray = json_decode($_POST['imgArr'], true);
foreach($imageArray as $key=>$value){....}
Please help. Thanks
I tried your example on my web server... works as expected... and correctly... the only thing I removed is the beforeSend and success javascript functions implementations
I tested this and it works correctly
HTML:
test.html
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js">
</script>
</head>
<body>
<button id="btn">btn</button>
<script type="text/javascript">
$(function() {
$('#btn').on('click', function(evt) {
var photoId = 1;
var imgArr = [{ "name": "photo.jpg", "id": 1 }];
$.ajax({
type: 'POST',
url: 'test.php',
data: {'photoId': photoId, 'imgArr' : JSON.stringify(imgArr)},
beforeSend: function(){
},
success: function(response){
alert(imgArr);
}
});
});
});
</script>
</body>
</html>
PHP:
test.php
<?php
//print_r($_POST);
$photoId = $_POST['photoId'];
$imageArray = array();
$imageArray = json_decode($_POST['imgArr'], true);
print_r($imageArray);
foreach($imageArray as $key=>$value){
}
?>
the $imageArray variable is an array of arrays as shown by the print_r($imageArray) output:
Array
(
[0] => Array
(
[name] => photo.jpg
[id] => 1
)
)
thus you have to walk it like this:
foreach($imageArray as $key=>$value){
echo $value["name"];
}
or you might try this function, which handles slashes problem in the JSON according to the magic quotes setting in PHP:
function _json_decode($string) {
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return json_decode($string);
}

Passing POST variables from jQuery to PHP, want to update div

I am trying to pass the form value "New Value" from jQuery to a PHP script, and then update the "to_change" div from "Old value" to "New value". It seemed like the AJAX call succeeded, but the POST variables are not being sent to the PHP script, and when I use getJSON, I do not succeed. How could I resolve this issue?
Javascript/HTML code:
<html>
<head>
<script src = 'jquery-1.10.2.js'></script>
<script>
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
$.getJSON("parameters_form2.php", function(tmin) {
document.getElementById("to_change").innerHTML = tmin[1];
});
}
});
return false;
});
});
</script>
</head>
<body>
<div id="to_change">Old value</div>
<form id="form_tmin" name="form_tmin">
<input type="hidden" id="tmin_value" name="tmin_value" value="New value">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
PHP code:
<?php
header('Content-Type: application/json');
if ($_POST["tmin_value"]) {
$tmin[1] = $_REQUEST["tmin_value"];
}
else {
$tmin[1] = "FAILURE";
}
echo json_encode($tmin);
?>
You already have json response in data just set this data in where ever you want to display. you don not need $.getJSON again.
try like this:
$(document).ready(function() {
$("#form_tmin").submit(function(event) {
var values = $(this).serialize();
$.ajax({
type: "POST",
url: "parameters_form2.php",
data: values,
dataType: "json",
success: function(data){
document.getElementById("to_change").innerHTML = data[1];
}
});
return false;
});
});
You already have the response of query, no need to use $.getJson again
Instead just use:
success: function(data){
$("to_change").html(data[1]);
}

Access Javascript variable in php in same page

Hi I am facing problem with json data. Here is my js code.
<script>
$(function(){
$.ajax({
url:"http://example.com/salary?from=USD&to=GBP",
dataType: 'jsonp',
success:function(json){
alert(json['to']);
},
error:function(){
alert("Error");
},
});
});
</script>
I want to use json data in PHP in same page.
I know that you cannot assign Javascript value to PHP variable.
Is there way to do this?
Or is possible to do similar task in php (Jquery Ajax cross domain) like above javascript code ?
Any help?
your js code
var my_json_obj = new Object();
my_json_obj .name = "Lanny";
my_json_obj .age = "25";
my_json_obj .location = "China";
var json_str = JSON.stringify(my_json_obj);
<script>
$(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "my.php",
data: {
postData: json_str
},
success: function (data) { alert(data) },
eror: function (data) { alert(data) }
});
});
</script>
your my.php file
$postData=$_POST['postData'];
$my_obj=json_decode($postData,true);
$name=$my_obj['name'];
$age=$my_obj['age'];
$localtion=$my_obj['location'];
You could do that with AJAX.
You need a script, which will give javascript vars to the PHP Script, like:
var PHPFile = 'PHPFile.php?arg1=' + arg1 + '&arg2=' + arg2;
In the "PHPFile.php" you can access them by
$arg1 = $_GET["arg1"];
$arg2 = $_GET["arg2"];
Or you could do that with jquery $.ajax-> data, too.
You can access them by
$arg1 = $_POST["arg1"];
$arg2 = $_POST["arg2"];
Something like that:
result = $.ajax({
type: 'POST',
async: false,
url: 'PHPFile.php',
data: ({
arg1: arg1,
arg2: arg2
})
}).responseText;
alert(result);
EDIT:
If you want to do that with a json-object, try this:
json_decode();
http://www.php.net/manual/en/function.json-decode.php
http://www.php.net/manual/en/function.json-encode.php

Categories

Resources