trouble submitting ajax form in yii - javascript

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;

Related

Can I send a variable to my PHP code when I use $.getJSON?

I currently have some JQuery code where I send the variable 'name' to a PHP file, and that PHP file calls the data in row 'name'
//JQuery Code
$('#next').click(function() {
$('#question > h1').load('/php/getQuestion.php', {
name: qty
});
});
//PHP Code Below
$value = (integer)$_POST["name"];
$sql = "SELECT `question_id`, `question` FROM Question WHERE `question_id` =
{$value}";
I want to do a similar call using JQuery's $.getJSON. Currently this is my code:
var requestAnswer = ($.getJSON('[URL HERE]'));
Is there any way I could send the value of 'name' to my PHP code and get only the JSON request from row: 'name'. Something like:
var requestAnswer = ($.getJSON('[URL HERE]'),{ name:2});
I know this example doesn't work.
Based on jQuery.getJSON() documentation:-
You can pass your data as the second parameter:
$.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
like below:-
$.getJSON( "Url", {name:2},function( data ) {
//code based on data
});
Again the documentation says:-
"Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL."
So you can retrieve it to php end by using:-
$_GET['name'];
You can add the query string into the url like that
$.getJSON('getQuestion.php?name=abc', function(data) {
//process data here
});
on Server side, use $_GET["name"] to retrieve parameter

How do I send a variable name and its value to the server and receive back a calculated response

I am new to wordpress and plugins but have a reasonable grip on php, javascript and html. I have created a plugin for wordpress which generates a page (form) which gathers information regarding a product specification. [It is actually a number of sequential forms, but for simplicity lets say it is one. I do not want to "submit" the form as there are many fields on each form and I do not want to "submit" until it is completed and they are ready to move to the next form].
I would like to be able to (re)calculate the product price when the user changes a parameter. To do this I would like to be able to pass the name of the changed parameter and its value back to the server (where all of the dependant data for the calculation is stored), and do the calculation and return the new price. At present I have a javascript function which is called with the pertinent data on an "onChange" and then modifies the div which represents the total price. this works if I compute the value locally, but now I am looking to complete the function by sending data to the server and receiving the calculated response e.g. :
function total_price(arg,value) {
***** send arg and value to server *****
***** receive total_price back from server *****
var total_div = document.getElementById("total_price");
total_div.innerHTML = "£"+total_price;
}
What code should I be putting in here and what should I have on the server in order to receive the data, do the calculation and send back the result?
I mostly have jQuery loaded in the front-end, so I'll post an answer using the jQuery framework. You'll most probably find a good vanilla snippet elsewhere if you're not looking to load a javascript library.
Front End
var html_price = 1; // Whatever you need here
// You'll notice that the ajaxurl variable below, is sent to the front-end in the second code snippet of this answer
$.post( ajaxurl, {
action: "get_total_price", // action is a special parameter Wordpress is listening for
price: html_price
}).done( function( price ) {
// Price back from the server you can use in the DOM
// You should probably send this using JSON, this example only uses a string
console.log( price );
});
Back End
// Here is where Wordpress is waiting for that special action parameter
// https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action( 'wp_ajax_get_total_price', 'get_total_price' );
add_action( 'wp_ajax_nopriv_get_total_price', 'get_total_price' );
function get_total_price() {
$price = $_POST[ 'price' ];
if( $price ) {
// do with the price what you want
echo $price; // Echo instead of return
exit; // Remember to close up the server response here
} else {
echo '0'; // Unrealistic, but guarantees a response
exit;
}
}
// Send the AJAX URL to the front end. There are more elegant ways to do this, but for the purpose of this answer, this should work.
add_action( 'wp_head', 'add_ajaxurl_to_head' );
function add_ajaxurl_to_head() { ?>
<script>
ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
At last I got it working (based upon your code and grasping the difference between the server and client contexts, which language to use where and what data is accessible). Thanks for your help. There must be scope for a single language for web development which is readable and context aware? HeHo, there I go wanting the world to change to suit me!!

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

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

How to pass a variable with $.post for javascript script?

Here is my code in my jquery/javascript that is performing the ajax request...
else {
$.post("http://www.example.com", {email: val},
function(response){
finishAjax('email', response);
});
}
joinAjax('cemail');
}
if (id == 'cemail') {
$('#cemailMsg').hide();
var email = $('#email').val();
if (errors.email == false) {
if (val != email) {
The ajax request is working and all is good, but the next if statement where the argument is:
if (errors.email == false) {
I need to be able to set this variable from my ajax.php file to either true or false and return it so the javascript can read it. Is this possible??
It is because the ajax is checking if the username is available or not, if not available a form error would be true preventing the form submitting, or if false then the user can submit.
My ajax.php file:
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo '<div id="emailMsg" class="success">Email OK</div>';
exit();
}
else {
echo '<div id="emailMsg" class="error">Email taken</div>';
exit();
}
}
Why not have your ajax.php return an associative array like so:
echo json_encode(array("email" => "success", "key2" => "val2"));
And then use
var responseJSON = JSON.parse(response);
In the $.post callback function to read the response and act accordingly. You can generate the appropriate markup (divs or whatever) client-side and insert it.
You may want to back up and determine what you want here. If all you want to do is display a different message depending on the result of the post, return (from the post) the smallest amount of information. In this case the value could simply be boolean. email valid or invalid.
I would recommend returning json from your post.
If you are returning json, the success method (function(response){}) is where you could operate on or evaluate the response.
If you return json (which can be strings from PHP, in this case), it evaluates to JavaScript objects. so if you returned '{"errors":"true"}' it will evaluate to (response.errors === true) within your success method in the post call.
'errors' is undefined, correct? Make it a property of the response json object, and be sure to test for undefined values on the data you get back.
Generate HTML or manipulate CSS based on the values you get from the post.
In that vein, jquery makes it easy to add HTML to the DOM. Try
(can someone fix my formatting and add a code tag if you can edit? I'm on my cell ATM)
$('&ltdiv&gt&lt/div&gt', {
text : 'your text here',
class : 'yourclass'
}).appendTo($(element));

Categories

Resources