Javascript Associative Array cant post via php - javascript

Iam trying to post an Javascript Object via php, but i cant get the value in PHP, iam using laravel framework.
my array,
[type: "sadf", level: "sadfasdf"]
javascript code,
var data_push = Array();
$('form').on('change', 'select, textarea, input', function(t,s){
var key = $(this).attr('id');
var value = $(this).val();
data_push[key] = value;
});
$("#submit").click(function(){
$.post("{!! URL::to('test') !!}", {
_token : tempcsrf,
req_data : data_push
},
function (resp, textStatus, jqXHR) {
alert(resp);
});
});
php code,
public function workbook_save(Request $request_data)
{
$require_data = $request_data->req_data;
print_r($require_data);
}
Tried also JSON.stringfy(data_push) ,json_decode but no luck, i cant get the Javascript object in php, donno what iam doing wrong here, pls advice.

This is what your JS does:
Creates an array
Sets up an event handler to populate the array when things change in the form
Posts the (empty) array to the server
Later on, things will change in the form and data will be put in the array.
The server knows nothing about this because you already sent its contents.
You need to change your logic so you only make the POST request when you are ready to send the data.

Related

Javascript Passing a Parameter to a Controller

I am trying to call the propDetails function and pass an ID to it. Then pass the same ID to the Static controller but I keep on getting an error: "id = id" (second ID doesn't exist).
I am sorry for this silly question and I can't figure out what I am doing wrong...
function propDetails(id) {
var $detailDiv = $('#detailsDiv'), url = $(this).data('url');
$.get( '#Url.Action("PropDetails", "Static", new { id = id })', function(data) {
$('#detailsDiv').html(data);
});
}
Any guidance would be greatly appreciate.
The id variable is not available in the Razor helper, what you can do is concatenate the id after the Url.Action helper has finished:
function propDetails(id) {
var $detailDiv = $('#detailsDiv'), url = $(this).data('url');
$.get('#Url.Action("PropDetails", "Static")' + id, function(data) {
$('#detailsDiv').html(data);
});
}
In the long run you would want to render a form to serialize your id as part of the request, written as $("form").serialize().
It is much easier to append more fields to an action that uses a complex type as a parameter. Your new code would look as follows:
$.get($detailDiv.find("form").attr("action"),$detailDiv.find("form").serialize(), function(data){
$('detailsDiv').html(data);
});
Your form object would be created in your HTTPGET request in MVC, returning the view with your built #Html.BeginForm() helper, which is part of innerHtml of detailsDiv, that can then be serialized using $("form").serialize()
I hope this is clear and fully answers how to fix the issue. I will modify if it is off base and adds more muddle to the mix of Javascript and MVC.

populating a form from an ajax call

Im retrieving some json data from an mvc controller and I want to edit it in a form. Imhaving trouble actually populating the form with the returned data. There is only one row of data, with three properites. Ive checked the data being returned and it is there but whenever I try to set the form value to the json data value, it just falls over. My ajax call compltes ok, i get data back, but I just cant seem to put it into the form. heres the bit in my ajax call that im trying to make work
success: function (data) {
var frm = $("#frmAddDisclaimer");
if ("Disclaimer_ID" in frm.elements) {
frm.elements["Disclaimer_ID"].value = data.ID;
}
if ("Disclaimer_DisclaimerRef" in frm.elements) {
frm.elements["Disclaimer_DisclaimerRef"].value = data.DisclaimerRef;
}
if ("htmlEditorDisclaimer_source" in frm.elements) {
frm.elements["htmlEditorDisclaimer_source"].value = data.DisclaimerText;
}
ive checked the form.elements contents at runtime, and those are the correct ID's and data has corresponding data in each 'property' as well
frm is a jquery object, it has no elements property.
What you're looking for is the fom element inside it, you can expose it via square bracket notation $("#frmAddDisclaimer")[0] or just use document.querySelector
var frm = document.querySelector("#frmAddDisclaimer");

How do i use a javascript variable in wordpress query string?

I need to find a way to use a js variable in wordpress query string. I know it involves ajax but i don't know how to go about it. Please help!
<script>
$(document).ready(function(e) {
var x=$(this).find('.resp-tabs-list li').attr('id');
//alert(x);
});
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
//alert(x);
});
</script>
In the code above, i fetch 'x', which is the category id, based on which i want to fetch posts in a loop.
You are correct that it does involve ajax. You'll need to do something like the following (I haven't tested it, but it should put you on the right track):
Javascript (assuming you have jQuery loaded, and that you've used PHP to output the admin url as a javascript variable ajaxurl):
$(document).ready(function() {
bindCategoryFilter();
}
function bindCategoryFilter() {
$('.resp-tabs-list').on('click',function(e){
var x = $(this).find('.resp-tab-active').attr('id');
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
//this is the name of our Wordpress action we'll perform
'action' : 'get_ajax_posts',
//this is the important line--send 'x' to the server as category
'category' : x
},
success: function(data) {
//do whatever with the data you're getting back
//with the PHP below, it's an array of the post objects
}
});
});
This will POST data to our server, with the variable 'category' set to x in the $_POST variable. To access this, in your functions.php you would want to add something like the following:
//add our action hooks--wp_ajax_XXXXX is defined in the ajax query as 'action'
//the second argument is the name of the PHP function we're calling
add_action('wp_ajax_get_ajax_posts', 'get_ajax_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_ajax_posts');
function get_ajax_posts() {
if(isset($_POST['category'])) {
//get all the posts in the category, add more arguments as needed
$posts = get_posts(array('category' => $_POST['category']));
//data is returned to javascript by echoing it back out
//for example, to return all of the post objects (which you probably don't wnat to do)
echo json_encode($posts);
//we're done
die();
}
}
See the wordpress codex for more information about AJAX and Wordpress.

