passing javascript array to php via jquery AJAX - javascript

I am having problems passing my javascript array to a php file. i know that the JS array has the correct users input data because I have tested this by using toString() and printing the array on my web page. My plan was to use send the JS array to my php script using AJAX's but I am new to using AJAX's so there is a good chance I am doing something wrong. I have look through a good lot of different posts of people having this same problem but everything i have tried has not worked so far. All I know at this point is the JS has data in the array fine but when I try to pass it to the php file via AJAX's the php script dose not receive it. i know this because I keep getting undefined variable errors. To be fully honest I'm not to sure if the problem in how I'm trying to pass the array to the php script or if it how I'm trying to request and assign the array values to variables on the php side. At the moment my code is as follows:
My Javascript:
function createAsset(str, str, str, str, str, str, str, str, str)
{
var aID = assetID.value;
var aName = assetName.value;
var pPrice = purchasedPrice.value;
var pDate = purchasedDate.value;
var supp = supplier.value;
var cValue = currentValue.value;
var aOwner = actualOwner.value;
var wEdate = warrantyExpiryDate.value;
var dDate = destroyedDate.value;
//document.write(aID);
//var dataObject = new Array()
//dataObject[0] = aID;
//dataObject[1] = aName;
//dataObject[2] = pPrice;
//dataObject[3] = pDate;
//dataObject[4] = supp;
//dataObject[5] = cValue;
//dataObject[6] = aOwner;
//dataObject[7] = wEdate;
//dataObject[8] = dDate;
//dataObject.toString();
//document.getElementById("demo").innerHTML = dataObject;
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
$.ajax
({
type: "POST",
url: "create_asset_v1.0.php",
data: dataObject,
cache: false,
success: function()
{
alert("OK");
location.reload(true);
//window.location = 'create_asset_v1.0.php';
}
});
}
My PHP:
<?php
// Get Create form values and assign them to local variables.
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
// Connect to the SQL server.
$server='PC028\ZIRCONASSETS'; //serverName\instanceName
$connectinfo=array("Database"=>"zirconAssetsDB");
$conn=sqlsrv_connect($server,$connectinfo);
if($conn)
{
echo "Connection established.<br/><br/>";
}
else
{
echo "Connection couldn't be established.<br/><br/>";
die(print_r( sqlsrv_errors(), true));
}
// Query the database to INSERT record.
$sql = "INSERT INTO dbo.inHouseAssets
(Asset_ID, Asset_Name, Perchased_Price, Date_Perchased, Supplier, Current_Value, Actual_Owner,Worranty_Expiry_Date, Destroyed_Date)
VALUES
(?, ?, ?, ?, ?, ?, ?, ?, ?)";
$params = array($assetID, $assetName, $purchasedPrice, $purchasedDate, $supplier, $currentValue, $actualOwner, $warrantyExpiryDate, $destroyedDate);
// Do not send query database if one or more field have no value.
if($assetID && $assetName && $purchasedPrice && $purchasedDate && $supplier && $currentValue && $actualOwner && $warrantyExpiryDate && $destroyedDate != '')
{
$result = sqlsrv_query( $conn, $sql, $params);
// Check if query was executed with no errors.
if( $result === false )
{
// If errors occurred print out SQL console data.
if( ($errors = sqlsrv_errors() ) != null)
{
foreach( $errors as $error )
{
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br/>";
echo "code: ".$error[ 'code']."<br/>";
echo "message: ".$error[ 'message']."<br/>";
}
}
}
else
{
echo "Record Created!<br/>";
}
}
// Close server connection
sqlsrv_close( $conn );
if($conn)
{
echo "<br/>Connection still established.";
}
else
{
echo "<br/>Connection closed.";
}?>
Just as extra info if its not obvious from my code I am trying to send user data from a html form to a php script that process it and uses it to query a MSSQL database. This function that I am working on now is the create database entry function.

You need to match the keys you send through AJAX:
var dataObject = { assitID: aID,
assitName: aName,
purchasedPrice: pPrice,
purchasedDate: pDate,
supplier: supp,
currentValue: cValue,
actualOwner: aOwner,
warrantyExpiryDate: wEdate,
destroyedDate: dDate };
with the POST array keys:
$assetID = $_POST['aID'];
$assetName = $_POST['aName'];
$purchasedPrice = $_POST['pPrice'];
$purchasedDate = $_POST['pDate'];
$supplier = $_POST['supp'];
$currentValue = $_POST['cValue'];
$actualOwner = $_POST['aOwner'];
$warrantyExpiryDate = $_POST['wEdate'];
$destroyedDate = $_POST['dDate'];
Your code should look like this:
$assetID = $_POST['assitID'];
$assetName = $_POST['assitName'];
$purchasedPrice = $_POST['purchasedPrice'];
...

