can't pass php array to jquery - javascript

Not able to pass PHP encoded array to js.
index.php
echo '<script src="script.js"></script>';
$a=array(1,2,3,4,5);
echo json_encode($a);
?>
script.js:
$.ajax({
method: 'GET',
url: 'index.php',
dataType: 'json',
success: function (Data) {
alert("Success!" + Data);
},
error: function (Data) {
alert("Wrong");
}
});
I always got message - "Wrong".

You have not pass html tags in your json value generated from php
echo '<script src="script.js"></script>';
simply delete the code above. also, you have to parse your JSON string after your function is succssed, :
function (data) {
JSON.parse(data).forEach(function (x) {
alert(x);
});
}

use post method i think It work
method: 'POST',

Related

Ajax - How to use a returned array in a success function this codes

I use web services, i try this code. i want to select and show my php page , select 1.string or 2.string
ajax.php
$bb=json_decode($result,true);
$a= strlen($bb[$user_id]['1']);
if ($a!=0)
{
$this->data[$bb];
echo "<br>User ID===> ".$bb[$user_id]['1'];
echo "<br>name===> ".$bb[$user_id]['2'];
echo "<br>surname===> ".$bb[$user_id]['3'];
echo "<br>etc..===> ".$bb[$user_id]['4'];
}
x.php Js codes
$.ajax({
type:'post',
data:{user:user,user_id:user_id},
url:'<?php echo site_url('ajax/hello');?>',
success: function(result){
$('#htmlname').html(result);
}
});
});
});
Return the array as JSON. To do this, set the dataType to JSON in your ajax call: dataType: "json"
You can then access each element of the array in the success callback:
success: function (result) {
var item1 = result[0];
var item3 = result[2];
}

Passing javascript array through ajax with php

I have an array that is created in my ajax php file that looks like this
[[1,2,3],[1,2,3]]
So I echo it with a json_encode
echo json_encode($array);
This is my ajax code
$.ajax(
{
url: "ajaxfile.php" + "?something=" + something + "&something2=" + something2 + "&something3=" + something3,
type: "POST",
data: JSON,
success: function (data) {
object = data;
functionIwantthearraytobepassedto();
}
}
)
In the console all I get is
Notice: Array to string conversion in
ajaxfile.php on line
78 "[Array]"
Where am I going wrong? And how can I fix it?
Please try to add a header:
header('Content-Type:text/json');
echo json_encode($array);
Try adding to your ajax
dataType: 'json'
and
cotentType: 'application/json; charset=utf-8'

Submit form for php without refreshing page

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!
The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}
Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});
PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

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

What is the proper or best way to get data from ajax?

I have this javascript code with ajax.
$('#btnCart').click(function() {
var pName = document.getElementById('prodName').value;
$.ajax({
url: 'index.php',
data: 'prdName='+pName,
success: function(data) {
$('#prod').html(data);
}
});
});
I want to get the value of pName to be returned on my php. Here's my code on my index.php side:
<?php
$prodName = $_GET['prdName'];
echo $prodName;
?>
But it returns Unidentified index: prdName.
How can I get the value from ajax to my php? Please help...
if(isset($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo $prodName;
}
You should send the data as:
data: {prdName: pName},
add this to your PHP code:
if(!empty($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo cartTable($prodName);
}
also some corrections in js:
$('#btnCart').click(function() {
var pName = $('#prodName').val();
$.ajax({
url: 'index.php',
data: {prdName:pName},
success: function(data) {
$('#prod').html(data);
}
});
});
In index.php Get the prdName value from $_POST[] global array.
to send data to index.php file add type type:'POST' in ajax code
$.ajax({
type:'POST',
url: 'index.php',
data: {'prdName': pName},
success: function(data) {
$('#prod').html(data);
}
});
or you can use $.post() method in jQuery
$.post(
'index.php',
{'prdName='+pName},
function(data) {
$('#prod').html(data);
}
});
in index.php
if(isset($_POST['prdName']){
$prodName = $_POST['prdName'];
echo $prodName;
}

Categories