0

I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked. My PHP function is

function adddata($mobile){
    // outside of this function, another database is already selected to perform different
    //tasks with program's original database, These constants are defined only within this
    //this function to communicate another database present at the same host
    define ("HOSTNAME","localhost");
    define ("USERNAME","root");
    define ("PWD","");
    define ("DBNAME","budgetbot");

    // link to mysql server
    if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
        die ("Cannot connect to mysql server" . mysql_error() );
    }

    // selecting the database
    if (!mysql_select_db(DBNAME)) {
        die ("Cannot select database" . mysql_error() );
    }

    //inserting phone number into database
    $query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
    if(!mysql_query($query)){
       die( mysql_error() );
    }

    // wait for 2 seconds after adding the data into the database
    sleep(2);

    $query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
    $result = mysql_query($query) or die( mysql_error() );
    // if more than one records found for the same phone number
    if(mysql_num_rows($result) > 1){
        while($row = mysql_fetch_assoc($result)){
            $data[] = $row['response'];
        }
        // return an array of names for the same phone numbers
        return $data;
    }else{
        // if only one record found
        $row = mysql_fetch_assoc($result);
        $response = $row['response'];
        return $response;
    }
    // end of function
}

HTML Code is written as

<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
    <input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
    <button id="verify" class="btn btn-primary">Verify</button>
    <button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>

I want to call this function and assign the return value to a javascript variable by ajax/jquery. My code to do this is...

<script type="text/javascript" language="javascript">
    $('#verify').click(function(){
        var value = $( ".serial_item" ).val();
        //I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work            
        $.ajax({
            url  : "add_data.php&f="+value,
            type : "GET"
            success: function(data){
                document.getElementById("cname").innerHTML = data;
            }
        });  
    });
</script>

I would like to share that the above javascript code is placed outside of documnet.ready(){} scope Any help would be much appreciated. Thanks

3
  • If the javascript code is placed after the form element, there is no need to put it inside the $(document).ready() function. Commented Mar 8, 2015 at 10:40
  • @kidA Thanks for your reply, but It does not work sir. I want to call the php function without reloading the page and want to display the returned value on the page. Commented Mar 8, 2015 at 10:44
  • You have several bits you need to change in your code. Some tips are prevent form submission, how to return data in ajax, json as dataType in ajax call and the most important, do NOT use mysql functions, switch to PDO or mysqli. Commented Mar 8, 2015 at 10:58

1 Answer 1

1

Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.

You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():

$('#verify').click(function(event){
    event.preventDefault();
    var value = $( ".serial_item" ).val();           
    $.ajax({
        // there's a typo, should use '?' instead of '&':
        url  : "add_data.php?f="+value,
        type : "GET",
        success: function(data){
            $("#cname").html(data);
        }
    });  
});

[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):

if(isset($_GET['f'])){
    // call your function:
    $result = adddata(trim($_GET['f']));
    // if returned value is an array, implode it:
    echo is_array($result) ? implode(', ', $result) : $result;

    // if this is on the same page use exit instead of echo:
    // exit(is_array($result) ? implode(', ', $result) : $result);
}

Make sure you escape the value on $query.

Sign up to request clarification or add additional context in comments.

6 Comments

That will just prevent the page from reloading which is one of the many problems OP's code has at the moment.
@Artur Filipiak Thank you sir, It does help me to prevent the form submission. Can you please provide me any type of link to ajax tutorials where I can understand what is happening in my code, I just copy paste this from other answers. currently, I have no clue what is going on in ajax.
@ArturFilipiak Great sir, That really helps me. Thank you, It would be great if you can guide me how to run this function without saving this into another file, i.e lets say, how to call this function by ajax if php function is placed inside the same php file where we are writing the ajax code to call it.
@ArturFilipiak , you can make it modular by using data:{f:value} .
@jQuery.PHP.Magento.com yes, sure. I just didn't want to change much in OP code, so that it's more understandable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.