Returning a PHP response in a AJAX query

thebarless

I want to submit a form to a PHP script, let the script do its magic, then return said magic into a div as a visual indicator of its success/failure/change in status.

I have a form which I submit (I've cut out a lot of extraneous inputs/text areas, etc. of code which aren't important):

HTML:

<form name="ajaxform" id="ajaxform" method="post" action="ajax.php">
<table>
<tr class="left"> 
<td>Reporter:</td>
<td>//list of people</td>
</tr>
<tr class="left"> 
<td width="75%">
<p><label for="start">Start:</label>
<input type="text" name="start" id="start"></p>
<p><label for="end">End:</label>
<input type="text" name="end" id="end"></p>
</td>
</tr>
<tr>
<td>
<input name="sid" type="hidden" id="sid" value="<?=$sid?>"> 
<input name="table" type="hidden" id="table" value="add"> 
<input name="submit" type="submit" id="submit" value="Submit" class="submitForm"> 
</td>
</tr>
</form>
<div id="messageResponse"></div>

On submitting, the following JS gets run:

JS:

$(function() {
    $('#ajaxform').validate({ // initialize the plugin
        errorClass: "invalid", 
        submitHandler: function (form) {

        $.ajax({
                type:'POST',
                url:'ajax.php',
                data: $(form).serialize(),
                success: function() {
                    $('#messageResponse').fadeIn(500);
                    $('#messageResponse').addClass('ui-state-highlight ui-corner-all').removeClass('ui-state-error');
                    $('#messageResponse').text('Success!' + result);                        
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $('#messageResponse').fadeIn(500);
                    $('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
                    $('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
                }

        });

        setTimeout(function(){ $('#messageResponse').fadeOut(500); }, 5000);

        // resets fields
        $('#ajaxform')[0].reset();
    }
});

});

And then I have the script which get's picked out from a list of several PHP scripts based on the table variable passed from the form's hidden table input:

PHP:

if($_POST['table'] == "add"){

// Do mysql query which gives me an array

    $result = array("foo" => "bar", "captain" => "coke");
    echo(json_encode($result));
}

I want to submit my form, have it find the appropriate code in ajax.php and execute it, then return the result of that PHP script to messageResponse div. Where is this failing so miserably?

dashtinejad

You should pass the result variable in your success method:

success: function (result) {
    console.log(result);
}

In addition:

  1. Set the type of data that you're expecting back from the server:

    dataType: 'json'
    
  2. Set the header of your result as JSON (in your PHP file):

    header('Content-Type: application/json; charset=utf-8');
    

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Ajax JSON PHP Stringify not posting but returning successfully

분류에서Dev

Empty response by JQuery.ajax and object and php

분류에서Dev

Wcf returning ususual response

분류에서Dev

PHP: Cannot stream CSV file to client in response to AJAX call

분류에서Dev

How To Deal With Response To PHP Prepared SELECT EXISTS QUERY?

분류에서Dev

AJAX not returning anything - Wordpress

분류에서Dev

JSON response returning null array

분류에서Dev

Linq query returning duplicates

분류에서Dev

Query returning false

분류에서Dev

Laravel Ajax search gives the whole collection as response to the query after input is cleared from input box

분류에서Dev

MS SQL Server procedure from php fails with 500 when returning query is not empty

분류에서Dev

AJAX response text displaying

분류에서Dev

Ajax response in datatables

분류에서Dev

Ajax response not showing in JS

분류에서Dev

Json response to ajax

분류에서Dev

Trailing newline in AJAX response

분류에서Dev

PHP function not returning value

분류에서Dev

PHP Model not returning result

분류에서Dev

MongoDb query not returning all the fields

분류에서Dev

MongoDb query not returning all the fields

분류에서Dev

WMIC Query returning unexpected answer?

분류에서Dev

Returning an error response in the case of a null model

분류에서Dev

Laravel 4.2 returning a json response with Auth::onceBasic()

분류에서Dev

Jquery/Ajax - Parse JSON Response

분류에서Dev

Script shop Ajax response in fancybox

분류에서Dev

Can't get Ajax response

분류에서Dev

Ajax call to controller function not returning data

분류에서Dev

allDocs query returning design docs in PouchDB

분류에서Dev

Why is this query (potentially) only returning posts that are questions?