How to add checkbox info to MySQL database using Ajax?

I have a simple list populated via MySql via Ajax / Json. The list is just a title and description and every entry has a checkbox. I need the checkbox, once clicked, to push to database that it is clicked. How would you go about doing that?
[btw...
right now since I have a setTimeInterval on my SQL data to deliver the list on the fly it automatically resets my checkbox. I'm assuming that if I record that my checkbox has been set via boolean in the SQL that there could be a way to keep it checked...]
I'm new at this and I'm just playing around and trying to learn so this information is entirely theoretical.
You can use the on() function to listen to checkbox clicks.
$(function() {
$(document.body).on('click', 'input.mycheckbox', function() {
var checkbox = $(this);
var checked = checkbox.attr('checked');
$.ajax('service.url', {
type: 'post',
data: {action: 'checkbox-select', id: checkbox.attr('id'), checked: checked},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
// Revert
checkbox.attr('checked', !checked);
}
});
}
});
Feel free to ask if you need any clarification or if this doesn't fit your situation.
EDIT:
The data parameter of the AJAX function is an object that will be posted to your PHP page. When your PHP code is running, $_POST will be an array containing the values we passed. So, $_POST['action'] will be 'checkbox-select', $_POST['id'] will get the ID, and $_POST['checked'] will be true or false depending on whether the checkbox was selected or deselected. Your method of getting the ID in the Javascript will probably change; I just put checkbox.attr('id') to give you an idea.
When learning PHP it can be helpful to dump the responses from the server on the client-side. Example PHP code:
if($_POST['action'] == 'checkbox-select']) {
$checkbox = $_POST['id'];
$checked = $_POST['checked'];
// Your MySQL code here
echo 'Updated';
}
echo 'Code ran';
I edited the JS to show the result from the server.

Getting data via JSON using jQuery

I have a website, where once a button is clicked it will trigger some javascript actions. I want to get some data via a php script i have written. I am using this method:
$.get("get_uni_info.php?addressToSearch=" + address, address, function(myData)
{
$.each(myData, function(key, value)
{
console.info(value);
})
}, "json");
Inside the php code I am trying to get the value "address" to be able to search my database and send back some data but everything I just get nothing returned. I have test to the php code and it will return data if artificial measures are put in place so I can tell its not my PHP code.
Am i going wrong in my jQuery?
Possibly the problem is in usage of $.get method.
You should write either
$.get("get_uni_info.php?addressToSearch=" + address, function(myData) {
...
}, "json");
or
$.get("get_uni_info.php", { addressToSearch : address }, function(myData) {
...
}, "json");
PHP code should handle address as:
$address = $_GET['addressToSearch'];
EDIT: If this does not help, we need to have a look at your PHP code (the response part precisely) to know where is the exact problem.

Categories

Resources