jquery.ajax to PHP fails when I use ECHO in my PHP - javascript

this is the 1st time I try to use AJAX - my website needs to call a PHP during runtime when the user leaves a specific form field (VIN). I pass the value of this field to a PHP function for validation and processing. Then PHP should return 3 values for 3 different form fields.
This is my problem: I won't get the 3 values back into my javascript.
Each time when I use ECHO json_encode in my php the AJAX call crashes and the console shows "VM7190:1 Uncaught SyntaxError: Unexpected token Y in JSON at position 0(…)".
If I put any other simple ECHO in my PHP the AJAX call would return with an error.
If I remove each ECHO from my PHP the AJAX call returns as success but the returning data is NULL.
It would be so great if I could get a solution for this problem here.
If anybody would like to test the site - this is the url: mycarbio
Thank you very much.
This is my AJAX call:
function decode_my_vin(myvin) {
alert("in decode_my_vin");
dataoneID = '123';
dataoneKEY = 'xyz';
jQuery.ajax(
{
cache: false,
type: 'POST',
url: '/wp-content/themes/Impreza-child/vin-decoder.php',
dataType:'json',
data: {
'value1_VIN': myvin,
'value2_ID': dataoneID,
'value3_KEY': dataoneKEY,
'value4_Year': ' ',
'value5_Make': ' ',
'value6_Model': ' '
},
// async: false,
success: function(response) {
var obj = jQuery.parseJSON(response);
alert("success returned: " + obj);
document.getElementById("fld_7290902_1").value = "2015";
document.getElementById("fld_1595243_1").value = "Ford";
document.getElementById("fld_7532728_1").value = "Focus";
return;
},
error: function() { alert("error in der jquery"); }
});
}
And this is my PHP
<?php
header('Content-Type: application/json');
$resultYear = '2010';
$resultMake = 'Ford';
$resultModel = 'Focus';
$vinResult = array("Year: ", $resultYear, "Make: ", $resultMake, "Model: ", $resultModel);
echo json_encode($vinResult);
?>

This may not be your only problem, but you should try using an associative array when rendering the JSON:
$vinResult = array(
'Year' => $resultYear,
'Make' => $resultMake,
'Model' => $resultModel
);
Currently you are combining your property names and values.

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

How to get data from json array in php via ajax get request?

I have 3 data in my database and I want my js to show all my data, But when I'm using json array, I get an error and my data doesn't show it all.
var confurl = "http://localhost:8080/servisppk/web_service.php";
$.ajax({
url : confurl,
type : 'GET',
dataType: 'json',
beforeSend : function() {
$.mobile.loading('show', {
text : 'please wait while retrieving data...',
textVisible : true
});
},
success : function(dataObject) {
var appendList = '<li><h2>' + dataObject.Nama + '</h2><p>' + dataObject.NIM + '</p><p><b>' + dataObject.Fakultas + '</b></P></li>';
$('#list-mhs').append(appendList);
$('#list-mhs').listview('refresh');
},
complete : function(){
$.mobile.loading('hide');
}
});
i'm using json array in my php:
$ms = array($mhs,$mhs2,$mhs3);
ECHO JSON_ENCODE($ms);
when i'm using it, it doesn't show my data at all, it just show that my data is undefined, but when I change it to only be able to read one data, the data can appear even if only one.
changed to this:
$ms = $mhs;
ECHO JSON_ENCODE($ms);
You need send header let browser known, like:
<?php
$data = ['test' => 'hello'];
header('Content-Type: application/json');
echo json_encode($data);

Separate values returned from AJAX

