My imaginery code:
$(document).ready(function() {
$("#sub").click(function() {
info['moto'] = $("#moto").val();
info['motox'] = $("#motox").val();
$.ajax({
type: "POST",
url: "index.php",
data: "arr="+info,
success: function(msg){
$('.answer').html(msg);
}
})
})
})
How could I make, that after receiving it in .php file I could use POST method like this: $_POST['moto'] and $_POST['motox'] or something like that? What should I change? Thanks.
Just:
data: info,
(And you need to initialize info as an object in the first place: var info = {})
Check out jQuery serialize(), it does all the work for you if you are working with form inputs.
I thinkyoushould go also the same way like jquery-ajax-data-array-from-php
Related
I am fairly new to Laravel and ajax in general, what I am trying to implement is to pass the value of an input field through an ajax get request.
My request looks like this:
function getInfo() {
$.ajax({
url: "info",
dataType: "json"
}).success(function(data){
$('#result').append(JSON.stringify(data));
}).fail(function(){alert('Unable to fetch data!');;
});
}
$('#infoSubmit').click(getInfo);
I have setup a route for my function in laravel that works like this
public/info/Variable <--
When I add a variable after info/
I get the data for that variable (e.g profile name)
I need to pass this variable from an inputfield to ajax request to something like this:
url: "info/+$inputfieldVariable"
Change:
url: "info",
TO:
url: "info/" + $('input-field-selector').val(),
Not sure about the correctness of your JS code: Shouldn't you be using done instead of success?
JavaScript:
function getInfo() {
var myFieldsValue = {};
var $inputs = $("#myForm :input");
$inputs.each(function() {
myFieldsValue[this.name] = $(this).val();
});
$.ajax({
url: "info",
dataType: "json",
data: myFieldsValue,
type: "GET" // Even if its the default value... looks clearer
success: function(data){
$('#result').append(JSON.stringify(data));
},
error: function(){
alert('Unable to fetch data!');
}
});
return false;
}
$('#infoSubmit').click(getInfo);
Untested but should be something like that
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?
Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.
The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.
When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>
I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});
I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P
Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));
In the process of learning Laravel 4, so please pardon me if my question sounds silly.
I am trying to use $.ajax to post form data to the controller.
Upon checking the controller, Input::all() is not populated with data at all.
Have checked that the form is already serialized in the jquery codes.
So now I am here seeking help to see if anyone know how to resolve this issue.
Below is what I have coded so far.
Jquery Code
<script>
$(document).ready(function(){
var BASE = "<?php echo Request::root(); ?>/signup/add";
$('#password').on('blur', function() {
var info = $('.info');
$.ajax({
url:BASE,
method:'post',
contentType:'application/json; charset=utf-8',
cache:false,
dataType:'json',
data: $("#membersignup").serialize(),
success:function(data){
console.log(data);
},
error:function(xhr,status,error){
//errors here
}
});
});
});
</script>
route.php
Route::post('signup/add', array('uses'=>'MemberController#store'));
MemberController.php
public function store()
{
return Response::json(Input::all());
}
Instead of creating the url using this:
var BASE = "<?php echo Request::root(); ?>/signup/add";
Use a named route like this:
Route::post('signup/add', array('uses' => 'MemberController#store', 'as' => 'signup.add'));
So, it'll be easier for you to generate the url for your ajax request, using something like this:
var BASE = "<?php echo route('signup.add'); ?>
This may not solve your problem if you are still generating the right url but this will generate the right url for sure. I doubt that, you are not sending the request to the right url but not sure.
Since there is still no accepted answer, I have just had a similar problem and it was fixed by removing the dataType option and allowing it to select automatically.
Set your contentType like this...
$.ajax({
url:BASE,
method:'post',
contentType: 'application/x-www-form-urlencoded',
cache:false,
dataType:'json',
data: $("#membersignup").serialize(),
success:function(data){
console.log(data);
},
error:function(xhr,status,error){
//errors here
}
});
My guess is that the $.ajax is not working for jquery-1.11.0.min.js.
Changed to $.post and you will have Input::all() working.
Actually the following function works fine, but now I need to add other variable in order to return from the php file the right statement.
function sssssss1(page) {
loading_show();
$.ajax({
type: "GET",
url: "load_data.php",
data: "page=" + page,
success: function (msg) {
$("#search").ajaxComplete(function (event, request, settings) {
loading_hide();
$("#search").html(msg);
});
}
});
}
I need to add the following two variable to be read by my php file. I have tried different solution, but nothing seem working
var form2 = document.myform2;
var dataString1 = $(form2).serialize();
How to add those variable in my existing function? Any idea?
You can send object as data,
this line:
data: "page="+page,
could be
data: {mypage:"page="+page, form2:document.myform2, dataString1:$(form2).serialize()}
and your PHP can get it like:
$page = $_GET['mypage'];
$form2 = $_GET['form2'];
$dataString = $_GET['dataString1'];
Hope it Help.
I've created one Ajax function like this:
function searchPlanAjax(url){
jQuery('#loader').css('display','block');
var plan = jQuery('.rad').val();
var site = url+"fbilling_details/subscription";
jQuery.ajax({
type: "POST",
url: site,
data: "plan="+plan,
//data: "business_name="+val+"&bs="+bs,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
Which I'm calling on radio button's onclick:
<?php echo $form->text(BILLING_DETAIL.'][id_plan', array('type'=>'radio', 'value'=>$val[PLAN]['id'], 'id'=>'id_plan_'.$val[PLAN]['id'], 'class'=>'rad','onclick'=>'searchPlanAjax('."'".SITE_NAME.ROOT_FOLDER_NAME."'".')')); ?>
The Ajax call will be processed in controller of cakePHP like this:
if(!empty($_REQUEST['plan'])){
$search_plan = $this->{PLAN}->find("all",array("conditions"=>array("id=".$_REQUEST['plan'])));
$this->set('search_plan',$search_plan);
}
but I couldn't get value in $search_plan variable. thanks if anybody can help.
Look at conditions in your find query
if(!empty($_REQUEST['plan'])){
$search_plan = $this->{PLAN}->find("all",array("conditions"=>array("id" => $_REQUEST['plan'])));
$this->set('search_plan',$search_plan);
}