Getting php with js with ajax - javascript

It won't give me the value from $scoresArray in php to data_response in js
If I log (obj) it returns nothing.
I have this in JS
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) {
stageRef.$("txtTopscorePunt").html(obj.score[0]);
stageRef.$("txtTopscorePunt2").html(obj.score[1]);
stageRef.$("txtTopscorePunt3").html(obj.score[2]);
}
});
This in php:
function GetScores(){
$query = "SELECT * FROM topscores ORDER BY Scores DESC LIMIT 3";
$result = mysql_query($query);
$scoresArray = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$scoresArray[$i]['score'] = $row['score'];
$i++;
}
echo json_encode($scoresArray);
}

You don't need to JSON.parse(str) with dataType:json -- it's already parsed.
In addition, your selectors are wrong. If you want to select an ID, you need the # character.
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (obj) { // not 'complete'
console.log(obj);
$("#txtTopscorePunt").html(obj.score[0]);
$("#txtTopscorePunt2").html(obj.score[1]);
$("#txtTopscorePunt3").html(obj.score[2]);
}
});
http://api.jquery.com/jQuery.ajax/

update the code to this:
$.ajax({
url: "Database.php",
type: "POST",
dataType: "json",
success: function (data_response) {
console.log(data_response);
var response = data_response;
var response_str = JSON.stringify(response);
alert(response_str); // don't do this if the returned is too much
console.log(response_str); // use your browser console to view the results
}
});
Once you have done this, can you post the results of alert or console log.
Also, in the results does it start with "[" or "{"?
From the results we should be able to help you with the correct way to access your JSON object.
Regards.

Related

submit form to check something with ajax and jquery

