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

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

Related

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;

Manage form-data + other variable sent via ajax to php

My question is probably basic, but there is the question:
I have a javascript function which sends an array via ajax to process some information...
var second = $('form.contact').serialize();
var arry = {keystatus: varId, keyname: second}
In php, I added the data sent via ajax a array and wrote an echo to see in ajax success, displaying via console.log.
What do I get:
My php script:
$name = strip_tags($_POST['keystatus']);
$email = strip_tags($_POST['keyname']);
$teste['nome'] = $name;
$teste['email'] = $email;
echo json_encode($teste);
I needed to find a way to get separate, for example:
$_POST['keyname']['nome'] -> (in this example) discovery
$_POST['keyname']['email'] -> discovery#discovery.com
$_POST['keyname']['usuario'] -> discovery
You are currently adding the form data as a serialized string to an object, which you send. That's why it looks the way it does.
You can either build a new object with all data and send that object with ajax:
var data = {
keystatus: varId,
keyname: {
nome: $("#the_nome_input").val(),
email: $("#the_email_input").val(),
usuario: $("#the_usuario_input").val()
}
};
Or you can add the extra value (since it only seems to be one) as a hidden input field in your form:
// Add this to the form
<input type="hidden" value="" name="keystatus" id="keystatus" />
// In your js, add
$("#keystatus").val(varId); // Sets the value
var data = $("form.contact").serialize();
...now you can send data to your back end using ajax.
If you want to fetch your data like this: $_POST['keyname']['nome'] and use the second alternative, then you need to rename your input fields to: name="keyname[nome]", name="keyname[email]" and name="keyname[usuario]".
That will give you the correct data structure and values.

Passing data from Javascript to php with Laravel 5.1

I need to pass data from Javascript to php using Laravel 5.1
So right now I have a blank page with input(name='q'). When I start typing it sends the query via Ajax data:{q: query} to php so in php I am taking the value from q $query = e(Input::get('q', '')); (Laravel syntaxis) and I am processing the data and I have a respond from the php
return response()->json(array(
'data' => $data
));
So after Ajax is succeeded. The ajax is taking the respond :
function(item, escape) {
console.log(item); }
And the output data is object:
Object {url: "http://localhost:8000/well/3", name: "Welly", iso3_code: "NOR", class: "product"}
So by clicking a button I want to send this data via POST to some method.
After this all I need to take the "item" from js and save it to php variable so via POST I can send this data to differened procces. So after the POST I will have the data for the other process.
I would have access to the object via the respond from the php 'data' => $data
or from the js "item" .... But whatever I try I can not manage to do it.
Thank for helping me.
EDIT
So at all I have JS object that I need to send as a POST request to the server so after that with php I will do stuffs with the object taken from the JS. Is that clear enough.
You can probably do return response via json_encode from php to javascript then in the javascript you can do {{$phpVariable}} = var javascriptVariable

Can't manipulate data from $.post

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);
}
});

passing JSON data and getting it back

I'm new to passing objects through AJAX, and since I am unsure of both the passing and retrieving, I am having trouble debugging.
Basically, I am making an AJAX request to a PHP controller, and echoing data out to a page. I can't be sure I'm passing my object successfully. I am getting null when printing to my page view.
This is my js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
My PHP controller:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
My PHP view:
<?php var_dump($filters);?>
Perhaps I need to use a jsondecode PHP function, but I'm not sure that my object is getting passed in the first place.
IIRC the data attribute of the $.ajax jQuery method accepts json data directly, no need to use JSON.stringify here :
data: {filters: filters}
This way, you're receiving your json data as regular key/value pairs suitable for reading in PHP through the $_POST superglobal array, as you would expect.
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
When you use ajax the page is not reloaded so the php variable isn't of use.
You may want to look for a tutorial to help. I put one at the beginning as I don't see how to format this on my tablet
you will need to json_encode your response as the tutorial shows
you may want to print to a log on the server when you are in the php function and make it world readable so you can access it via a browser
I like to use the developer tools in Chrome to see what is actually returned from the server

Categories

Resources