Can't manipulate data from $.post - javascript

I'm trying to use the result of an Ajax query in order to set the value of an input.
The problem is that I get an empty result ([Object object])
Here is my process :
First : I realise a simple query and encode the result in JSON :
file : getVar.php
//getMyVar($id) runs a simple "select" query with a specified id
// SELECT name FROM table where id = id
$var= getMyVar($id);
header('Content-type: application/json; charset=UTF-8');
echo json_encode($var);
Then, I (try to) extract the data and I insert it as a value in an input which has the id "name"
Note : I am sure of the input's id.
file : printStuff.js
request = $.post('getVar.php', {id:id}, 'json');
request.done(function(data){
$('#name').val(data.name);
});
When I inspect my page in my browser with firebug, I can see that my first page (getVar.php) returns a well formatted JSON result.
{"id":"42","name":"test"}
So, I think that the error occurs when I try to extract the data form the $.post
If you need any additional information, don't hesitate :)
Thanks for reading.

Try this way to debug you data and encode your data from server side using json_encode()
//getVar.php
$var= getMyVar($id);
die(json_encode(array('status'=>'success','name'=>$var)))
//javascript code
$.post("getVar.php",{id:id}, 'json').done(function( data )
{
console.log(data.status);
console.log(data.name);
if(data.status=='success'){
$('#name').val(data.name);
}
});

Related

Access array posted with Javascript

I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful

JSON response at ajax request to JS variables

I am trying to upload files with dynamic names and get those dynamic names back.
In detail, I have 2 page form.php and upload.php. When upload button is pressed on form.php then request sent to upload.php, where 2 files (DLpath and PhotoIDPath) are uploaded to server with dynamically names e.g :
DLpath=documents/20161130232311i8hGn0HzJT276415832.png
And
PhotoIDPath=documents/20161130232311SSRqCyIbKKalock.png.
It is working fine. Then on upload.php, I am encoding those file names as JSON array i.e.
$response = array ('DLpath'=>$Dlpath ,'PhotoIDPath'=>$PhotoIDPath);
echo json_encode($response);
And firebug snapshot is :
I want to get DLpath in var jsDlpath and PhotoIDPath in var jsPhotoIDPath
And my code ( Not working) to get response is :
complete: function(response)
{
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}
And alert show :
undefined - undefine
If you can help me to gwt those values in js variables, I will be very thankful to you.
Since you're encoding you response in server side you should parse it in the js side, you could use $.parsejson() :
success: function(response)
{
var response = $.parseJson(response);
//if $.parseJson dont work, use JSON.parse
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}
NOTE : Use success/done callback instead of complete.
Hope this helps.
If running in pure javascript you will find that there are two response attributes: responseText and responseXML. You probably want:
var data = JSON.parse(response.responseText);
A complete example, using curl from https://gist.github.com/bitdivine/7ddd943387a4350336dd (but jquery will do fine as well) to get open issues on Github:
curl('https://api.github.com/repos/gchq/CyberChef/issues?state=open')
.then((res) => JSON.parse(res.responseText))
.then((data) => console.log(data))

trouble submitting ajax form in yii

I am creating a widget for use in a website to 'find' a match in any field in the database. I currently am using a jQuery 'Dialog' box, and wish to submit the form, have the form redirect to a controller/action (I am using yii which uses the MCV model), and return the output of that function into the current window.
I am currently using a hidden div, and the jquery load function.
$("#find_results").load(loadPage, function(){
}).show();
which calls a function that does this essentially:
public function actionFind(){
if (!empty($_POST)){
//do really big query
//put results into <tr> and <td> tags using a for loop
}else{
echo <tr><td>"no results found"</td></tr>;
}
}
this code returns an output, but only ever "no results found", leading me to believe that the form never actually gets posted.
does anyone know what kind of black magic is happening here??
thanks!
P.S.
The dialog box is a partial view which contains the form to be submitted with the action /controller/find
updated:
I implemented this instead: new error is "undefined index: findtext", which is the name of my text input.
$("#find_results").load(loadPage,{ data: $("#find_form").serialize() },function(data){
console.log(data);
$('#find_results').html(data);
$(this).show();
});
First, lets look at the signature for .load()
.load( url [, data ] [, complete ] )
url
Type: String
A string containing the URL to which the request is sent.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
complete
Type: Function( String responseText, String textStatus, jqXHR jqXHR )
A callback function that is executed when the request completes.
So, if you want to send data to the server, you'd do something like:
$("#find_results").load(loadPage, {someKey: 'some value'}, function(){
$(this).show();
});
Now, that we are sending data, nevermind what I said before about $_GET
From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Also, since you've tagged yii you may need to access $_POST differently in your app, something like this:
public function actionFind( ){ // pass in $request from your app
$request = Yii::$app->request;
if (!empty( $request->post() )){ // change this
//do really big query
//put results into <tr> and <td> tags using a for loop
}else{
echo <tr><td>"no results found"</td></tr>;
}
}
See The Definitive Guide to Yii 2.0 which says this:
$request = Yii::$app->request;
$post = $request->post();
// equivalent to: $post = $_POST;
$id = $request->post('id');
// equivalent to: $id = isset($_POST['id']) ? $_POST['id'] : null;

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

Unable to access parameters in PHP, Posted values from jQuery with Serialize

I am sending data from jquery via AJAX Post with all the form fields serialized (In WordPress).
$('#SendEmail').click(function () {
jQuery.post(
the_ajax_script.ajaxurl,
{
'action': 'the_ajax_hook_SendEmailWithCalculatorContent',
'calculatorFormContent': $("#CalculatorForm input").serialize()
},
function (response_from_the_action_function) {
$("#G1").val(response_from_the_action_function);
}
);
});
Here are the post paramters from firebug POST:
action the_ajax_hook_SendEmailWithCalculatorContent
calculatorFormContent ZIPCodeTextBox=01915&G1=PhoneNumber+%3A++ZipCode+%3A+&G2=&G3=&G4=&G5=&G6=&G7=&G8=&G9=&G10=&G11=&G12=&G13=&G14=&G15=&G16=&G17=&G18=&G19=&G20=&G21=&G22=&G23=&G24=&G25=&G26=&G27=&fullname=&email=&phone=7324211531
Need to access these parameters in PHP, when I try to access them
echo "PhoneNumber : ".$_POST['phone']." ZipCode : ".$_POST['ZIPCodeTextBox']." IndexValue : ".$_POST['0'];
I get the output as "PhoneNumber : ZipCode : IndexValue : ", so all the form data is coming as blanks.
When I try:
echo $_POST;
i see value "Array" come across.
How do I access the array value?
Saw multiple posts here that answer by using the parameter name, one can fetch data from $_POST['name']. (Similar link: jQuery AJAX form data serialize using PHP)
But apparently it is not working in my case.
What about 'calculatorFormContent': JSON.stringify($("#CalculatorForm input").serializeArray()) and then in your PHP script use $array = json_decode($_POST['calculatorFormContent'], true);
Later access it with $array['phone'].

Categories

Resources