I am making a form to check a security code. In fact, I am new to ajax and jquery, so I tried what I can, but my code doesn't work. Can anybody help me?
php file :
<?php
include('/includes/db-connect.php');
if( isset($_POST["seccode"]) ){
$result=mysqli_query($con,"SELECT * FROM `certificate_acheived_tbl` WHERE `cert_check_code` = ".$seccode.")";
if( mysql_num_rows($result) == 1) {
echo "<script>alert('s')";
}
}
?>
js file:
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: 'certcode='+ ID,
success: function() {
$('#someHiddenDiv').show();
console.log();
}
});
});
});
your code is bad... (sometimes mine too)
One first mistake : data: 'certcode='+ ID, in jQuery
and isset($_POST["seccode"]) in PHP 'certcode' != 'seccode'
so a better code.. ?
jQuery (I allways use JSON, it's more easy)
$(function () {
$(".btn btn-success").click(function() {
var
Call_Args = {
certcode: $(this).attr('id')
};
$.ajax({
url: 'cert-check-ajax.php',
type: 'POST',
data: Call_Args,
cache: false,
dataType: 'json',
success: function (data) {
console.log( data.acceptCod ); // or data['acceptCod'] if you want
$('#someHiddenDiv').show();
// ...
}
}); //$.ajax
}); // btn btn-success").click
});
PHP (with utf8 insurance, and good header / JSON encode response )
<?php
mb_internal_encoding("UTF-8");
include('/includes/db-connect.php');
$T_Repons['acceptCod'] = "bad";
if (isSet($_POST['certcode'])) {
$sql = "SELECT * FROM `certificate_acheived_tbl` ";
$sql .= "WHERE `cert_check_code` = ".$_POST['certcode'].")";
$result = mysqli_query($con, $sql);
$T_Repons['acceptCod'] = (mysql_num_rows($result) == 1) ? "ok" : "bad";
}
header('Content-type: application/json');
echo json_encode($T_Repons);
exit(0);
?>
you can use it
$(function() {
$(".btn btn-success").click(function() {
var ID = $(this).attr('id');
$.ajax({
type: "POST",
url: "cert-check-ajax.php",
data: {'seccode': ID}
}).done(function(data) {
$('#someHiddenDiv').show();
console.log(data);
});
});
});

AJAX does what I need it to do, but errors still occur

I am writing a web page which reads data from an html table to be used on a MySQL query using PHP. This is a continuation of this question. I got AJAX send the data I need to use on to the PHP file with the code to update the information it sent. However, two errors have occured.
I get a message saying Error:Error: jQuery21405680291895882033_1487801210725 was not called
The data I send has a ":1" at the end of it, giving me an error.
How can I fix these two mistakes? Thank you so much!
JS code:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
if($(this).find("textarea").length){
var costo = $(this).find('textarea').val();
arrayItem[headers[index]] = costo;
}else{
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
actualizarCostos(array);
}
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: false,
jsonpCallback: jsonCallback,
cache: true,
data:{ "table_data": JSON.stringify(array[i])},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
},
traditional: true
});
}
}else{
alert("Input must be array");
}
}
function jsonCallback(data, status){
console.log(data + " " + status);
}
PHP portion:
//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
conectar();
$array = json_decode($json, true);
echo "<script>console.log('$array');</script>";
$costo = $array["Costo"];
$sku = $array["SKU"];
$instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";
return ejecutarInstruccion($instruccion);
}
if(isset($_GET['table_data'])){
foreach($_GET['table_data'] as $index => $item)
{
// do something here
echo "<script>console.log('$item');</script>";
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
Edit:
I forgot to mention that I have tried changing 'jsonp' as 'json' on this code but I get an error saying the PHP file doesn't allow foreign data, even though I tried using header('Access-Control-Allow-Origin: *') on said file.
Your page is returning JSON, not JSONP. They aren't interchangeable. Remove the jsonp and jsonpCallback properties from the $.ajax() call, and change dataType to json:
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
data: {
table_data: JSON.stringify(array[i])
},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status" + status + " \nError:" + err);
},
traditional: true
});
I'd suggest you have the following AJAX:
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
}
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{ "table_data": JSON.stringify(array)},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
}
});
}else{
alert("Input must be array");
}
}
Then do the For-Loop on the PHP side of the server. Maybe each variable in array has a hidden parameter to know its own index, or JSON is doing something strange like displaying the number of elements in the array (in this case 1 because you're iterating over each one)

Need Help In Script

My script code like :
function changePrice(id) {
var url = '<?php echo $base_url ?>home/getprice/';
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
success: function(msg) {
alert(msg);
/*
"regular_price": "800",
"discount_price": 720
*/
}
});
}
I want to both regular price and discount price on separate variable.How??
If you are getting the response as "regular_price": "800", "discount_price": 720 then make it valid JSON, parse it and get the properties.
var obj = JSON.parse('{' + msg + '}');
// valid json -^-----------^-
// get object properties
var regular = data.regular_price;
var discount = data.discount_price;
UPDATE : If response data is valid JSON format then set dataType: 'json' option.
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
// set response datatype as json
dataType:'json',
success: function(msg) {
// get properties
var regular = msg.regular_price;
var discount = msg.discount_price;
}
});
Or parse it directly if the response is a string.
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
success: function(msg) {
// parse the string
var data = JSON.parse(msg);
// get properties
var regular = data.regular_price;
var discount = data.discount_price;
}
});
Thanx to all..Here are the solution :
<script>
function changePrice(id)
{
var url = '<?php echo $base_url ?>home/getprice/';
$.ajax({
url:url,
type:'post',
data:'id='+id,
dataType:'json',
success:function(msg)
{
var regular = msg.regular_price;
var discount = msg.discount_price;
}
});
}
</script>
My Function :
$new = array (
"regular_price" => $result->price,
"discount_price" => $price
);
$newarray = json_encode($new, JSON_PRETTY_PRINT);
print_r($newarray);
Try this:
In server side ajax call:
$respose['regular_price'] = 120;
$respose['discount_price'] = 100;
echo json_encode($response);
In JS: Considering msg is an json object
var data = JSON.parse(msg);
var regular = data.regular_price;
var discount = data.discount_price;

ajax and javascript drilldown script addition

I have a make/model/engine search form, the user selects the make which then populates the model, the user selects the model and it populates the engine. The problem I have encountered is that several of the manufacturers (make) use the exact same model. The script I have chooses the engine based on the model only. I would like to modify the script so it chooses the engine based on the make AND model, this would resolve my problem. I am somewhat familiar with javascript but I am no expert, I see the ajax requests in the aircraftMakeModel.php file but do not know how to add the make to the query. I have included the three files used below. Any help is appreciated in advance.
Thanks
Tom
aircraftMakeModel.php
<script type="text/javascript">
$(document).ready(function()
{
$('#aircraftMake').change(function()
{
var make=$(this).val();
var dataString = 'make='+ make;
$.ajax
({
type: "POST",
url: "include/getAirFrame.php",
data: dataString,
cache: false,
success: function(html)
{
$('#aircraftModel').html(html);
}
});
});
});
$(document).ready(function()
{
$('#aircraftModel').change(function()
{
var model=$(this).val();
var dataString = 'model='+ model;
$.ajax
({
type: "POST",
url: "include/getEngine.php",
data: dataString,
cache: false,
success: function(html)
{
$('#engineModel').html(html);
}
});
});
});
</script>
getAirFrame.php
<?php
include "../connection.php";
$q = $_POST['make'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`aircraftModel`) FROM `aircraftData` WHERE `aircraftMake` = '$q' ORDER BY aircraftModel ; ");
echo '<option value="0">Aircraft Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
getEngine.php
<?php
include "../connection.php";
$q = $_POST['model'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`engineModel`) FROM `aircraftData` WHERE `aircraftModel` = '$q' ORDER BY engineModel");
echo '<option value="0">Engine Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
If you want to send the make and model on the ajax call to get the engine something like this should work. Make the call to get the model as you do, then also add the make to the ajax request data to get the engine.
Note: not sure if this is a typo $('#marke')
$(document).ready(function(){
$('#marke').change(function() {
//make id
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "include/getph.php",
data: dataString,
cache: false,
success: function(html) {
$('#model').html(html);
}
});
});
});
$(document).ready(function() {
$('#model').change(function(){
//make id
var id = $('#marke option:selected').val();
//model id
var id1=$(this).val();
var dataString = 'id1='+ id1 + '&id=' + id;
$.ajax({
type: "POST",
url: "include/getph2.php",
data: dataString,
cache: false,
success: function(html) {
$('#engine').html(html);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Passing array and other data through ajax

This is my javascript function....
But my php controller getting all values but not the array not sure why ? Need help.....
Thanks in advance :)
function submitForm(){
var id = $('#id').val();
var supplier_id = $('#supplier_id').val();
var description = $('#description').val();
var numofpro = $('#numofpro').val();
var product_id = new Array();
for(var i=0;i<numofpro;i++){
product_id[i] = $('#product_id'+(i+1)).val();
}
var payment_mode = $('#payment_mode').val();
//description = description.replace(new RegExp('\r?\n','g'), '<br />');
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase", //The url where the server req would we made.
data: "id="+id+"&supplier_id="+supplier_id+"&description="+description+"&product_id="+product_id+"&payment_mode="+payment_mode,
dataType: "html", //Return data type (what we expect).
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
}
because you pass a string, not an array :) try it:
$.ajax({
url: "<?= base_url(); ?>edit/save_purchase",
type: "POST"
data: {id : id, supplier_id : supplier_id, description : description, product_id : product_id, payment_mode : payment_mode},
dataType: "json",
beforeSend:function(){
//alert("asds");
},
success: function(data) {
//alert("Edited");
alert(data);
}
});
in you php use :
$arr = json_decode($_POST);
//some php code
//some $result;
// if $result arr then
echo json_encode($result);
// else
echo json_encode(array('data' => $result))
hope this helps...
You need to first turn that array into a string in JS. Before sending it, do this:
JSON.stringify(product_id);
Once you receive it in PHP, you need to decode it.
$decoded = json_decode($_POST['product_id'])

Categories

Resources