Jump to content
Sign in to follow this  
nash

вычисления через AJAX

Recommended Posts

Есть форма, куда вводятся числовые значения.

<div class="box">
  <div class="box-heading"><?php echo $heading_title; ?></div>
  <div class="box-content">
		 
    <h2 id="zag">Заголовок</h2>
    <form action="#" method="post" enctype="multipart/form-data">
	<div class="content">
	
    <b><?php echo $text_p1; ?></b><br />
    <input type="text" name="p1" value="<?php echo $p1; ?>" />
    <br />
    <?php if ($error_p1) { ?>
    <span class="error"><?php echo $error_p1; ?></span>
    <?php } ?>
    <br />
	
    <b><?php echo $text_p2; ?></b><br />
    <input type="text" name="p2" value="<?php echo $p2; ?>" />
    <br />
    <?php if ($error_p2) { ?>
    <span class="error"><?php echo $error_p2; ?></span>
    <?php } ?>
    <br />
    
	 <b><?php echo $text_lyudi; ?></b><br />
    <input type="text" name="lyudi" value="<?php echo $lyudi; ?>" />
    <br />
    <?php if ($error_lyudi) { ?>
    <span class="error"><?php echo $error_lyudi; ?></span>
    <?php } ?>
    <br />
	
                  	
	 <b><?php echo $text_p3; ?></b><br />
    <input type="text" name="p3" value="<?php echo $p3; ?>" />
    <br />
    <?php if ($error_p3) { ?>
    <span class="error"><?php echo $error_p3; ?></span>
    <?php } ?>
    <br />
	
	<div class="buttons">
      <div class="right"><input type="submit" id="btn1" value="<?php echo $text_btn; ?>" class="button" /></div>
    </div>
	
	<?php if ($resultat) { ?>
	<div id="notific"><?php echo $resultat; ?></div>
	<?php } ?>
	
    </div>
    </form>
  
  </div>
</div>

в контроллере:

if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			
			$this->data['p1'] = $this->request->post['p1'];
			$this->data['p2'] = $this->request->post['p2'];
			$this->data['p3'] = $this->request->post['p3'];
			$this->data['resultat'] = $this->data['p1'] + $this->data['p2'] + $this->data['p3'];
			}

пытался написать скрипт AJAX, но ничего не получилось, сложение трех переменных не происходит.

Без скрипта переменные складываются, но страница перезагружается(( Скиньте примерчик, пожалуйста. Хочу разобраться

Share this post


Link to post
Share on other sites

Конечно перегружается, идет же обычный Post.

Для отдельного ajax вызова нужно создать отдельный публичный метод в контроллере и дергать именно его.

public function index() {
....
}

public function insert() {
...
}

public function myAjaxMethod() {
... А вот тут уже обработка

        $this->response->addHeader('Content-Type: application/json; charset=utf-8');
        $this->response->setOutput(json_encode($json));
}
 

 

 

Ну и в виде дергать

$.ajax(....url : index.php?route=xxx/controller/myAjaxMethod

Share this post


Link to post
Share on other sites
<script type="text/javascript"><!--
	$('#btn1').bind('click', function() {
	$.ajax({
		type: 'POST',
		url: 'index.php?route=module/calc/rasschet',
		dataType: 'json',
		data: 'ploschad=' + encodeURIComponent($('input[name=\'ploschad\']').val()) + '&lyudi=' + encodeURIComponent($('input[name=\'lyudi\']').val()),
		beforeSend: function() {
		//	$('.success, .warning').remove();
			$('#btn1').attr('disabled', true);
			$('#zag').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" /> подожди!</div>');
		},
		complete: function() {
			$('#btn1').attr('disabled', false);
			$('.attention').remove();
			notific.innerHTML = $('input[name=\'lyudi\']').val() + $('input[name=\'ploschad\']').val();
		},
		success: function(data) {
			
			if (data.success) {
				$('.buttons').after('<div id="notific">' + data.success + '</div>');
			}
		}
	});
});
</script>
		public function rasschet() {
			$this->language->load('module/calc');
			
			if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			
			$this->data['ploschad'] = $this->request->post['ploschad'];
			$this->data['lyudi'] = $this->request->post['lyudi'];
			$this->data['PC'] = $this->request->post['PC'];
			$this->data['moschnost_priborov'] = $this->request->post['moschnost_priborov'];		

			$this->data['resultat'] = $this->data['ploschad'] + $this->data['lyudi'];
			}
			
			$this->response->addHeader('Content-Type: application/json; charset=utf-8');
			$this->response->setOutput(json_encode($json));
			
		}

вот вроде написал, но не выводит результат(

Share this post


Link to post
Share on other sites
if ($this->request->server['REQUEST_METHOD'] == 'POST') {

Нахрена? :)

 

Считаем  $this->data

а отдаем

$json

 

Уж определитесь.

public function rasschet() {
			$this->language->load('module/calc');
			$json = array();
			
			$json['ploschad'] = $this->request->post['ploschad'];
			$json['lyudi'] = $this->request->post['lyudi'];
			$json['PC'] = $this->request->post['PC'];
			$json['moschnost_priborov'] = $this->request->post['moschnost_priborov'];		

			$json['resultat'] = $json['ploschad'] + $json['lyudi'];
			
			$this->response->addHeader('Content-Type: application/json; charset=utf-8');
			$this->response->setOutput(json_encode($json));
			
		}

Share this post


Link to post
Share on other sites

сделал так... но результат вычислений не отображается... появляется и затем пропадает только вот эта штука, а результата вычислений нет:

$('#zag').after('<div class="attention"><img src="catalog/view/theme/default/image/loading.gif" alt="" /> подожди!</div>');

Share this post


Link to post
Share on other sites

а зачем все это, если сумму чисел из двух полей можно посчитать простейшим javascript

var resultat = ($('input[name="ploschad"]').val() + $('input[name="lyudi"]').val());
?

Share this post


Link to post
Share on other sites

для практики, разбираюсь с AJAX

Share this post


Link to post
Share on other sites

...
$json['resultat']
...
...
if (data.success) {
				$('.buttons').after('<div id="notific">' + data.success + '</div>');
...
$json -> data

success != resultat

Share this post


Link to post
Share on other sites

поподробнее можно, пожалуйста?

Share this post


Link to post
Share on other sites

нельзя васю называть петей :-)

data.success
>>

data.resultat

Share this post


Link to post
Share on other sites

Join the conversation

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

Guest
You are posting as a guest. If you have an account, please sign in.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

×

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.