AJAX POST request is failing - javascript

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}

You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.

If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.

You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

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;
?>

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);

how to loop all data on JSON

Hi I tried Looping my json_encode() to get all data that are related based on my query
the script is working fine but not the looping part
here's what I have so far:
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_GET['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_GET['name'];
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
echo json_encode($message_array);
}
}
It only returns one data from my database..
this is my javascript for retrieving from my php side:
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
You just keep overwriting $json_string with each loop iteration.
What you want to do is save your DB data to array then encode.
$array = array();
if(count($message_query) > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$array[] = $message_array;
}
}
$json_string = json_encode($array);
echo $json_string;
It also appears that in your AJAX success handler function, you are not properly iterating the array.
Notice here that you only call $.each() on the first array element of the returned result set:
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
I would think you would want to iterate the entire result set like this:
$.each(result, function(rowKey, row) {
// row is single row of result set from database
// rowKey is numerical index of the row in the result set
// rowKey is probably not useful here
// You can just append new div to #clog with
// whatever content from row which you desire
// for example, this would insert message_content value
// in child div to #clog
$("#clog").append('<div>' + row.message_content + '</div>');
});
Try This.....
$i=0;
$fet=mysql_query('select * from tbl1 WHERE tbl1.id='20');
while($row=mysql_fetch_assoc($fet,MYSQL_ASSOC)){
$json[$i]['date']=$row['time'];
$i++;
}
echo json_encode($json);
Please use ->rowCount() to count rows:
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
}
echo json_encode($json);
You should use an array to store your message_arrays, so that you're not just replacing the same variable over and over.

Categories