Here is my JavaScript:
$.ajax({
url: 'CheckColorPrice.php',
type: 'POST',
data: {
url: '<?php echo $LINK;?>',
ColorId: ColorNumber
},
dataType: 'json',
success: function (data) {
$('#LoadingImage').hide();
$("#PRICE").text("£ " + data["price"]);
}
});
Here is CheckColorPrice.php:
<?PHP
$url = $_POST['url'];
$ColorId = $_POST['ColorId'];
if(isset($_POST['url']))
{
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$DataVariants = $xpath->query('//span[#class="ImgButWrap"]/#data-variants')->item(0)->nodeValue;
$jsonStart = strpos($DataVariants, '[');
$jsonEnd = strrpos($DataVariants, ']');
$collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
$SellPrice = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
$SellPrice[0] = $size->ProdSizePrices->SellPrice;
}
$names = implode(',', $SizeNames);
$price = implode('', $SellPrice);
if($ColVarId == $ColorId){
$healthy2 = array('£',' ','Â');
$yummy2 = array('','','');
$price = str_replace($healthy2, $yummy2, $price);
$PRICE = $price;
echo "price: ", json_encode($PRICE), "\n";
}
}
}
?>
The result from CheckColorPrice.php is looking just like this:
price: "37.99"
Where is my mistake, why it is not receiving the response properly. I don't get it at all... Can you help me out ?
Thanks in advance!
You're not returning json. You're returning plain text which contains some json:
echo "price: ", json_encode($PRICE), "\n";
^^^^^^^^^^
That'd look like
price: "$9.99"
which is NOT valid json.
You need to return an array for your JS code to work:
echo json_encode(array('price' => $PRICE));
which would output:
{"price":"$9.99"}
Add the following header to your script:
header('Content-type: application/json');
header("Content-Disposition: inline; filename=ajax.json");
Also change the line
echo "price: ", json_encode($PRICE), "\n";
to
echo json_encode(array('price'=>$PRICE));
Hope that helps
First thing, in your ajax request, add this parameter :
dataType : 'json'
Then, your response is not a correct json.
You can return this :
echo json_encode(array("price"=>$PRICE));
Related
I want my response to be in JSON Object. But in some functions it comes as string and I want to parse it. How can I achieve this? This is my function.
function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
var METHOD = "POST";
var serverURL = 'http://istudy.com.pk/api/server.php'; //Path to Server.php
//var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
var DATA_TYPE = 'json';
var TIMEOUT = 20000;
console.log(requestDATA);
$$.ajax({
url: serverURL,
data: requestDATA,
dataType: DATA_TYPE,
type: METHOD,
timeout: TIMEOUT,
success: function(data){
successCallback(data, hideIndicator, showAlert);
},
error: function(a, b, c){
errorCallback(a, b, c, hideIndicator, showAlert);
}
});
}
And this is my responseText
responseText: "{"status":"success","message":"Your Order has Processed. Please Note this pin <b style=\"background-color:green;\">osIyKvAp<\/b> and send it to the admin with payment details."}"
THIS IS MY PHP FUNCTION
function confirm_order($id, $newarray, $cn) {
$today = date('y-m-d');
$expiry = date('Y-m-d', strtotime("+30 days"));
$total_items = 0;
$total_price = 0;
foreach ($newarray as $key => $val) {
$total_items++;
foreach ($val as $doc) {
$total_price = $total_price + $doc->doc_price;
}
}
$pin = random_string('alnum', 8);
$sql = "INSERT INTO orders (order_id, order_UserId, order_total_items, order_amount, date_created,order_status,order_pin)
VALUES ('', '" . $id . "', '" . $total_items . "', '" . $total_price . "', '" . $today . "','0','" . $pin . "')";
if (mysqli_query($cn, $sql)) {
$order_id = mysqli_insert_id($cn);
foreach ($newarray as $key => $val) {
$total_docs = 0;
$total_items++;
$sep = '|';
$sub_price = 0;
$doc_list = '';
foreach ($val as $doc) {
$doc_list .= $doc->doc_id . $sep;
$sub_price = $sub_price + $doc->doc_price;
$total_docs++;
$sep = '|';
}
$sql = "INSERT INTO cart_items (uc_id, uc_user_id, uc_course_id, uc_course_docs_id, uc_course_docs_num,uc_price,uc_order_num,uc_order_status,uc_dateBuy,uc_dateExpire)
VALUES ('', '" . $id . "', '" . $key . "', '" . $doc_list . "', '" . $total_docs . "','" . $sub_price . "','" . $order_id . "','0','" . $today . "','" . $expiry . "')";
mysqli_query($cn, $sql);
}
$response_array['status'] = 'success';
$response_array['message'] = 'Your Order has Processed. Please Note this pin <b style="background-color:green;">' . $pin . '</b> and send it to the admin with payment details.';
} else {
$response_array['status'] = 'error';
$response_array['message'] = 'An error occurred. Please try again later.';
}
echo json_encode($response_array);
}
Can I place any check to JSON.parse if and only if my response is string?
Add this in your success handler.
data = typeof data === 'string' ? data : JSON.parse(data);
"Can I place any check to JSON.parse if and only if my response is string?"
Yes, you can.
if (typeof (response) != 'object'){
response = JSON.parse(response);
}
You can use fairly simple javascript to do that:
if (typeof(data) == 'string') {
data = JSON.parse(data);
}
If you are curious as to why it might not automatically parse your JSON, here are a couple common reasons:
Invalid JSON (check with jsonlint.com)
Not getting an application/json content type when expecting JSON (as set in the dataType parameter.
See also: jQuery won't parse my JSON from AJAX query
Remove the DATA_TYPE = 'json'; and try again:
function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
var METHOD = "POST";
var serverURL = 'http://istudy.com.pk/api/server.php'; //Path to Server.php
//var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
var TIMEOUT = 20000;
console.log(requestDATA);
$$.ajax({
url: serverURL,
data: requestDATA,
type: METHOD,
timeout: TIMEOUT,
success: function(data){
try {
if(typeof(data)==='string') data=JSON.parse(data);
} catch(ex) { // bad json response
console.error(ex);
}
successCallback(data, hideIndicator, showAlert);
},
error: function(a, b, c){
errorCallback(a, b, c, hideIndicator, showAlert);
}
});
}
NOTE. This will not avoid the issue, but will let us to parse the response, while having a possibile bad response from the server i.e. a Content-Type that is not application/json. Some web server will accept both Content-Type:text/plain and Content-Type:application/json; headers, while returning in both cases a json formatted string rather than json object parsed by $.ajax (when finds the application/json as the Content-Type header value).
To achieve that, be sure in your php code to print out the right header
<?php
header('Content-Type: application/json`)
When I try to use the returned array data on view page, it prints undefined not array value. Please help me.
My controller is:
function test(){
$pro_id = $this->input->post('id',TRUE);
//echo $pro_id;
$cat_id = $this->input->post('cat',TRUE);
$date1 = $this->input->post('dt',TRUE);
$firstdate = date('Y-m-d', strtotime($date1));
$lastdate = strtotime(date("Y-m-d", strtotime($firstdate)) . " +6 day");
//echo $cat_id;
$data = array();
$this->load->model('inserttimemodel');
$whr = $this->inserttimemodel->gettime($pro_id,$cat_id,$firstdate,$lastdate);
$data['whr'] = $whr;
//print_r($data); //working properly
echo json_encode($data);
exit();
}
JS:
$(document).ready(function(){
$("#cat").change(function(){
var catid = $(this).val();
var id = $('#project option:selected').val();
var dt = $('#period option:selected').val();
$.ajax({
url:"<?php echo base_url();?>/timesheet/test",
data:{cat:catid,id:id,dt:dt},
type:"POST",
dataType: "json",
success:function(data){
document.getElementById("res").innerHTML = data[0];
document.getElementById("res1").innerHTML = data[1];
}
});
});
});
You need to decode "data" before using "JSON.parse" in Javascript.
Please help, I am trying to get the value of input field after ajax success, I don't know why is it always undefined?
ajax.js
$(document).on('click','.modify',function(){
var modId = $(this).attr('id');
var event_id = $(this).attr('class').split(' ')[1];
$.ajax({
cache: false,
url: '../ajax/paraphernalia/ajax_get_edit.php',
type: 'post',
data: { modId: modId, event_id: event_id},
success:function(data){
var mod_name = $(data).find('input#hidden_headerName').val();
alert(mod_name);
$('#display_modal_edit').html(data);
$('#judge_name_header').html(mod_name);
}
});
});
ajax_get_edit.php
session_start();
require ("../../global.php");
if (isset($_POST['modId']) && isset($_POST['event_id'])) {
$modId = $_POST['modId'];
$event_id = $_POST['event_id'];
$output = '';
$sql = mysql_query("SELECT * FROM tbl_judges WHERE judge_id = ".$modId." AND event_id = ".$event_id."");
$soc_sql = mysql_fetch_assoc($sql);
$output .= '<input type="text" value="GetThisvalue" id="hidden_headerName">';
$output .= '.....';//bunch of codes here
$output .= '</div>';
echo $output;
}
You can Return a JSON from PHP and Create the Divs you need/dont Need on the Client, further its also simpler if you just Need some values
I have a PHP/Ajax function that returns a list of countries with the given characters in a textbox. Ofcourse Ajax updates this list everytime the textbox gets edited.
Index.PHP calls all the other files, classes and HTML. But when the textbox gets updated, Ajax sends a POST variable to index.PHP because this is where the Search.PHP file with the class name SearchEngine gets called. But because he sends this to the index.php everything keeps getting reloaded and the HTML will be returned twice.
Index.php
<?php
require_once("cgi_bin/connection.php");
require_once("Database_Handler.Class.php");
require_once("HTML_Page.Class.php");
require_once("search.php");
$hostname_conn = "localhost";
$database_conn = "ajax";
$username_conn = "root";
$password_conn = "";
$db = new DatabaseHandler();
$conn = $db->openConnection($hostname_conn, $username_conn, $password_conn, $database_conn);
$IndexPage = new page();
echo $IndexPage->render();
$SearchEngine = new SearchEngine($conn);
?>
Please ignore the poor and unsecure database connection. I am currently transforming all my code to PDO and refining it but that is for later.
Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
And as final the Javascript
$(document).ready(function() {
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "index.php", //Referring to index.php because this is where the class SearchEngine is called
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
note: HTML is being returned from the "page" class called inside Index.php
How do i not let everything get called twice?
Thank you,
EDIT: A new file was suggested where i direct the ajax url to AutoComplete.php
AutoComplete.PHP
Please explain what should be in the file and why. I am clueless.
Basically, just add a parameter to your Ajax call to tell the index.php its being called by Ajax, and then wrap an if-statement around the two lines that print out your actual index page:
if(!isset($_REQUEST['calledByAjax']))
{
$IndexPage = new page();
echo $IndexPage->render();
}
and in your Ajax call:
data: { query: query_value, calledByAjax: 'true' },
Or make another php page, like ajaxsearch.php that's the same as your index.php but lacking those two lines, and call that in your Ajax call.
First thing (this is a sample, not tested yet)
autocomplete.php
<?php
$search_string = $_POST['query'];
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
}
echo($output);
?>
autocomplete.js
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "autocomplete.php", //Here change the script for a separated file
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").keyup(function() {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
} else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
search(); // call the function without setTimeout
}
});
});
Have luck :)
i got a problem when i try to use ajax in a php file, which calls to another php file.
Here is the code of the php file:
<script>
function obtenerProductos(cat) {
parametros = {"idCat": cat};
$.ajax({
data: parametros,
url: '/bin/getProductos.php',
type: 'post',
beforeSend: function() {
$(".prods > form").html("Procesando, espere por favor...");
},
success: function(respuesta) {
$(".prods > form").html(respuesta);
}
});
}
function obtenerProducto(prod) {
parametros2 = {"idProd": prod};
$.ajax({
data: parametros2,
url: '/bin/getProducto.php',
type: 'post',
beforeSend: function() {
lista = $(".cPreview").html() + "<br/> Añadiendo...";
$(".cPreview").html(lista);
},
success: function(respuesta) {
lista = $(".cPreview").html()+ respuesta.nombre + "\t" + respuesta.precio + "<br/>" ;
$(".cPreview").html(lista);
precio = parseFloat($(".precioT").html()) + respuesta.precio;
$(".precioT").html(precio);
}
});
}
</script>
In the first function of this script i call to the first PHP (getProductos.php) to get all the products of a category and receive a html which print in a form.
The second function calls to another php (getProducto.php) to get all the information of the selected product and print it in another div.
Here you have the PHP files named.
getProductos.php (This works)
<?php
include '../funciones.php';
$recibido = $_POST['idCat'];
echo obtenerProductosCategorias($recibido);
?>
getProducto.php (Dont Works)
<?php
include '../funciones.php';
$recibido = $_POST['idProd'];
echo obtenerProductos($recibido);
?>
And the 2 functions of this code:
function obtenerProductosCategorias($idCat) {
conectDB();
$string = "";
$sql = 'select * from Productos where id_categoria="' . $idCat . '";';
$resultado = mysql_query($sql);
while ($row = mysql_fetch_array($resultado)) {
$string = $string . "<input type='button' onclick='obtenerProducto(" . $row["id_producto"] . ");return false;' value='" . $row['nombre_producto'] . "' />";
}
return $string;
closeDB();
}
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}
I have alerts inside the PHP to check that everything is going fine but the second function doesnt enter in his PHP and it returns undefined undefined without show any alert of the PHP thats why i think that the second function have some problems to reach his PHP but the URL is correct and the file is located in the right place.
Thanks for reading and sorry for my English.
Try defining $resultado as an array prior to assigning anything too it. Not sure but in some configurations this does break PHP.
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
$resultado = array();
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}