admin管理员组

文章数量:1402050

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:

function getObdDescription(){

    var $code = document.getElementById("vehicle_obd_code").value;
    var $length = $code.length;


    if($length == 5){
        window.confirm($length);

        $.ajax({ url: '/new.php',
            data: {action: 'test'},
            type: 'post',
            success:function(result)//we got the response
            {
            alert('Successfully called');
            },
            error:function(exception){alert('Exception:'+exception);}
        });
        }
    return false;
}

Here is new.php

<?php
    echo '<script language="javascript">';
    echo 'alert("message successfully sent")';
    echo '</script>';
?>

I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?

I have a very simple jquery function that sends an Ajax call to a php file that should echo out an alert, but for the life of me, cannot get it to run. For now, I'm just trying to trigger the php to run. Here is the javascript:

function getObdDescription(){

    var $code = document.getElementById("vehicle_obd_code").value;
    var $length = $code.length;


    if($length == 5){
        window.confirm($length);

        $.ajax({ url: '/new.php',
            data: {action: 'test'},
            type: 'post',
            success:function(result)//we got the response
            {
            alert('Successfully called');
            },
            error:function(exception){alert('Exception:'+exception);}
        });
        }
    return false;
}

Here is new.php

<?php
    echo '<script language="javascript">';
    echo 'alert("message successfully sent")';
    echo '</script>';
?>

I'm testing in Chrome, and have the network tab up, and can see that the call is successful, as well, I get the 'Successfully called' message that pops up, so the jquery is running, and the Ajax call is successful. I also know that the url: '/new.php is correct, because when I delete new.php from my server, I get a status "404 (Not Found)" from the console and network tab. I've even test without the conditional if($length ==... and still no luck. Of course, I know that's not the problem though, because I get the 'Successfully called' response. Any ideas?

Share Improve this question asked Nov 27, 2017 at 15:20 JordanJordan 1582 silver badges13 bronze badges 4
  • So in a server script you write a client script ? – Daniel E. Commented Nov 27, 2017 at 15:22
  • 3 That script won't run itself...it is simply a text string that is available in result. Browser knows nothing about running it because it isn't in the dom – charlietfl Commented Nov 27, 2017 at 15:22
  • this is not going to happen the way you are doing it – Muhammad Omer Aslam Commented Nov 27, 2017 at 15:25
  • 1 for testing: set "message successfully sent" in your PHP and alert(result) in your ajax call. As said before, you need to use the result of your call into your action! – Odyssey1111 Commented Nov 27, 2017 at 15:27
Add a ment  | 

2 Answers 2

Reset to default 9

This isnt the way it works if you need to alert the text, you should do it at the front-end in your ajax success function, follow KISS (Keep It Simple Stupid) and in the php just echo the text . that is the right way to do it.

You should do this:

function getObdDescription() {

    var $code = document.getElementById("vehicle_obd_code").value;
    var $length = $code.length;


    if ($length == 5) {
        window.confirm($length);

        $.ajax({
            url: '/new.php',
            data: {
                action: 'test'
            },
            type: 'post',
            success: function (result) //we got the response
            {
                alert(result);
            },
            error: function (exception) {
                alert('Exception:' + exception);
            }
        });
    }
    return false;
}

In your php

<?php
   echo 'message successfully sent';
?>

You are exactly right Muhammad. It was not going to work the way I was expecting it. I wasn't really trying to do an Ajax call, but just to get an alert box to pop up; I just wanted confirmation that the call was working, and the PHP was running. Changing the alert('Successfully called'); to alert(result); and reading the text from the php definitely confirmed that the php was running all along.

I want to stay on topic, so will post another topic if that's what's needed, but have a follow-up question. To elaborate a bit more on what I'm trying to do, I am trying to run a function in my php file, that will in turn, update a template variable. As an example, here is one such function:

function get_vehicle_makes()
{
    $sql = 'SELECT DISTINCT make FROM phpbb_vehicles
            WHERE year = ' . $select_vehicle_year;

    $result = $db->sql_query($sql);

    while($row = $db->sql_fetchrow($result))
    {
        $template->assign_block_vars('vehicle_makes', array(
            'MAKE'    => $row['make'],
        ));
    }
    $db->sql_freeresult($result);
}

Now, I know that this function works. I can then access this function in my Javascript with:

<!-- BEGIN vehicle_makes -->
        var option = document.createElement("option");
        option.text = ('{vehicle_makes.MAKE}');
        makeSelect.add(option);
<!-- END vehicle_makes -->

This is a block loop, and will loop through the block variable set in the php function. This work upon loading the page because the page that loads, is the new.php that I'm trying to do an Ajax call to, and all of the php runs in that file upon loading. However, I need the function to run again, to update that block variable, since it will change based on a selection change in the html. I don't know if this type of block loop is mon. I'm learning about them since they are used with a forum I've installed on my site, phpBB. (I've looked in their support forums for help on this.). I think another possible solution would be to return an array, but I would like to stick to the block variable if possible for the sake of consistency.

I'm using this conditional and switch to call the function:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];

    //Get vehicle vars - $select_vehicle_model is used right now, but what the heck.
    $select_vehicle_year = utf8_normalize_nfc(request_var('vehicle_year', '', true));
    $select_vehicle_make = utf8_normalize_nfc(request_var('vehicle_make', '', true));
    $select_vehicle_model = utf8_normalize_nfc(request_var('vehicle_model', '', true));

    switch($action) {
    case 'get_vehicle_makes' :
        get_vehicle_makes();
        break;
    case 'get_vehicle_models' :
        get_vehicle_models();
        break;
    // ...etc...
    }
}

And this is the javascript to run the Ajax:

function updateMakes(pageLoaded) {
    var yearSelect = document.getElementById("vehicle_year");
    var makeSelect = document.getElementById("vehicle_make");
    var modelSelect = document.getElementById("vehicle_model");

    $('#vehicle_make').html('');

    $.ajax({ url: '/posting.php',
            data: {action: 'get_vehicle_makes'},
            type: 'post',
            success:function(result)//we got the response
            {
            alert(result);
            },
            error:function(exception){alert('Exception:'+exception);}
    });
    <!-- BEGIN vehicle_makes -->
        var option = document.createElement("option");
        option.text = ('{vehicle_makes.MAKE}');
        makeSelect.add(option);
    <!-- END vehicle_makes -->

    if(pageLoaded){
        makeSelect.value='{VEHICLE_MAKE}{DRAFT_VEHICLE_MAKE}';
        updateModels(true);
    }else{
        makeSelect.selectedIndex = -1;
        updateModels(false);
    }
}

The javascript will run, and the ajax will be successful. It appears that the block variable is not being set.

本文标签: javascriptajax request is successfulbut php is not runningStack Overflow