My ajax functions returns two values, and when I call "data" they are displayed as one.
Javascript
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'checkinfo.php',
data: { address: "37.187.139.123", port: "26618" },
dataType: 'html',
async: true,
success: function(data)
{
$("output").html(data);
}
});
});
PHP
<?php
$SERVER_IP = $_REQUEST['address'];
$SERVER_PORT = $_REQUEST['port'];
$QUERY_PORT = $_REQUEST['port'];
$HEADS = "3D";
$show_max = "unlimited";
$SHOW_FAVICON = "on";
$TITLE = "My fancy Serverpage";
$TITLE_BLOCK_ONE = "General Information";
$TITLE_BLOCK_TWO = "Players";
$ping = json_decode(file_get_contents('http://api.minetools.eu/ping/' . $SERVER_IP . '/' . $SERVER_PORT . ''), true);
$query = json_decode(file_get_contents('http://api.minetools.eu/query/' . $SERVER_IP . '/' . $QUERY_PORT . ''), true);
if(empty($ping['error'])) {
$version = $ping['version']['name'];
$online = $ping['players']['online'];
$max = $ping['players']['max'];
$motd = $ping['description'];
$favicon = $ping['favicon'];
}
if(empty($query['error'])) {
$playerlist = $query['Playerlist'];
}
echo $version;
echo $online;
?>
The output I get in the "output" element is" Version 1.80". Where as the $version variable is "Version 1.8" and the $online variable is "0". How do i separate these two values and assign them to two element different elements ex. output1 and output2.
Lastly, is there any better way to directly get the value from individual variables, rather than using echo for them all and collecting them as one "data".
You're dealing with a plain text/html response, which would need parsed. Also, the ajax function only returns one value. Anything echoed by the PHP script gets dumped into the ajax response.
You should change the dataType to json, and return the values as a json-encoded array:
die(json_encode(array(
'version' => $version,
'online' => $online
)));
This can be accessed in javascript as:
data.version
data.online
ProTip: If you're not sure what's being returned, check the Network tab of Chrome's developer tools (or Firebug or whatever). Console.log() can be used to dump the var to the console for inspection, and doing the following will allow you to manipulate it directly in the console:
success: function(response) {
console.log(resp=response);
/* open the console, and you can manipulate the var 'resp' */
}

Saving to DB works...but an error is thrown

