I am trying to pass a JS object (associative array) that I create dynamically to a PHP / MySQLi query.
- When I write the JS object (transferData) to the console it appears as intended (see below).
- When I test the PHP / MySQLi query separately it works too.
- I therefore assume my problem is with the Ajax call that I use to pass the JS object to PHP / MySQLi.
Can someone tell me how the correct Ajax call should look like here (e.g. using JSON etc.) or what I have to change on the PHP / MySQLi side ?
My JS object:
0: {vId: "04567901", rId: "DE-002"}
1: {vId: "04567902", rId: "DE-005"}
2: {vId: "04567903", rId: "DE-007"}
length: 3
__proto__: Array(0)
My jQuery / Ajax:
$('#btnConfirm').click(function() {
$.ajax({
type: 'POST',
url: 'updateIds.php',
data: {
transferData: transferData
},
success: function(result){
$('#modalSuccess').modal('show');
}
});
});
My PHP / mySQLi:
$postData = $_POST;
$transferData = $_POST['transferData'];
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("UPDATE myTable l SET l.rId = ? WHERE l.vId = ?");
foreach($transferData as $vId => $rId) {
$stmt->bind_param('ss', $rId, $vId);
$stmt->execute();
}
$stmt->close();
$conn->close();
Update:
My focus is on the Ajax call as I think there is the reason why the data does not reach the PHP page.
Many thanks for any help with this,
Tom
just get your data in php like this:
$postData = file_get_contents("php://input");
$transferData = json_decode($postData, true)['transferData'];
When you use the POST request is better to indicate the data type you're expecting from the server-side use "dataType" in your ajax request, and then parse the data to a valid javascript object in your success handler using JSON.parse().
$('#btnConfirm').click(function() {
$.ajax({
type: 'POST',
url: 'updateIds.php',
dataType: 'JSON', // I'm expecting a json response
data: {
transferData: transferData
},
success: function(result){
// parse json
const data = JSON.parse(result);
$('#modalSuccess').modal('show');
}
});
});
Related
I am having some issue on accessing Ajax Post data on server side. I have
var data = {
ox:'A',
oy:'B',
dx:'C',
dy:'D',
method:null
};
I have a jQuery event hamdler like
$("#route").on("click", function(){
var request = $.ajax({
type: "POST",
url: "assets/app.php",
data: data,
cache: false,
dataType: "JSON",
beforeSend: function() {
console.log(data);
}
});
request.done(function( data ) {
console.log(data);
});
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
});
I am able to send the data correctly as it is logging out at beforeSend
{ox: A, oy: B, dx: C, dy: D, method: null}
On PHP side I have
$method = $_POST['method'];
$ox = $_POST['ox'];
$oy = $_POST['oy'];
$dx = $_POST['dx'];
$dy = $_POST['dy'];
now only accessing to one of the $_POST[] data is working like echo $ox; but when I try to access all $_POST[] data like
echo $ox;
echo $dy;
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
I am getting Request failed: parsererror error on .fail()
From the docs:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So, your response isn't a valid JSON.
What you can do is to create an array, like you are doing:
$startPoint = array($ox, $oy);
$endPoint = array($dx, $dy);
Then encode into json and echo it
echo json_encode(['startPoint' => $startPoint, 'endPoint' => $endPoint]);
On the frontend (javascript) you will get and JSON like
{
'startPoint' : ['ox','oy'],
'endPoint' : ['dx','dy'],
}
the values of ox, oy, dx and dy, of course, will be the values sent before.
I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?
I have an AJAX request here:
var model = $("#variation").val();
var problem_id = $('input[name="problem"]:checked').val();
$.ajax({
type: "POST",
url: "../common/prices.php",
data: {model: model, problem_id: problem_id},
datatype: "json",
success: function (data) {
alert(data['bronze_price']);
},
error: function() {
alert("Error: Contact administrator");
}
});
and the end result is some sort of array.
console.log(data)
returns {"bronze_price":null,"silver_price":null,"gold_price":"249.00"}, by the way
This is the PHP code:
$query = "SELECT * FROM ext_product_price WHERE product_id='".$_POST['model']."' AND problem_id='".$_POST['problem_id']."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
die(json_encode(array("bronze_price"=> $row['bronze_price'], "silver_price"=>$row['silver_price'], "gold_price"=>$row['gold_price'])));
So, data['bronze_price'] returns "undefined" but when I remove all parameters it displays the array {"bronze_price":null,"silver_price":null,"gold_price":"249.00"}. I want to access each individual piece of data (bronze_price, silver_price, gold_price). All answers and comments would be greatly appreciated.
Set the following json header to return json with a valid content type
header('Content-Type: application/json');
die(json_encode(array("bronze_price"=> $row['bronze_price'], "silver_price"=>$row['silver_price'], "gold_price"=>$row['gold_price'])));
you can use the dot notation to get the values
alert(data.bronze_price);
make sure you are returning the correct json structure
It will be data.bronze_price. Others looking OK.
I'm more of a designer but I need to grab some data from a database. I would be able to get what I need without problem using PHP but I'm creating a mobile app in Phonegap so can't use anything other than HTML, CSS or JS.
I've read that this can be done in a PHP file on the server, encoded to JSON and then grabbed in the HTML with Ajax.
Can anyone show me how do I do this, as simply as possible please?
Javascript file
$.ajax({
type: "GET",
dataType: "JSON",
url: "php/phpDb.model.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
php file (phpDb.model.php)
// Connect to database
$con = mysqli_connect("host", "userName", "password", "database")
or die('{ "error" : true, "errorMessage" : "Cannot connect to database '.mysqli_error($con).'"}');
// Query
$sqlCalling = "SELECT * FROM table WHERE ";
$result = mysqli_query($con,$sqlCalling);
$rowCalling = mysqli_fetch_array($resultCalling);
mysqli_close($con);
//getting column_1 and column_2
$column_1 = $rowCalling['column_1'];
$column_2 = $rowCalling['column_2'];
// Return a JSON parseable array
return array(
"column_1" => $column_1 ,
"column_2" => $column_2 ,
);
This solution is very generic, you will most likely just replace the name of the tables and the name of column with what they actually are in your database.
This is a very basic example using jQuery:
//hello_world.js
$.ajax({
url:'hello_world.php',
type: 'POST'
data: { 'var' : 'Hello World' }
}).done(function(response){
alert(response); //Well now alert an json string based on your query..
});
//hello_world.php
$STH = $DBH->prepare("SELECT blabla FROM table WHERE column = ?");
$STH->execute(array($_POST['var']));
$STH->setFetchMode(PDO::FETCH_ASSOC);
$resultQuery = $STH->fetchAll();
echo json_encode($resultQuery); //
I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/