简体   繁体   English

Laravel使用AJAX将Javascript变量传递给PHP

[英]Laravel Using AJAX to pass Javascript variable to PHP

I am trying to pass a variable from my javascript code to the server side PHP code. 我试图将变量从我的JavaScript代码传递到服务器端PHP代码。 I know this must be done via an ajax, But unfortunately I do not receive the value in the PHP variable in blade view. 我知道这必须通过ajax完成,但是很遗憾,我没有在刀片视图的PHP变量中收到该值。

form : url = facture=20 形式:网址=实际= 20

{!! Form::open(array('url'=> 'admin/facture=20', 'method'=>'post',   'name'=>'pushds')) !!}
{!! Form::hidden('ms_id', $fact->id) !!}
{!! Form::hidden('mstid', $fact->b_id, array('id' => 'mstid')) !!}     
{!! Form::close() !!}

jquery : jQuery的:

$('form[name="pushds"]').on('submit', function (e){
    e.preventDefault();

  var mstid = $('#mstid').val();
  var ms_id = $('#ms_id').val();

        $.ajax({
            type: 'post',
            url: 'facture=20',            
            data: {mstid: $('#mstid').val(), ms_id : $('#ms_id').val()},
            success: function( data ) {
......
},

the current page url : facture=20 当前页面网址:facture = 20

the variable php in blade view 刀片视图中的变量php

<?php 
if (!empty($_POST["mstid "])) {
echo $_POST['mstid ']; 
}
?>

Try this 尝试这个

In form ( Add id field to from ) 格式将id字段添加到from

{!! Form::hidden('ms_id', $fact->id, array('id' => 'ms_id')) !!}
{!! Form::hidden('mstid', $fact->b_id, array('id' => 'mstid')) !!} 

In AJAX 在AJAX中

var mstid = $('#mstid').val(); # Calling through respective ID
var ms_id = $('#ms_id').val(); # Calling through respective ID

$.ajax({
    type: 'post',
    url: 'facture=20',            
    data: {mstid: mstid , ms_id : ms_id }, # passing variables 
    success: function( data ) {

Make sure your from submit reaches the AJAX code. 确保您的发件人达到AJAX代码。 You can test it by using alert() inside AJAX function .. 您可以使用AJAX函数..中的alert()对其进行测试。

There are many methods to pass javascript value to server side using ajax: 有很多方法可以使用ajax将javascript值传递给服务器端:

Method 1: 方法1:

Change your ajax code to: 将您的ajax代码更改为:

From: 从:

    $.ajax({
            type: 'post',
            url: 'facture=20',            
            data: {mstid: $('#mstid').val(), ms_id : $('#ms_id').val()},
            success: function( data ) {
......
},

To: 至:

$.ajax({
            type: 'post',
            url: 'facture=20',            
            data: {mstid: $('input[name=mstid]').val(), ms_id : $('input[name=ms_id]').val()},
            success: function( data ) {
......
},

And on server side you can get it as : 在服务器端,您可以将其获取为:

<?php 
if (isset($_POST["mstid "]) && $_POST["mstid "] != "") {
echo $_POST['mstid ']; 
}
?>

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM