First off sorry if I'm missing something simple just started working with AJAX today. I have an issue where I'm trying to get information from my database, but different records have different amounts of values. For instance, each record has a "features" column. In the features column I store a string. (ex: Feature1~Feature2~Feature3~Feature4... ) When I'm building the object I take apart the string and store all the features into an array. Some objects can have 1 feature others can have up to whatever. So... how do I return this values back to my ajax function from my php page? Below is my ajax function that I was trying and I'll provide a link with my php file. [ next.php : http://pastebin.com/SY74jV7X ]
$("a#next").click(function()
{
$.ajax({
type : 'POST',
url : 'next.php',
dataType : 'json',
data : { nextID : $("a#next").attr("rel") },
success : function ( data ) {
var lastID = $("a#next").attr("rel");
var originID = $("a#next").attr("rev");
if(lastID == 1)
{
lastID = originID;
}
else
{
lastID--;
}
$("img#spotlight").attr("src",data.spotlightimage);
$("div#showcase h1").text(data.title);
$("div#showcase h2").text(data.subtitle);
$("div#showcase p").text(data.description);
$("a#next").attr("rel", lastID);
for(var i=0; i < data.size; i++)
{
$("ul#features").append("<li>").text(data.feature+i).append("</li>");
}
/*
for(var j=1; j < data.picsize; j++)
{
$("div.thumbnails ul").append("<li>").text(data.image+j).append("</li>");
}
*/
},
error : function ( XMLHttpRequest, textStatus, errorThrown) {
$("div#showcase h1").text("An error has occured: " + errorThrown);
}
});
});
First replace the below in your next.php file:
for ( $i=0; $i < $arraySize; $i++ )
{
$return['feature'.$i.''] = $features[0];
}
With:
$return['features'] = $features;
P.S: the current code is wrong you should have ... = $features[$i]; anyway, you don't need that just send the array as is. and then in the JS part replace:
for(var i=0; i < data.size; i++)
{
$("ul#features").append("<li>").text(data.feature+i).append("</li>");
}
With:
$.each(data.features, function(k,v){
var li = '<li>' + v + '</li>';
$("ul#features").append(li);
});
This way, don't need the data.size anymore.
Related
PHP:
header('Content-Type: application/json');
//Some code
$files_arr['BadIMG'][$i] = $fileName;
//Some code
$files_arr['GoodIMG'][$i] = $path;
//Some code
echo json_encode($files_arr);
JS:
success: function(response) {
console.log(response.BadIMG);
console.log(response.GoodIMG);
for (var i = 0; i < response.GoodIMG.length; i++) {
var src = response.GoodIMG[i];
$('#fast-reply_textarea').focus().val($('#fast-reply_textarea').val() + '\n[img]https://url/' + src + '[/img]\n');
}
}
If from PHP received only GoodIMG, all it`t ok and in #fast-reply_textarea successfully added links for images:
console.log(response.BadIMG);
undefined
console.log(response.GoodIMG);
Array [ "1_Good.jpg", "2_Good.jpg" ]
But if from PHP received GoodIMG + BadIMG nothing inserted in #fast-reply_textarea:
console.log(response.BadIMG);
Array [ "1_Bad.jpg", "2_Bad.jpg" ]
console.log(response.GoodIMG);
Object { 2: "1_Good.jpg", 3: "2_Good.jpg" }
And if from PHP received onlly BadIMG:
console.log(response.BadIMG);
Array [ "1_Bad.jpg", "2_Bad.jpg" ]
console.log(response.GoodIMG);
undefined //With error:
Uncaught TypeError: can't access property "length", response.GoodIMG is undefined
How to parse this data if received BadIMG together with GoodIMG and add GoodIMG links in editor?
For BadIMG I will add alert, like as: From (Count all images) images (Count or Names of BadIMG) not uploaded.
You could remove the $i index in your arrays in PHP.
$files_arr['BadIMG'][] = $fileName;
$files_arr['GoodIMG'][] = $path;
In this case, both will be arrays, not objects.
Also, in JS, you should test if the variables are defined or not.
success: function(response) {
if (typeof response.GoodIMG !== "undefined") {
for (var i = 0; i < response.GoodIMG.length; i++) {
var src = response.GoodIMG[i];
$('#fast-reply_textarea').focus().val($('#fast-reply_textarea').val() + '\n[img]https://url/' + src + '[/img]\n');
}
}
}
I'm new in Laravel and Ajax, and I have working code (see below).
I have 2 tables, criteria and rating.
I want to query first the table named:criteria like (select * from criteria where level = 1),
then using the result, I want to save multiple rows in "ratings" using some field of query result + some input variable from user.
Like this:
for (i = 0; i < criteria-result.length; i++) {
$addItem= New Rating;
$addItem->empname = $request->empname; //this is from user this is a repeating value
$addItem->criteria = criteria-result[i].(criteria)
}
Existing Ajax:
$.ajax({
type: 'POST',
url: 'generate-rating-criteria',
data: {
'employee_name': $("#emp_name").text(),
},
success: function()
{
swal("Saved", "Ok", "success")
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
Existing Controller:
$addItem= New Rating;
$addItem->employee_name = $request->employee_name;
$addItem->save();
You can just use a count() method instead of length.
$criteria = DB::table('criteria')->where('level', 1)->get();
for ($i = 0; $i < count($criteria); $i++) {
$addItem= New Rating;
$addItem->empname = $request->empname;
$addItem->criteria = $criteria[$i]->criteria; /* if criteria column exist in the rating table. */
$addItem->save();
}
I'm trying to get dates from my database and put them in an array where it would be stored in json.
MAIN.PHP
$('#datepicker').focus(function(){
$.ajax({
url: 'getDates.php',
data: "artist_name="+$('#name').html(),
dataType: 'json',
success: function(data)
{
}
});
})
getDates.php
$fullname = $_GET['artist_name'];
$result = mysql_query("SELECT .... FROM .... WHERE ... ='$fullname'")
$arraydates = array();
while($details = mysql_fetch_assoc($result)) {
array_push($arraydates, $details['event_date']);
}
echo json_encode($arraydates);
I've managed to put all the dates from the selected artist in the "arraydates".
I found this on google:
var unavailableDates = ["21-8-2013"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
That's fine. But now I'm trying to get the results from the array (within getDates.php) and use them in the "main.php". So basically I want to use the data like above with "unavailableDates" array. (and thus, disable the specific dates within the jquery date picker).
Instead of having "unavailableDates", I have the "arraydates". I don't really know how can I use my array inside the "unavailable" function.
I'm not really good with json, actually it's my first time I used json. So could anyone please help me with that?
you can use jquery:
//...
success: function(data){
var arrayLength=data.length;
for(var i=0;i<arrayLength;i++){
if(unavailable(data[i]){
//your code here
}
}
}
//...
The ajax will return $arraydates in a JSON format. Use parse.JSON(returned value)
for example
success: function(data)
{
var unavailableDates = parse.JSON(data);
//Your code ....
}
Hope that helped.
I am working on extjs 4 project. In this project I have to communicate back and fourth between js and php files. So to call php from js, I am using Ext.Ajax.request.
var dirs = [];
Ext.Ajax.request(
{
url: 'text.php',
method: 'GET',
success: function(response)
{
dirs = JSON.parse(response.responseText);
},
failure: function(response)
{
alert('server-side failure with status code ' + response.status);
}
});
// Creating dropdown list menu
document.write("<select class='select'>");
for (var i = 0; i < dirs.length; i++)
{
document.write("<option>" + dirs[i] + "</option>");
}
document.write("</select>");
php code is the following:
<?php
$filepath = "scenarios";
$dirs = array();
$files = array();
$scenes = array_diff(scandir($filepath), array('..', '.'));
for ($i = 2; $i < count($scenes)+2; $i++)
{
if (strpos($scenes[$i], '.'))
{
array_push($files, $scenes[$i]);
}
else
{
array_push($dirs, $scenes[$i]);
}
}
if (count($dirs) > 0)
{
echo json_encode($dirs);
}
else
{
echo json_encode("You do nat have any projects. Please create new project.");
}
?>
Now the problem appears in the part where I want to generate list menu from the resulting dirs object. In the firebug DOM dirs = ["google","yahoo"], but in the loop, dirs.length returns 0???
Also when I put alert(dirs.length) before the for loop, it shows 0, then correctly generates the list menu...weird????
The request call is asynchronous which means, that after calling Ext.Ajax.Request, the next instruction is your loop. But you haven't received the data from the server yet. You need to put the loop in the success callback to make sure that you'll execute it after getting the data from the server.
var dirs = [];
Ext.Ajax.request(
{
url: 'text.php',
method: 'GET',
success: function(response)
{
dirs = JSON.parse(response.responseText);
// Creating dropdown list menu
document.write("<select class='select'>");
for (var i = 0; i < dirs.length; i++)
{
document.write("<option>" + dirs[i] + "</option>");
}
document.write("</select>");
},
failure: function(response)
{
alert('server-side failure with status code ' + response.status);
}
});
Also when I put alert(dirs.length) before the for loop, it shows 0,
then correctly generates the list menu...weird????
This is because the alert stop the execution flow of your program until you click on "ok". The data are probably coming from the server during this time, and the dir variable is populated with them.
I can't see any headers being sent out - which is required by most browsers:
header('content-type: application/json; charset=utf8;');
if(sizeof($dirs) > 0){
echo json_encode(array('success' => true, 'data' => $dirs));
}
else {
echo json_encode(array('success' => false, 'error' => 'You do not have any projects.' ));
}
The JavaScript:
var xhr = new Ext.data.Connection();
xhr.request({
url: '/text.php',
method: 'GET',
headers: {'Accept':'application/json'},
success: function(response, opts) {
var obj=Ext.decode(response.responseText);
var html='';
Ext.each(obj.data, function(v,i){html+='<option>'+v+'</option>';});
html='<select>'+html+'</select>';
console.info(html);
}
});
The HTML generation has to reside in the callback function - else it makes no sense at all.
Without having seen the JSON which is being returned - it's hard to tell what's wrong with it.
Down-voting without leaving a comment why exactly is really lame.
Turning off asynchronous requests in jQuery fixed the issue.
I have the following Javascript & AJAX request (using jQuery) in my page:
"use strict";
var hsArea, counter, hotspots, count;
counter = 4;
count = 0;
hotspots = {};
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
});
}
function displayHotspot(type, id, number) {
$.ajax({
url: '/alpha/engine/hotspots/gethotspot.php',
dataType: 'json',
data: {'type' : type, 'id' : id},
success: function(json) {
console.log(json);
var hotspot, extract;
extract = json.content;
extract = extract.replace(/<(?:.|\n)*?>/gm, '');
extract = extract.substring(0, 97);
extract = extract + "...";
json.content = extract;
hotspot = document.createElement("div");
hsArea.append(hotspot);
hotspot.setAttribute('class','hotspot');
hotspot.setAttribute('id','hotspot' + number);
$(hotspot).css('position', 'absolute');
$(hotspot).css('top', number * 100 + 100);
$(hotspot).css('left', number * 100 + 110);
hotspot.innerHTML = "<h1>"+ json.title + "</h1><p>" + json.content + "</p>";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
}
});
}
function listHotspots() {
for(count = 0; count < counter; count++) {
(function(count) {
displayHotspot('scribble',hotspots[count], count);
count = count + 1;
})(count);
}
}
function loadHotspots() {
fetchHotspotList();
listHotspots();
}
$(document).ready(function() {
hsArea = $("#hotspotArea");
fetchHotspotList();
listHotspots();
});
(Sorry the formatting is a bit off!) - Now, the $(document).ready() function assigns the hsArea variable as it should, however, a combination of fetchHotspotList() and listHotspots() returns:
Uncaught TypeError: Cannot call method 'replace' of null
However, if in the Google Chrome Javascript console, I run:
loadHotspots();
it fetches the data from the AJAX request and displays it properly on the page. At first I thought the problem was that I Wasn't using the $(document).ready() handler, but adding it hasn't fixed it. Neither has using an onload handler inside of the body tag.
Any help would be greatly appreciated.
Regards,
Ben.
It's probably due to the fact that your listHotSpots function is called before fetchHotSpots returns (since it's an async call).
You're better off chaining the execution of listHotSpots to the completion of fetchHotSpots, like so:
function fetchHotspotList() {
$.getJSON ('/alpha/engine/hotspots/gethotspot.php', {'type' : 'list'}, function(json) {
hotspots = json;
listHotSpots();
});
}
You may be better off modifying listHotSpots to take the json data returned from your AJAX call. Hope this helps!