Return Named Array in Ajax Request - javascript

I am trying to pass back an array with named indexes (e. g.: data.sugg_id) for a post request. This is how my javascript / jQuery looks like:
$.post('submit_text.php', JSON.stringify({'unit_id' : unit_id,
'text' : text,
'ignore_warnings' : ignore_warnings
}),
function(data) {
sugg_id = data.sugg_id;
if (data.status == 'failure') {
warning_history = {}
showMessage(errorBox, data.message);
warnBox.fadeOut("fast");
}
My submit_text.php looks like:
<?
header("Content-Type: application/json");
$unit_id = $_POST["unit_id"];
$text = $_POST["text"];
$ignore_warnings = $_POST["ignore_warnings"];
$sugg_id = 24;
//$status = "success";
$status = $text;
$message = "";
$data = array("sugg_id" => $sugg_id, "status" => $status, "message" => $message);
echo json_encode($data);
?>
I tried to use alert(data.status) but it said "undefined". What am I doing wrong?

As suggested by #A. Wolff pass dataType
$.post('submit_text.php', JSON.stringify({'unit_id' : unit_id,
'text' : text,
'ignore_warnings' : ignore_warnings
}),
function(data) {
sugg_id = data.sugg_id;
if (data.status == 'failure') {
warning_history = {}
showMessage(errorBox, data.message);
warnBox.fadeOut("fast");
}
}, "json");

Related

Ajax jQuery on success if statement double json_encode return underfined value

I trying to get $comments_id,$comments_timestamp, $user_firstname, $user_lastname values and pass back to ajax, but in the if statement was execute only one object array which is ['successful-submit-comment'] = true;.
Ajax
$.ajax({
type:'post',
url:'getcomment_detail.php',
data:{comment_id: comment_id,user_desc:user_desc},
cache:false,
dataType:'json',
success: function (data){
console.log(data);
var ttes1 = data.comments_timestamp;
alert(ttes1);
}
});
getcomment_detail.php :
$u_id = $_SESSION['u_id'];
$submit_comment_status = array();
if($sql = "INSERT INTO comments (post_id, user_id, user_desc) VALUES ('$comment_id','$u_id','$user_desc')"){
mysqli_query($conn,$sql);
mysqli_close($conn);
$get_comment_user_detail = "SELECT comments.id, comments.timestamp, user.firstname, user.lastname FROM comments INNER JOIN user ON user.id = comments.user_id WHERE user.id = $u_id ORDER BY comments.id DESC LIMIT 1";
if($stmt = $conn->prepare($get_comment_user_detail)) {
$stmt->execute();
$stmt->bind_result($comments_id, $comments_timestamp, $user_firstname, $user_lastname);
while ($stmt->fetch()) {
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
}
$stmt->close();
}
$submit_comment_status['successful-submit-comment'] = true;
header('Content-Type: application/json');
echo json_encode($submit_comment_status);
}
Console return value:
Alert return value:
Undefined
Why don't you just put it into the array and return it all as a json file?
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname,
'successful-submit-comment' => true
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
and in your ajax you just get the value like
console.log(data['successful-submit-comment']);

Laravel "MethodNotAllowedHttpException in RouteCollection.php line 219"

I'm just wondering right now why this particular table I am interacting with the database returns an error like the above subject where in fact I am just using the same mechanism from other table. I am refering to my table "Inventory". My store method just simply returns an error stated in the subject above and I have checked all the parameters in controller and in my model and it seems there is no error. Can somebody help me spot the error here. Please help. Here are my codes.
InventoryController.php
public function store( Request $request ){
$prod_ids = $request['product_ids'];
$purchase_order_ids = $request['purchase_order_ids'];
$purchase_ids = $request['purchase_ids'];
$quantity = $request['purchaseQuantity'];
for($i = 0; $i < count($prod_ids); $i++){
Inventory::create([
'product_id' => $prod_ids[$i],
'purchase_order_id' => $purchase_order_ids[$i],
'purchase_id' => $purchase_ids[$i],
'quantity' => $quantity[$i]
]);
}
return json_encode(array('notify' => "Success"));
}
My model => Inventory.php
<?php
namespace App\Inventory;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
protected $fillable =
['product_id','purchase_order_id','purchase_id','quantity'];
}
My Javascript:
$("#purchase_toInventoryID").click(function(e){
e.preventDefault();
var array_prodID = <?php echo json_encode(isset($array_prodID) ? $array_prodID : 0); ?>;
var array_poID = <?php echo json_encode(isset($array_poID) ? $array_poID : 0); ?>;
var array_purchaseID = <?php echo json_encode(isset($array_purchaseID) ? $array_purchaseID : 0); ?>;
var array_purchaseQuantity = <?php echo json_encode(isset($array_purchaseQuantity) ? $array_purchaseQuantity : 0); ?>;
$.post("{{ url('saveToInventory') }}", {
'product_ids': array_prodID,
'purchase_order_ids': array_poID,
'purchase_ids':array_purchaseID,
'purchaseQuantity': array_purchaseQuantity
}, function(data){
if(data.notify == "Success"){
console.log(data.notify);
}else{
console.log(data.notify);
}
}, 'json');
});
My routes.php
Route::post('saveToInventory', 'Inventory\InventoryController#store');

echo select options according to AJAX call

ive been trying this for the whole day and cant get my head around it. Im retrieving a count from an ajax call called quote.pdfnum which tells me the number of pdfs generated per user. I want to echo quote.pdfnum (number) of options. Im trying to echo in the select at the last table column.
setInterval(function(){
$.ajax({
url: 'poll_requests.php',
type: 'POST',
data: {data:currRequests},
dataType: 'json',
// dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
})
.done(function(response, textStatus, jqXHR) {
// console.log("new Requests "+response.new_quotes);
// console.log("all requests "+response.all_quotes);
var oldRequests = currRequests;
currRequests = response.all_quotes;
var newRequests= response.new_quotes;
if(oldRequests!=currRequests){
if(activeTab!='requests_tab' && newRequests.length>0 && pollRequests>1){
var spanText=Number($('#rbadge').text())+newRequests.length;
$('#rbadge').text(spanText);
}
if(newRequests.length==0 && oldRequests.length==1){
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
$("#rtable tr:first").after("<tr><td colspan='8'>No pending requests at the moment...</td></tr>");
}
if(newRequests.length>0 && oldRequests.length==1){
//and old requests are 0 (-1) remove the first row "no requests at the moment"
$('#rtable tr').not(function(){if ($(this).has('th').length){return true}}).remove();
}
for (var i = 0; i < newRequests.length; i++) {
quote = newRequests[i];
if (activeTab!='requests_tab' && pollRequests>1) {
noty({text: quote.company+' requested a new quote'});
};
// $("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a><a class='approve' href='approve.php?id="+quote.id+"'>Approve</a></td> </tr>");
$("#rtable tr:first").after("<tr><td>"+quote.id+"</td><td>"+quote.user+"</td><td>"+quote.country+"</td><td>"+quote.insured+"</td><td>"+quote.status+"</td><td>"+quote.date+"</td><td>"+quote.time+"</td><td><a id='pdf' href='"+quote.pdf+"' target='_blank'></a><a id='edit' href='edit.php?id="+quote.id+"'></a></td><td><select name='pdfs' id='pdfs'></select></td> </tr>");
};
}
// console.log('requests length '+newRequests.length);
pollRequests++;
})
.fail(function(error) {
console.log("error"+ error.responseText);
})
.always(function() {
// alert("complete");
});
// },1000000);
},2000);
And this is my poll_requests.php page.
<?php
header('Content-Type: application/json');
$data = $_POST['data'] ;
$new_quotes = array();
$files = array();
$all_quotes = array();
require_once('db_connect.php');
$sql = $db->prepare("SELECT * FROM users, quotes WHERE users.id = quotes.user_id and quotes.status = 'req' ORDER BY quotes.rdate ASC");
if($sql->execute()){
while ($row = $sql->fetch(PDO::FETCH_ASSOC)) {
$files[] = $row;
}
}
foreach ($files as $file):
$quote_id = $file['quote_id'];
$all_quotes[] = $quote_id;
if(!in_array($quote_id, $data)):
$date_time=explode(' ',$file['qdate']);
$insured=$file['insured'];
$status = $file['status'];
$user_id = $file['id'];
$username= $file['username'];
$country = $file['country'];
$company = $file['company'];
$pdfcount = $file['pdfnum'];
$pdf_path="all/$quote_id/$quote_id.pdf";
$new_quotes[] = array('id' => $quote_id,
'user' => $username ,
'country' => $country,
'insured' => $insured,
'status' => $status,
'date' => $date_time[0],
'time' => substr($date_time[1],0,8),
'company' => $company,
'pdfcount' => $pdfcount,
'pdf' => $pdf_path);
endif;
endforeach;
$all_quotes[]=-1;
$data_to_send = array();
$data_to_send['new_quotes'] = $new_quotes;
$data_to_send['all_quotes'] = $all_quotes;
$json_to_send = json_encode($data_to_send);
echo $json_to_send;
?>

ajax when trying to access d[obj].src it return undefined

AJAX
function ajax_json_gallery(folder) {
alert(folder);
var thumbnailbox = $('#thumbnailbox');
$.ajax({
type: "POST",
url: "json_gallery_data.php",
contentType: "application/x-www-form-urlencoded",
dataType: "json",
data: "folder=" + folder,
success: function(d) {
for (var obj in d) {
if (d.hasOwnProperty(obj)) {
alert(d[obj]); //access data//
alert(d[obj].src); //undefined//
}
}
}
});
}
PHP
header('Content-Type: application/json');
$folder = "Img/Company1/Jersey1";
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$directoryfiles[] = '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
echo json_encode($directoryfiles);
console.log(d)
[""img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },",
""img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },",
""img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },",
""img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" },"]
x3
i am using ajax to get all image inside the folder directory , and return to ajax but when i tried to access the d[o].src it return undefined ,i had no idea what am i missing here.
Don't try to write JSON text yourself. Just create an associative array or stdClass object, add the appropriate key/values, then add that to $directoryfiles. json_encode will then do the proper encoding
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$temp = new stdClass;
$temp->num = $i;
$temp->src = $src;
$temp->name = $file;
$directoryfiles["img".$i] = $temp;
}
}
closedir($dirHandle);
echo json_encode($directoryfile);
change the format of json to,
{"img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },
"img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },
"img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },
"img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" }};
then u use the code,
console.log(d.img1.src);

How can i add Dynamic Json data into a Mysql Database.

How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called
JSON_decode
I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?
Here is the data located:
http://csgo.nssgaming.com/api.php
The current script:
<?php
require_once ('simple_html_dom.php');
$html = #file_get_html('http://csgolounge.com/');
$output = array();
if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));
// Source: http://php.net/manual/en/function.strip-tags.php#86964
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE)
return preg_replace('#<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>#si', '', $text);
else
return preg_replace('#<('. implode('|', $tags) .')\b.*?>.*?</\1>#si', '', $text);
} elseif($invert == FALSE) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
return $text;
}
foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
$additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;
$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;
foreach($match->find('.teamtext') as $key => $team) {
$output[$id]["teams"][$key] = array(
"name" => $team->find('b')[0]->plaintext,
"percent" => $team->find('i')[0]->plaintext
);
if(#$team->parent()->find('img')[0])
$result = array("status" => "won", "team" => $key);
}
if($additional)
$result = $additional;
if(isset($result))
$output[$id]["result"] = $result;
}
echo json_encode($output);

Categories