2015-01-27 21 views
1

Надеюсь, кто-то может помочь.Изменение html-содержимого с помощью PHP/AJAX

Я хочу заменить элемент input в документе с использованием AJAX и PHP, в зависимости от значения переменной в php.

HTML выглядит следующим образом:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="utf-8"> 
<title>Twitter Bootstrap Modal Contact Form Demo</title> 
<meta name="description" content="Creating Modal Window with Twitter   
Bootstrap"> 

<link href="assets/bootstrap.min.css" rel="stylesheet"> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js">  
</script> 
<script src="assets/bootstrap.min.js"></script> 
<script> 
$(document).ready(function() { 
$("#submit").click(function(event) { 
event.preventDefault(); 
$.ajax ({ 
type: "POST", 
url: "process.php", 
data: $('form.contact').serialize(), 
success: function(msg) { 
$("#log").html(msg); 
}, 
error: function() { 
alert("failure"); 
} 
}); 
}); 
}); 
</script> 

<style type="text/css"> 
body { margin: 50px; background: url(assets/bglight.png); } 
.well { background: #fff; text-align: center; } 
.modal { text-align: left; } 
</style> 

</head> 
<body> 

<div class="container"> 
<div class="well well-large"> 
<h2>Twitter Bootstrap Modal Contact Form Demo</h2> 
<div id="form-content" class="modal hide fade in" style="display: none;"> 
<div class="modal-header"> 
<a class="close" data-dismiss="modal">×</a> 
<h3>Send me a message</h3> 
</div> 
<div class="modal-body"> 
<form class="contact" name="contact"> 
<label class="label" for="name">Your Name</label><br> 
<input type="text" name="name" class="input-xlarge" id="contactName"><br> 
<label class="label" for="email">Your E-mail</label><br> 
<input type="email" name="email" class="input-xlarge"><br> 
<label class="label" for="message">Enter a Message</label><br> 
<textarea name="contactMessage" class="input-xlarge" id="contactMessage">  
</textarea> 
</form> 
</div> 
<div class="modal-body" id="log"> </div> 
<div class="modal-footer"> 
<input class='btn btn-success' type='submit' value='Send!' id='submit'> 
</div> 
</div> 
<div id="contactButton"><p><a data-toggle="modal" href="#form-content"  
class="btn btn-primary btn-large">Modal powers, activate!</a></p></div> 
</div> 
</div> 

</body> 
</html> 

process.php (немного УДАЛЕНО) выглядит следующим образом:

<?php 
$myemail = '[email protected]'; 

$error = ""; 

//Validates the fields and set the 'name', 'email' and message fields to   
required. I have removed this part of the code. It works and the error 
displays in the html 

//Displays the success message 
if (isset($_POST['name']) AND ($error != "")) { 
echo "<span class=\"alert alert-danger\" ><strong>The following errors exist 
in your form: </strong></span><br><br>"; 
echo $error; 
} else { 
$name = strip_tags($_POST['name']); 
$email = strip_tags($_POST['email']); 
$message = strip_tags($_POST['contactMessage']); 
echo "<span class=\"alert alert-success\" >Your message has been received.  
Thanks! Here is what you submitted:</span><br><br>"; 
echo "<strong>Name:</strong> ".$name."<br>";  
echo "<strong>Email:</strong> ".$email."<br>"; 
echo "<strong>Message:</strong> ".$message."<br>"; 

//Sends e-mailto = $myemail, also deleted because this works. 

?> 

То, что я хочу, чтобы случиться, когда пользователь нажимает кнопку отправки и переменную php ($ error = ''), затем <input class='btn btn-success' type='submit' value='Send!' id='submit'> необходимо заменить на <input class='btn btn-success' type='button' value='Close' id='close' data-dismiss='modal'>

Любая помощь будет оценена по достоинству.

+0

Вы читали [это] (http://mattgemmell.com/what-have-you -пытался/) ? И, пожалуйста, просто разместите соответствующий код. – Naruto

+0

У меня есть. Я новичок в этом. Я поправится. Я просто ищу способ ссылки на атрибут php в jQuery, чтобы включить его в оператор if. – Agfokkit

ответ

1

Меняйте JQuery AJAX код:

$(document).ready(function() { 
    $("#submit").click(function(event) { 
     event.preventDefault(); 
     $.ajax ({ 
      type: "POST", 
      url: "process.php", 
      data: $('form.contact').serialize(), 
      dataType: 'json', 
      success: function(msg) { 
       $("#log").html(msg.html); 
       if(!msg.error){ 
        $(".modal-footer .btn-success").attr('type','button').val('close'); 
        $(".modal-footer .btn-success").attr('id','close'); 
        $(".modal-footer .btn-success").attr('data-dismiss','modal'); 
       }  
      }, 
      error: function() { 
       alert("failure"); 
      } 
     }); 
    }); 
}); 

И PHP код:

<?php 

$myemail = '[email protected]'; 

$error = ""; 
$html = ''; 
$err = false; 
//Validates the fields and set the 'name', 'email' and message fields to   
required. I have removed this part of the code. It works and the error 
displays in the html 

//Displays the success message 
if (isset($_POST['name']) AND ($error != "")) { 
    $html .= "<span class=\"alert alert-danger\" ><strong>The following errors exist in your form: </strong></span><br><br>"; 
    $html .= $error; 
    $err = true; 
} else { 
    $name = strip_tags($_POST['name']); 
    $email = strip_tags($_POST['email']); 
    $message = strip_tags($_POST['contactMessage']); 
    $html .= "<span class=\"alert alert-success\" >Your message has been received. Thanks! Here is what you submitted:</span><br><br>"; 
    $html .= "<strong>Name:</strong> ".$name."<br>";  
    $html .= "<strong>Email:</strong> ".$email."<br>"; 
    $html .= "<strong>Message:</strong> ".$message."<br>"; 

    //Sends e-mailto = $myemail, also deleted because this works. 
} 

echo json_encode(array('error'=>$err,'html'=>$html); 

?> 
+0

Это изменит атрибуты, я знаю, но он сделает это, когда пользователь нажимает на отправку, независимо от того, есть ли ошибки или нет. Я хочу, чтобы код проверял, является ли ошибка $ пустой и когда она пуста, тогда она должна изменить атрибуты. Я не знаю, как ссылаться на переменную php в коде jQuery. Вот где я застрял. – Agfokkit

+0

Проверьте обновленный ответ. –

+0

Спасибо. Это работает. – Agfokkit

Смежные вопросы