Jump to content

Form processing and return with page reload


lanredoyes
Go to solution Solved by lanredoyes,

Recommended Posts

Hello, I have a page that does two things at the same time. One is to ask the use to input a field in an input field and submit and the other is to display everything the user as saved in the database.

 

Presently, the script is working as expected but i am trying to implement this using jQuery Ajax so as to remove page reload. I have gone through lots of tutorials on the internet and have done everything they instructed.

 

I am at a deadline here and please asking for a way out. The screen shot of my output is attached and my current code is presented below.

 

<?php

//Include Functions
include('includes/Functions.php');

//Include Notifications
include ('includes/notification.php');

// add new category
if (isset($_POST['submit'])) {

$category = $mysqli->real_escape_string($_POST["account"]); 
//add new category
$sql="INSERT INTO account (UserId, AccountName) VALUES (?,?)";
if($statement = $mysqli->prepare($sql)){
//bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
$statement->bind_param('is',$UserId, $category); 
$statement->execute();
}
$msgBox = alertBox($SaveMsgAccount); 

}

//Get list category
$GetList = "SELECT AccountId, AccountName FROM account WHERE UserId = $UserId ORDER BY AccountName ASC";
$GetListCategory = mysqli_query($mysqli,$GetList); 

//Include Global page
include ('includes/global.php');


?>

<div class="pages">
  <div data-page="projects" class="page no-toolbar no-navbar">
    <div class="page-content">
    
     <div class="navbarpages">
       <div class="nav_left_logo"><a <?php ActiveClass("index");?> href="index.php"><img src="images/logo.png" alt="" title="" /></a></div>
       <div class="nav_right_button"><a <?php ActiveClass("index.php?page=menu");?> href="index.php?page=menu"><img src="images/icons/white/menu.png" alt="" title="" /></a></div>
     </div>
     
     <div id="pages_maincontent">
      
      <h2 class="page_title">My Accounts</h2>
      
      <div class="page_content">
 <div id="container">
<ul class="responsive_table">
<li class="table_row">
<div class="table_section2">Add New Account</div>
</li>
<li class="table_row">
<div class="contactform">
<form class="cmxform" method="post" id="AccountForm" action="" >
<label><?php echo $Category; ?></label>
<input required placeholder="<?php echo $Account; ?>" name="account" type="text" autofocus class="form_input" />

<input type='hidden' name='action' value='create' /> 
<input type="submit" name="submit" class="form_submit" id="submit" value="<?php echo $SaveAccount; ?>" />
</form>
</div>
<script>
$(function(){

$('#submit').click(function(){
$('#container').append('<img src = "images/loader.gif" alt="Loading..." id = "LoadingGraphic" />');
$.ajax({

url: 'accounts.php',
type: 'POST',
data: $('#AccountForm').serialize(),
success: function(result){
$('#response').remove();
$('#container').append('<p id = "response">' + result + '</p>');
$('#LoadingGraphic').fadeOut(500);

  }

});         
e.preventDefault(); //STOP default action
});
})
</script>
</li>
        </ul>
 </div>

<br /><br /> 

<h3>My Account List</h3>
<ul class="responsive_table">
<li class="table_row">
<div class="table_section"><?php echo $Account; ?></div>
<div class="table_section"> </div>
</li>
<?php while($col = mysqli_fetch_assoc($GetListCategory)){ ?>
<li class="table_row">
<div class="table_section"><?php echo $col['AccountName'];?></div>
<div class="table_section_last"> </div>
</li>
<?php } ?>
        </ul>
      
      </div>
      
      </div>
      
      
    </div>
  </div>
</div>

Thanking you for any help rendered.

 

post-139484-0-29780300-1468966912_thumb.png

Link to comment
Share on other sites

Help you with what? You haven't even told us what the problem is.

 

Until then, all I know is that your database queries are messed up. First you use a prepared statement and manual escaping at the same time, which will screw up the data. Then you use neither, which will lead to security vulnerabilities. Use prepared statements; no manual escaping, no unprotected queries.

 

The code is also vulnerable to cross-site scripting attacks. You need to HTML-escape strings before you can insert them into your page.

Link to comment
Share on other sites

Thanks for the response.

 

