AJAX post php response - javascript

So i have this code that posts to a php file,
var values = {
'socketid': data.socketid,
'id': memberid.value
};
console.log(values);
$.ajax({
url: "continue.php",
type: "POST",
data: values,
});
but i am unsure how to get each seperate value from the php file continue.php, do i ruse $_REQUEST or something, im just not sure if i have to parse or anything, could i get an example on how i can do this

Since you are using POST method just:
$socketid = $_POST['socketid'];
$id = $_POST['id'];
$_REQUEST is to check both $_GET and $_POST at the same time but it is not necessay in your code

$_POST should work fine since your request is of type POST

Your continue.php will get values in the following way:
<?php
$socket_id=$_POST['socketid'];
id=$_POST['id'];
?>

For simple post use $.post() it's a shorthand for $.ajax() for POST request.
var values = {
'socketid': data.socketid,
'id': memberid.value
};
$.post('continue.php', values, function (response) {
var res = JSON.parse(response);
if (res.results == true) {
console.log('Data updated');
}else {
console.log('Data not updated');
}
})
In your PHP
<?php
$socket_id = $_POST['socketid'];
$id = $_POST['id'];
// here update your data/ use
// then send response to javascript
// echo json_encode(['results' => true]); for success
// echo json_encode(['results' => true]); for fail

Related

PHP array to JavaScript array using json_encode()

How do I pass an array from PHP to the JavaScript function console.log()? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.
JavaScript code:
$.ajax({
method:"POST",
url:'php.php',
data:"",
dataType:'json',
success:function(data){
var y1=data;
console.log(data.name);
}
});
PHP code:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//assign vars after formatting to avoid a wrong login with correct
//username and password
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer_array[] = $customer1;
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer_array[] = $customer2;
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
echo json_encode($customer_array);
}
I am just going to summarize my comments into an answer, first I would just turn off the json return for trouble shooting. You can parse the json after fact anyway:
$.ajax({
// Do "type" here
type:"POST",
url:'php.php',
// Send something to check in the script
// This is optional, but I like to do it...
data: {
"action":"get_name_city"
},
success:function(data){
// Do a try, just incase your parse fails
try {
// Parse the json here
var getJson = JSON.parse(data);
console.log(getJson);
console.log(data);
}
catch(Exception) {
// Show any errors that might get thrown
console.log(Exception.message);
}
}
});
PHP:
# Check the action is set and is named
if(isset($_POST["action"]) && $_POST["action"] == "get_name_city") {
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
$customer_array[] = $customer1;
$customer_array[] = $customer2;
$customer_array[] = $customer3;
# Just die here
die(json_encode($customer_array));
}
# Die with error so there is some feedback to your ajax
die(json_encode(array('error'=>'No data was sent.')));
As has been mentioned, there are multiple options for passing the data from PHP:
add the Content-Type header with value application/json before sending the return from json_encode() to echo():
header('Content-Type: application/json');
echo json_encode($customer_array);
Parse the return from the PHP using JSON.parse()
success:function(data){
var y1=data;
var data = JSON.parse(data);
So pick one of those approaches. One might argue that the first is more semantically correct, since JSON data is being sent.
Additionally, the success callback of the AJAX request is attempting to access the property name of the data returned. However, the data returned should be an array of objects, each which has a property name. One approach to logging the name of each property is to use Array.forEach() and send the name of each element in the array to console.log().
data.forEach(function(dataItem) {
console.log(dataItem.name);
});
See a demonstration of this in this phpfiddle.
You where almost there. Your AJAX requests accepts JSON but your PHP does not output JSON (it does but not in the correct way), you'll have to set the appropriate Content-Type header:
header('Content-Type: application/json');
echo json_encode($customer_array);
Your AJAX request should now be able to use the properly formatted JSON as the data variable (and console.log it).

How to make the ajax 'data' that come with 2 values to get each value separately?

<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}

Passing Javascript Variable to PHP File

I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!

PHP script not getting called from ajax function

this is a noob question.
my javascript function(part of knockout.js model that I have defined):
self.loadData = function(){
alert("loadData got called");
$.ajax({
url: 'database_connection.php',
dataType: 'json',
success: function(data){ //json string of records returned from server
alert('success from server call');
},
error: function(){
alert('error from server call');
}
});
};
Contents of database_connection.php:
<?php
echo "this is called";
$db = new MySqli('localhost', 'username', 'password', 'database');
$activities = $db->query("SELECT * FROM MainActivity");
$activities_r = array();
while($row = $activities->fetch_array()){
$val = $row['mActivityID'];
$act = $row['Name'];
$activities_r[] = array('val'=>$val, 'act' => $act);
}
echo json_encode($activities_r);
?>
The php is correct, coz if I directly access this file through browser, it correctly displays the result from database table.
However, when executed through the loadData function, I get two alerts:
1. "loadData is called"
2. "error from server call"
the first line of database_connection.php is not being executed since I cant see the result of echo, so that means the script is not getting called.
Am I using the ajax function wrongly?
Your AJAX request contains:
dataType: "json"
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function
Use the following code to ensure the reponse is JSON format.. (PHP vsersion)
header('Content-Type: application/json');
Note : empty response is also considered invalid JSON; you could return {} or null which validate as JSON
you need to add headers in php file, because your data type is json in ajax call.
header('Content-Type: application/json');
echo json_encode($activities_r);
You need to set the type of your request and may be remove dataType. Also in the success callback it was one extra bracket. Check it :
self.loadData = function(){
alert("loadData got called");
$.ajax({
url: 'database_connection.php',
type : 'GET',
// dataType: 'json',
sucess: function(data){ //json string of records returned from server
alert('success from server call');
},
error: function(){
alert('error from server call');
}
});
};

Values not being transfered from JS to php

I have a JS script of:
function addTasteingNote(userID,beerID)
{
//get values
var note = $('#note1').val();
var ajaxSettings = {
type: "POST",
url: "a.php",
data: "u="+userID+"&b="+beerID+"&n="+note,
success: function(data){
} ,
error: function(xhr, status, error) { alert("error: " + error); }
};
$.ajax(ajaxSettings);
return false;
}
and the php script to add to the db is:
<?php
error_log("starting code");
require_once('connect.inc.php');
$u = $_GET['uID'];
$b = $_GET['bID'];
$n = $_GET['n'];
//do some checks etc
$db = new myConnectDB();
error_log("Successfully created DB");
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ($u, '$b', '$n')";
error_log($query3);
$result = $db->query($query3);
?>
The problem is that the error log shows nothing being put into the query:
[01-Nov-2013 23:40:29] Successfully created DB
[01-Nov-2013 23:40:29] INSERT INTO x (userID,beerID,note) VALUES (, '', '')
I have put alerts in the success of the ajax call, so I know that values are being passed through...
You need to give data like
var ajaxSettings = {
type: "POST",
url: "a.php",
data: {u:userID,b:beerID,n:note},
success: function(data){
}
data wont be and Query string,And since you are posting the values through ajax you need to get them via POST only like
$u = $_POST['u'];
$b = $_POST['b'];
$n = $_POST['n'];
And your query should be like
$query3 = "INSERT INTO x (userID,beerID,note) VALUES ('".$u."', '".$b."', '".$n."')";
And Better to use escape strings with your POST variables to prevent from SQL injection.
You are using post method so, you need to get data using $_POST or $_REQUEST instead of $_GET
$u = $_REQUEST['u'];
$b = $_REQUEST['b'];
$n = $_REQUEST['n'];

Categories