New to Web development and multiple scripting languages and how they mesh together...
I'm looking to return the entire SQL table (or a subset of it) from PHP and iterate through the values in JS and can't quite get it to work any help is appreciated.
In PHP encoding the array like this.
//get SQL data
$return_arr[] = array("id" => $id, "otherinfo" => $otherinfo);
echo json_encode($return_arr);
The ajax code I have looks like this but is where I'm getting tripped up...
jQuery.ajax({
type: "POST",
url: 'example.php',
type: 'POST',
data: { i: i },
dataType: "json",
success: function(response)
{
for(var i=0; i<response.length; i++)
{
var info = response[i].otherinfo;
var title = document.createElement("div");
var titletext = document.createTextNode(titledb);
title.appendChild(info);
}
}
)}
Thanks
I think its a syntax mistake.
jQuery.ajax({
url: 'example.php',
type: 'POST',
data: { i: '' },
dataType: "json",
success: function(response)
{
// code here
}
}) // <--- here
Related
I got problem when parsing JSON from my AJAX. This is my error and the data that I want to parse
This my code:
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
data: { kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust:
codeCustomer },
success: function(result) {
if(result) {
console.log(result);
obj = $.parseJSON(result);
}
My controller
public function get_produk_by_eancode() {
$eancode = $this->input->post('kodePilihan');
$kodeScala = $this->input->post('kodeScala');
$codecust = $this->input->post('codecust');
$barangPilihan = $this->web_ordering_model->get_produk_by_eancode_page3($eancode, $kodeScala, $codecust)->row_array();
echo json_encode($barangPilihan);
}
My result data from the controller or you can see in picture
{"SC01132":"*1038 AR BRU KM","SC01002":"BOX-50 dengan Roda","SC01011":"A-19","brand":"Kiramas","verpacking":12,"List1":"76250.00000000","SC01001":"625050","Free":".00","LastTglProduksi":"1900-01-01 00:00:00.000","PricelistName":"Netto"}
You get this error because what you give to parseJSON is not a string.
First try to add content-type to you AJAX call :
contentType: "application/json; charset=utf-8",
dataType: "json",
Also you can convert your object to a string.
var url = "<?php echo base_url(); ?>home/get_produk_by_eancode";
$.ajax({
type: "POST",
url: url,
dataType: "json", //changes
data: ({ kodePilihan: kodeBarangPilihan, kodeScala: kodeScala, codecust: codeCustomer }),
success: function(result) {
if(result) {
console.log(result);
var obj = JSON.parse(result); //changes
console.log(obj); //changes
}
}
Solved by this code
$.trim()
Sorry for my long report, thanks.
Because I get undefined. Where I am failing?
Code:
function add(id,cost){
var info = {
"id" : id,
"cost": cost,
};
$.ajax({
data: info,
url: 'a.php',
type: 'post',
success: function (datos) {
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
});
}
archive a.php
PHP:
$cost=$_POST['id']*$_POST['cost'] + 137;
echo json_encode(array("r1" =>$_POST['id'], "r2" => $cost));
Why do you think $.ajax will understand datos as a JSON? You need to specify it, you can do it using several ways.
Parsing it
success: function (datos) {
datos = JSON.parse(datos);
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
Specifying in $.ajax itself
$.ajax({
data: info,
url: 'a.php',
type: 'post',
dataType:"json",
....
Setting header in PHP (doesn't work for < IE8)
header('Content-Type: application/json');
I would suggest you to use a combination of first one and third one. Lets not leave any stone unturned.
Datos is probably a string
You can do:
datos = JSON.parse( datos );
Or, you can set the return type to JSON:
$.ajax({
data: info,
dataType: 'json',
url: 'a.php',
type: 'post',
success: function (datos) {
alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
}
});
I have a PHP function where I pass a variable to and it returns an array containing a start date and end date.
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return $date;
}
?>
I am also trying to use this PHP function in an AJAX call so I can reuse the code. I have added this to the beginning of the page:
if (isset($_POST['dateFunction'])) {
print_r(dateRangeTimeFrame($_POST['dateFunction']));
}
My jQuery code is as follows:
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response['startDate']);
console.log(response.startDate);
}
});
My issue is that I do not know how to access the response that the php function is returning.
Here is the response I am getting from the PHP function:
Array
(
[startDate] => 2015/01/17
[endDate] => 2015/02/16
)
How would I go about getting these 2 vars from the PHP response?
You need to use JSON. Your Javascript natively understands and can parse it
if (isset($_POST['dateFunction'])) {
echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}
And your jQuery (note I added dataType)
$.ajax({
url: 'includes/functions.php',
dataType: 'json',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return json_encode($date);
}
?>
jQuery
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
dataType: "json",
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1) {
// ...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
echo json_encode($date);
}
?>
Ajax
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate },
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i].startDate);
}
}
});
Hi I am completely new to jQuery and also not the strongest with Javascript so I would appreciate some input on modifying this AJAX request to jQuery.
var test = new Array();
var bindThis = {
url: "sampleHandler.data",
method: "post",
}
mimetype: "text/json",
content: test
};
var request1 = dojo.io.bind(bindThis);
dojo.event.connect(request1, "load", this, "ResultsFunction");
My guest is this but I am not 100% sure I have the syntax correct.
var test = new Array();
var bindThis = {
url: "sampleHandler.data",
type: "post",
}
dataType: "text/json",
data: test
};
As for the dojo event handler I haven't been able to find a great resource on how to bind the request. My guest is something along these
lines?
$(this).load(function(){"ResultsFunction"})
How am I making out? Thanks in advance.
EDIT: I forgot to add that this is an application that uses both Dojo and Prototype. I am trying to migrate the code to jQuery.
From the jQuery AJAX API
$.ajax({
type: 'POST',
url: 'sampleHandler.data',
data: data,
dataType: 'json',
success: function (result)
{
}
});
Alternatively
$.post("sampleHandler.data", data,
function(result) {
},
"json"
);
More info
If you are going to perform a POST operation, most likely you want to send data that needs to be serialized to a JSON format (if your server operation is expecting that type of data), here's an example:
var dataToSend = {'taco':'yum'};
$.ajax({
url:'/myurl/',
dataType:'json',
contentType: 'application/json',
data: JSON.stringify(dataToSend),
type: 'POST',
success: function(data){
// perform operation with the data you receive
alert('success! received: ' + data);
}
});
You can get more info if you visit: api.jquery.com
I have recently posted another question which straight away users pointed me in the right direction.
$.ajax({
type: 'POST',
url: './',
data: 'token=' + token + '&re=8',
cache: false,
timeout: 5000,
success: function(html) {
auth(html);
var JSON_array = eval(html);
alert(JSON_array[0].username);
}
});
this returns the data correctly but I want to perform a kind of 'foreach'. the array contains data about multiple incoming and outgoing Instant Messages. So if a user is talking to more than one person at a time i need to loop through. the array's structure is as follows.
Array(
[0] => Array
(
[username] => Emmalene
[contents] =>
<ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul>
<ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul>
)
)
Any help very much appreciated.
Well since you are using jQuery already you could use the each function:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000,
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
$('someelement').append(data.contents);
});
}
});
Instead of evaluating the HTML, you can even specify JSON as return type...
Iteration is easy when using $.each:
$.ajax({
type: "POST",
data: ...,
url: url,
dataType: "json",
success: function(data) {
$.each(data, function(i, item){
// do something with every item in data
// you can reference items in data via
// data.fieldName
});
}
});
But a for ... in loop isn't much harder:
$.ajax({
...,
dataType: "json",
success: function(data) {
var fields = data.fieldName;
var value;
for (value in fields) {
// do something with value
}
}
});
Just to clarify, As I've read many helpful hints and answers and only this one worked for me:
$.ajax({
type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, datatype: 'json',
success: function(html){
auth(html);
var JSON_array = eval(html);
$.each(JSON_array, function(index, data) {
var talk_to = JSON_array.username;
var contents_to_update = JSON_array.contents;
});
}
});
this which made work:
1) use of eval.
2) datatype: 'json'
3) use of jquery's $.each function