The help I need now is to make the form process without page reload. I know this is possible with Ajax but I just can't seem to make it work.

 

Another thing is with each form process, the table below has to be updated with the new content of the database also without reloading the page.

 

I will be cleaning up the code once I get the script to work as expected.

 

Thanks

Link to comment
Share on other sites

I know this is possible with Ajax but I just can't seem to make it work.

 

This tells us absolutely nothing. I know the code “doesn't work”, otherwise you wouldn't be here. The question is: What exactly is the problem? Be specific. What goes wrong when? Are there any PHP or JavaScript errors? What do the developer tools of your browser tell you about the HTTP communication?

 

We're not sitting in front of your screen. We don't have your application on our PC. We know nothing except what you tells us. So if you want help, you need to actually provide information.

Link to comment
Share on other sites

When I submit the form as it is above, the data goes into the database and it appears in the table below as well without error but this is done with page reload. I want the form to process without page reload and for the table below to display databse content.

 

I am sorry if I am not been clear enough, the onSubmit event doesn't just work. No error display of any kind.

 

Thanks

Link to comment
Share on other sites

to convert a design to use ajax, you are basically splitting and moving functionality around between the server-side and client-side code. however, your design should still work if javascript is disabled. therefore, the changes you make to the server-side code should be conditional, so that it produces the same exact output it does now, if javascript is disabled.

 

when you make the ajax requests (one to post the form data and a second to get and display the account listing), the response your code returns needs to be just the data that you expect, not the whole web page.

 

the response when you post the form data would be your $SaveMsgAccount/$msgBox on success, or validation errors or a generic 'cannot perform action' for query errors when it fails. the response when you get the account listing would be the html markup you are producing for that list now.

 

you can detect if a request to a page was made via ajax -   

// determine if the request was an ajax request
define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

the IS_AJAX_REQUEST constant would be used in conditional statement(s) to control what gets output back to the browser.

 

for the account listing, you would need to build the html markup in a php variable, so that you can either output it in the html document, for non-ajax requests, or output it in response to the ajax request. you would move the while(){} loop from where it is in the html document, to right after where you execute the sql query. You would define a variable to hold the markup, then build the markup in that variable -

// run the query here...
$list_content = '';
while($col = mysqli_fetch_assoc($GetListCategory))
{
    $list_content .= "
    <li class='table_row'>
        <div class='table_section'>{$col['AccountName']}</div>
        <div class='table_section_last'> </div>
    </li>
    ";
}

right before you start to output the html document, which i am assuming is at your "//Include Global page" code, you would output the response to the ajax request, then halt execution so that the html document is not output -   

// output content due to an ajax request
if(IS_AJAX_REQUEST){
    
    // use a switch/case as a controller
    $get_action = isset($_GET['action']) ? $_GET['action'] : '';
    
    switch($get_action)
    {
    case 'list_content':
        echo $list_content;
    break;

    // add code for other actions here...
    
    }
    exit; // stop execution so that nothing else is output to the browser
}
in the markup on your page, where the account list content is now, you would replace it with a container with an id so that the javascript can set the content from the ajax request. you would also echo the $list_content here for non-ajax requests -   
        <ul class="responsive_table">
            <li class="table_row">
                <div class="table_section"><?php echo $Account; ?></div>
                <div class="table_section"> </div>
            </li>
            <div id='list_content'>
            <?php echo $list_content; ?>
            </div>
        </ul>

in the javascript, you would write a function, that when called, uses an ajax request to get the account list and display it in the correct place on the page - 

<script>
function get_list()
{
    $.ajax({
    url: "accounts.php?action=list_content",
    cache: false
    })
    .done(function(html) {
        $( "#list_content" ).html(html);
    });
}
</script>

you would then simply call this function inside your existing ajax post form success: handler.

Link to comment
Share on other sites

Thanks @mac_gyver, it worked like a charm when I ran it as described above.

 

However, when I tried to implement it in my project, it just did nothing. I am using Framework7 with it's Template7 engine and I have declared the execution in the pageInit of myApp.js file. I don't know what to do anymore as it seem like for any script to run, it must be already declared in the framework which I don't know where to do just that.

 

Any framework7 help pls.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.