trying to get 2 values from an ajax call, cant seem to breakup the results back form the call
the ajax
$.ajax({
type:'POST',
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
alert(lname);
}
});
the php
$datas = $database->select("Drivers", "*", [
"id" => $q]);
if (count($datas)>0) {
foreach($datas as $data){
$fname=$data['first_name'];
$lname=$data['last_name'];
}
$rdata = array(
'fname'=> $fname,
'lname'=> $lname
);
echo $rdata; //$datas['first_name']
} else {
echo 'no datas';
}
trying to find the lastname only.
thank in advance
Jeff
Change to this:
$.ajax({
type:'POST',
dataType: 'json', // <-- specify that your return type should be JSON
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
if (data.fname && data.lname) {
var firstName = data.fname;
var lastName = data.lname;
}
}
});
when working with arrays you need to use JSON data type.
Your PHP: echo json_encode($rdata);
You can use json_encode() function in your PHP file
echo json_encode($rdata);
Use json_encode() in PHP to serialize your data first as Paramore has explained.
In javascript your success function callback has a parameter of "data", "lname" is not defined in that context so to access fname and lname you need to do like so:
data.lname
data.fname
Related
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
this is my php script from which am returning the value to the ajax calling it
<?php
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
//array values which will be passed to json
$result=array('correct'=>'Correct Answer',
'incorrect'=>'Incorrect Answer'
);
if($dbanswer==$answer)
{
//json to be passed to next page with key value pair
echo json_encode(array('display_msg'=>$result['correct'],'points'=>'positive'));
}
else{
echo json_encode(array('display_msg'=>$result['incorrect'],'points'=>'negative'));
}
?>
and this is my ajax code
$.ajax({
url:'checkanswer.php',
dataType:'json',
data:{'clickedvalue':clickedvalue,'qid':qid},
success:function(data){
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
}
});
So my question is how do i store the value of data.points object that is passed from the php as a json in the javascript variable or is it not possible to store in javascript variable directly if yes how and if no what will be the way to get the value and store somewhere
Just add a temp variable before calling ajax
Some thing like this
var myTempVariable; //Temp JS variable to use somewhere else
$.ajax(
{
url: 'checkanswer.php',
dataType: 'json',
data:
{
'clickedvalue': clickedvalue,
'qid': qid
},
success: function(data) {
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
myTempVariable = data; //assugn value to temp varaible
}
});
in your ajax success function :
var myVariable = data.points;
This might help
I was chasing after JSON as a method to do this, but I'm wondering if I should have been looking in a different direction. I'll tackle this as simply as possible.
Jquery from "page1.php"
$(".button").click(function() {
var name = "Jeremy";
var car = "Saturn";
var color = "blue";
var state = "Mississippi";
// I need all four of these to get passed over to PHP in the following ajax
$.ajax({
url: "page2.php",
//dataType: '???????',
type: 'POST',
data: 'mydata=' + ????????,
success: function(result) {
alert(result);
}
});
});
So there are four jquery variables that I've fudged. Now I need to hand them over to page2.php for my backend PHP. Here is page2.php
if (filter_has_var(INPUT_POST, "mydata")) {
$mydata = mysql_real_escape_string(filter_input(INPUT_POST,'mydata'));
// Here I need to turn these into variables, or just an array and then throw them into my SQL
mysql_query("INSERT INTO mysqldata (namefield, carfield, colorfield, statefield)
VALUES ($name, $car, $color, $state)");
$sqlresult = mysql_insert_id;
if ($sqlresult != '') {
echo "SQL successfully updated.";
}
}
Thus, my question is: What is the most effective method to pass the data to PHP, in this case?
There's probably a simple answer here that I just don't know. Can I turn those jquery variables into an array and hand them to PHP that way? Is JSON still the best way to go, and I just need to know how to convert it on the back end?
As an array
var mydata = [name, car, color, state];
Or as an object
var mydata = { 'name' : name, 'car' : car, 'color' : color, 'state' : state };
-
$.ajax({
...
data: mydata
...
JavaScript/jQuery
$(".button").click(function() {
// create the data object
var myData = {
name : 'Jeremy',
car : 'Saturn',
color: 'blue',
state: 'Mississippi'
};
$.ajax({
url: "page2.php",
//dataType: '???????',
type: 'POST',
data: myData,
success: function(result) {
alert(result);
}
});
});
PHP
// check if the name has been posted, which means we have a submission to process
if(isset($_POST['name'])){
$query = sprintf("INSERT INTO mysqldata (namefield, carfield, colorfield, statefield) VALUES ('%s', '%s', '%s', '%s')",
mysql_real_escape_string($_POST['name']), // clean malicious code
mysql_real_escape_string($_POST['car']), // from user input
mysql_real_escape_string($_POST['color']), // to protect against
mysql_real_escape_string($_POST['state'])); // SQL injection
// run the query
$result = mysql_query($query);
// check if the insert was done successfully
if($result){
echo 'SQL successfully updated.';
}
}
If you notice, based on the id we used on the javascript object to assign the data, we are accessing it in the $_POST array. E.g.
The name
var myData = {
name : 'Jeremy',
...
}
Will be access on PHP side with
$_POST['name']
Hope this blog posts helps you..
http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php
It focuses on using json_decode method to decode the json
I want to pass the key values into php page.
At php page, I will start to read value by matching ajaxcallid.
But it not working.
It gotta do with syntax/way I am passing in causing error.
parse error
invalid json: ajax call id is missing
JavaScript/AJAX:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
alert(person);
person= JSON.stringify(person);
alert(person);
$.ajax({
url: 'ROOT_URL/admin/ajaxtest.php',
type: "POST",
dataType: 'json',
data: {ajaxcallid: '26', jsarr: person},
timeout: 5000,
success: function(output) {
alert(output.Address);
},
});
PHP:
<?php
if (isset($_REQUEST['ajaxcallid']))
{
if($_REQUEST['ajaxcallid']==26)
{
//example, I want to read value of person.Address, person.City,
//person.PostalCode
//what is the easiest way
$phparr= json_decode($_REQUEST['jsarr']);
//do all other operation
$output= json_encode($phparr);
}
}
else
{
$output= "ajax call id is missing";
}
echo $output;
?>
If you are not using dataType : 'json', you might need to do stripslashes
$.post(window.data.baseUrl, {posts : JSON.stringify(posts)});
And in php:
$posts = json_decode(stripslashes($_POST['posts']));
This helped me:
data = json_decode($this->request->data['jsarr'], true);
in your php code for accessing the record
Hope it will help someone!
I'm going to take a guess and say that you SHOULDN'T stringify anything. I believe JQuery will do that for you. Namely, no person = JSON.stringify(person). Give that a try.
This is what your $.ajax call and the PHP side should look like:
JQuery
$.ajax({
url: "/admin/ajaxtest.php",
method: "POST",
data: {
ajaxcallid: "26",
person: JSON.stringify({
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : "99999"
})
}
}).done(function(data) {
if (!data) {
// generic error message here
} else if (data == 'invalid') {
alert('no ajaxcallid received');
} else {
var result = $.parseJSON(data); // if you pass back the object
alert(result.Address);
}
});
PHP
if (isset($_REQUEST['ajaxcallid'])) {
if ((int) $_REQUEST['ajaxcallid'] == 26) {
$personData = json_decode($_REQUEST['person']);
$address = $personData->Address;
$postalCode = $personData->PostalCode;
$returnData = json_encode($personData);
echo $personData;
die();
}
} else {
echo 'invalid';
die();
}
$data_array = json_decode($json_string);
If you want objects to be converted into associative arrays, then add true into function:
$data_array = json_decode($json_string, true);
I have not worked with PHP but from my experience with ASP.net following may help you.
Add contentType key to ajax settigns:
type: "POST",
contentType:'application/json',
dataType: 'json',
also I think you need to stringify whole value you are assigning to data like this:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
var d= {ajaxcallid: '26', jsarr: person};
var dat=JSON.stringify(d);
......
data: dat,
......