You are reading the wrong keys.
$assetID = $_POST['aID'];
Must be:
$assetID = $_POST['assitID'];
As per your sent object.

Related

Get json from sql using XMLHttpRequest

I have a json string in my sql database.
get_survey_results.php
<?php
// including some cfg & functions
include_once("config.php");
include_once("funcs.php");
// setting connection and getting user id
$con = setConnection();
$hash = $_COOKIE['hash'];
$query = "SELECT user_id FROM `users` WHERE hash='$hash' LIMIT 1";
$result = mysqli_query($con, $query);
$data = $result->fetch_assoc();
$id = -1;
if (sizeof($data) > 0) {
$id = $data['user_id'];
}
// if user id is exist get jsonstring from database
if ($id > 0) {
$q = "SELECT results FROM `survey_results` WHERE user_id='$id' LIMIT 1";
$r = mysqli_query($con, $q);
$d = $r->fetch_assoc();
echo json_decode($d['results']); // !!!
// PS $d['results'] exist, it is a json string
// tried also echo $d['results'] but get no result
}
else {
// otherwise get false, false is getting ok in responce, but not results above
echo "false";
}
closeConnection($con);
?>
I want to return it in JS using XMLHttpRequest:
var json
var data = new FormData()
// AJAX CALL
var xhr = new XMLHttpRequest()
xhr.open('POST', "php/get_survey_results.php", true)
xhr.onload = function(){
var jsonString = this.response
console.log("JSON STRING IS")
console.log(jsonString) // !!! returns empty
};
But it returns nothing in case user exist, otherwise returns false. I marked problem places as !!!

Ajax call is getting a 200 but I'm not inserting a record after function call