Hello fellow programmers!
I'm fairly new to PHP/JavaScript and have to admit it is quite the learning experience, but I am enjoying it quite a bit. I have a bit of a problem when I'm saving to a Database using Ajax however. The save works perfectly fine, but instead of falling into my "success" code it falls into the "error" section and gives me a Status of 200. I'm not sure what the status 200 means and am confused because it does actually save to the Database correctly. Eventually what I want to do is use a JavaScript function to updated fields (when successfully saving to the DB), but right now I'm just trying to display a message to the user. Also, in the JavaScript code I have to have the single quotes (') around the ajax variables (i.e. url, type, dataType, etc.) for it to work. I've tried adding the single quotes around success and error and their associated functions to no avail. Thanks!
Javascript:
function SaveUserBlankAnswer(form) {
if (form.Answer.value != "") {
var answer = form.Answer.value;
var contentID = form.ContentID.value;
var userID = form.UserID.value;
$.ajax({
'url': 'Database/SaveUserBlankAnswer_db.php',
'type': 'POST',
'dataType': 'json',
'data': { ContentID: contentID, UserID: userID, Answer: answer },
success: function(){
alert('BOOSH!');
},
error: function(data){
alert(data.status);
}
});
}
}
PHP:
<?php
session_start();
include("DBConnection.php");
$duplicateCheck = "SELECT UserID FROM BlankAnswer WHERE ContentID = " . $_POST[ContentID] . " AND UserID = " . $_POST[UserID];
if ($duplicateResult = $mysqli->query($duplicateCheck)) {
$rowCount = $duplicateResult->num_rows;
if ($rowCount == 0) {
$SQL = "INSERT INTO BlankAnswer (UserID, ContentID, Answer)
VALUES('$_POST[UserID]', '$_POST[ContentID]', '$_POST[Answer]');";
} else {
$SQL = "UPDATE BlankAnswer SET Answer = '" . $_POST[Answer] . "' WHERE ContentID = '" . $_POST[ContentID] . "' AND UserID = '" . $_POST[UserID] . "'";
}
$mysqli->query($SQL);
}
$mysqli->close();
?>
Use Jquery serialize method to create the form data for submission as you are not escaping the data on directly passing it.
Return 1 on success and 0 in failure from PHP script. No data is bad. Your POST request has no response, so maybe it thinks as an error. and the error in callback is for AJAX error. You can pass 0 or any message on DB level error.
function SaveUserBlankAnswer(form) {
//do validations here
var formData = $('#formId').serialize();
$.ajax({
type: "post",
url: "Database/SaveUserBlankAnswer_db.php",
dataType:"json",
data: formData,
success: function (data) {
if(data.status === "1") {
//Show success
} else if(data.status === "0") {
// alert for error on saving to DB
}
},
error: function(error){
alert('AJAX ERROR');
}
});
}
Hope it helps
Happy Coding !!!

send multidimensional array to php using ajax as json and receive html text to show in a div

First part is completed, The data is successfully sent to php using ajax as json (I did it by following an answer to an already posted question on this site).
Now how to access these values in php, and after using the string in abc[2] as sql query and printing the result in php(second page) using html in a table format (in second page), how to receive that response after ajax call completes in first page to show it in a div in first page.
Actually I am not asking about the procedure of running query and displaying values.
I am facing problem in accessing these array values in php and displaying them back in first page using ajax.
whenever I return some value from first page (using echo or print function), I receive an alert about syntax error: unexpected tocken after the ajax call comes back from second page. The code in first page is
var abc= {};
abc[0] = {};
abc[0]['name'] = 'first col';
abc[0]['width'] = 123;
abc[1] = {};
abc[1]['name'] = 'second col';
abc[1]['width'] = 456;
abc[2]="abcdefghijklmnopqrstuvwxyz";
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(data)
{
alert(data);
}
});
I don't know exactly...
you can try this one..
$param = cleanAll();
You can do it in this way :
Send parameter to your query.php file using ajax.
In query.php file write logic to process on posted data save/edit/fetch data from/to DB
and create html to print in div and echo that html
Inside your ajax call when success put that html to div which is returned from query.php.
Here are few changes on your ajax code:
Array will like this
var abc= {abc :[{name:'first col',width:123},{name:'second col',width:456},{name:"abcdefghijklmnopqrstuvwxyz",width:456}] };
Ajax will like this
$.ajax(
{
type: "POST",
url: "query.php",
data: abc,
dataType: "json",
beforeSend:function()
{
// Do something before sending request to server
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
},
success: function(my_html)
{
$('#my_div').val(my_html);
}
});
Code is not tested but it should work.
As I understand from my recent experiment, array will be placed to object before converting to JSON. Below my code:
JavaScript:
...
var read_numbers = new Array();
...
function read_ajax_done(num, num_in_word){
rec_count_in_cache = rec_count_in_cache + 1;
var number = {"num" : "", "word" : ""}; // Object type
number.num = num;
number.word = num_in_word;
read_numbers[rec_count_in_cache-1] = number; // Array is multidimensional
}
function save_to_db(read_numbers) {
var object_read_numbers = {"read_numbers" : read_numbers}; // Array placed to object
JSON_read_numbers = JSON.stringify(object_read_numbers); // Object converted to JSON
request = $.ajax({
type : "POST",
url : "post.php",
data : {read_numbers : JSON_read_numbers}
});
request.done(function(msg) {
alert("Respond: "+ msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
}
PHP:
if (isset($_POST["read_numbers"])) {
$read_numbers = json_decode($_POST["read_numbers"], TRUE);
.....
$response = $read_numbers["read_numbers"][n]["word"];
}
echo $response;
Second Page PHP
<?php
//need for displaying them back to the $.ajax caller
header('Content-type: application/json');
//accessing data
$post = $_POST['abc'];
/*
* how to access multid array
* $post[0]['name'] = 'first col'
* $post[0]['width'] = 123
* $post[1][name] = 'second col'
* $post[2] = 'abcdefghijklmnopqrstuvwxyz'
*/
//now to pass them back to your $.ajax caller
echo json_encode($post);
?>
First Page
$.ajax(
{
type: "POST",
url: "query.php",
data: {abc: abc},
dataType: "json",
success: function(data)
{
//prints your response variable
console.log(data);
}
});

Categories

Resources