This is a bit of a mystery but I think I've narrowed down part of the issue.
Basically, I have a form and when I hit submit I'm making an ajax post that hits my route then controller and this calls a function elsewhere that does an insert (via a procedure in DB2, but basically a straight insert)
My Ajax returns a 200 ok message and shows the form data in the dev tools, so that part is ok. The goal is to take the form values along with the values that I've hard coded in the controller, and pass them to the function which prepares the statement and executes.
I think the issue is the fact that everything coming from the form is a string but my function is expecting int and string plus the procedure will only insert successfully if the right data type is used. I think the issue is in the form data because if I do a rough hard code and call the function manually in a test file like this, it inserts:
$id = 123;
$name1 = 'Test Name';
$number1 = 112;
$name1 = '2nd Test Name';
$number2 = 584;
$number3 = 88;
$name3 = 'Name Blue';
$category = 'Fruit';
$comment = 'Testing the comments';
$date1 = '2018-09-18';
$date2 = '2018-09-19';
So basically, I need to still pass my form data, and take that as well as the other values from the controller, make sure strings pass as strings and INT passes as int, then execute the function. I've got to be missing something pretty simple here but I'm 100% lost right now.
Any help is much appreciated
Route.php
Route::post('insertPList', 'Controller#insertPList');
controller.php
public function insertPList(Request $request)
{
$id = 123;
$name1 = $request->name1;
$number1 = $request->number1;
$name2 = $request->name2;
$number2 = $request->number2;
$number3 = $request->number3;
$name3 = $request->name3;
$category = 'Fruit';
$comment = $request->comment;
$date1 = '2018-09-10';
$date2 = '2018-09-11';
$service = new service();
$service->insertListRecord($id, $name1, $number1,$name2, $number2, $number3, $name3, $category, $comment, $date1, $date2);
}
Service.php
public function insertListRecord(int $id, string $name1, int $number1, string $name2, int $number2, int $number3, string $name3, string $category, string $comment, string $date1, string $date2)
{
$link = Iseries::conn();
$sql = "CALL INSERT_LIST(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$prep = odbc_prepare($link, $sql);
$exec = odbc_execute($prep, array($id, $name1, $number1, $name2, $number2, $number3, $name3, $category, $comment, $date1, $date2));
if (odbc_error())
{
echo odbc_errormsg($link);
}
}
blade.php
$("#save").click(function(e){
e.preventDefault();
var name1 = $("input[name=name1]").val();
var number1 = $("input[name=number1]").val();
var name2 = $("input[name=name2]").val();
var number2 = $("input[name=number2]").val();
var number3 = $("input[name=number3]").val();
var name3 = $("input[name=name3]").val();
var comment = $("textarea[name=comment]").val();
$.ajax({
url:'URL',
data:{
name1:name1,
number1:number1,
name2:name2,
number2:number2,
number3:number3,
name3:name3,
comment:comment
},
"_token": "{{ csrf_token() }}",
type:"POST",
success:function(data){
console.log(data);
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
From your explanation, if the issue you are having is a type format issue (string, integer, boolean) and you are using the laravel framework then add some thing like this to your model.
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'number1' => 'integer',
'name1' => 'string',
'column name' => 'expected or required format of data',
];
Hopefully this should cast the data to your required format before inserting to data base. See also

Separating PHP variables in JSON string

I'm kinda lost in how to fix a problem of mine. I've got a little code on PHP that's passing data(errors, page(id, name, title etc) trough an array and that array has been set with parseJSON. If I alert the response I will get an array with the correct value. But my problem is, that the response is always different hence it are PHP variables that change.
I've tried something like responseText.pageid or responseText.error[1], but that can't work because it can be different. And I don't know if I need to call it responseText.pageid because in the array it's $pageid or something different...
So alerting responseText is giving me a good result, but separating it won't unfortunately work.
My JS code:
// Variables
var content_page = $('#content-page').val();
var content_url = 'action=chose&page='+content_page;
/* Starting AJAX post form */
$.ajax({
type: 'POST',
dataType: "JSON",
url: 'handlers/content.handler.php',
data: content_url,
success: function(responseText)
{
var obj = $.parseJSON(responseText);
console.dir(obj.error);
if(obj.error[1] > -1)
{
noty({ text: 'U hebt geen pagina gekozen!' });
}
else if(obj.error[2] > -1)
{
noty({ text: 'De gekozen pagina bestaat niet!' });
}
else if(obj.error[100] > -1)
{
noty({ text: 'Uw pagina wordt opgehaald...' });
}
}
});
return false;
});
My PHP code:
// Storing the variables.
$stringPage = trim($_POST['page']);
$error = array();
$bolean = false;
// Prepared statement.
$stmt = $mysqli->prepare('SELECT id,name,title,text FROM pages WHERE name = ?');
$stmt->bind_param('s', $stringPage);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($pageID, $pageName, $pageTitle, $pageText);
$stmt->fetch();
$intPage = $stmt->num_rows();
$stmt->close();
# Controle
if(empty($stringPage))
{
$error[] = 1;
$bolean = false;
}
if($intPage == 0)
{
$error[] = 2;
$bolean = true;
}
if($bolean == false)
{
$error[] = 100;
}
header('Content-Type: application/json');
$aVariables = array('error' => $error, 'id' => $pageID, 'name' => $pageName, 'title' => $pageTitle, 'text' => $pageText);
echo json_encode($aVariables, JSON_FORCE_OBJECT);
I've Googled and came to the conclusion that I need to make a variable out of the parseJSON but then I get no result unfortunately. My current result(http://prntscr.com/72c39h) is working but separating it with responseText.home isn't working.
Thank you in advance, and my apologies for the bad grammar and language!
There is no need to var obj = $.parseJSON(responseText);, this responseText is already in json format. If you want to access error then just refer it by simply responseText.error or 'alert(responseText.error);' and there is also no need to set header('Content-Type: application/json');
When calling JQuery's parseJSON() you have to both call it properly, e.g. $.parseJSON(), and store it in a variable, e.g. var obj = $.parseJSON(responseText);, as per the documentation.

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'];

Running loop from javascript to save in Mysql

Hello i am currently running a javascript on my php page (below) and it comes out with each data that i need is there any way i can connect this through to mysql database? (i am new to javascript)
<script>
var allItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
for(var i = 0; i < allItems.length; i++) {
var item = allItems[i];
console.log('Current item: %o', item);
}
</script>
'itemsArray comes from a save function'
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {};
var num = document.getElementById("num").value;
newItem[num] = {
"methv": document.getElementById("methv").value
,'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));
});
Thanks
PS I already have the connection for the database setup
Post your data with ajax/json request to a php function and do all database related work with php. Next return successful or failure status which will be catch in this called js function, and then you can display the success or failure message with javascript.
Example:
Include jQuery library:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Script for ajax request with jQuery:
var path = 'http:/your_url/your_php_script_file.php';
var data = 'json_data=' + JSON.stringify(newItem[num]);
$.ajax({
url: path,
type: "POST",
data: data,
cache: false,
success: function ($returm_msg){
alert($returm_msg);
}
});
PHP for save/update in database:
$receive_value = json_decode($_POST['json_data'], true));
You will get values like
$receive_value['methv'],$receive_value['q1'],....,$receive_value['comm'];
Now do save operation in database.
$result = mysql_query("INSERT INTO .....") or die(mysql_error());
if($result){
return "Success!"; // if not function then simply echo "Success!";
}else{
return "Failure!"; // if not function then simply echo "Failure!";
}
Helpful links:
http://www.bennadel.com/resources/presentations/jquery/demo21/index.htm
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

Categories