Jquery ajax request echo html data - php

I'm making an ajax request to my PHP script which will echo out a certain # of tables ( different each time), that I want to include on my original page when a user clicks the submit_form button. My question is how can i get Jquery to display this table into the table_layout div?
HTML :
<div id="table_layout"> </div>
JQUERY
$( ".submit_form" ).click(function( e ) {
$.ajax({
type : 'GET',
url: 'draw_tables.php',
dataType : 'html',
data: dataString ,
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('error'); },
success : function(data) { //appendto.('#table_layout') }
});
return false;
})
PHP (draw_tables.php)
echo '<table>';
echo '<input type="text" name="ID">';
echo '<input type="text" name="CLASS">';
echo '</table>';

For example you could make an ajax request and fill the div with it
$.get("draw_tables.php", function(data) {
$("#table_layout").html(data);
});
This will fill your table_layout id with the data from the ajax request.

$('#table_layout').append(data);

Inside the success callback you should add:
$('#table_layout').append(data);

Related

How can I use localStorage in php with AJAX to update my database?

I need to use a localStorage value in a PHP file to update values in my database. I know that I need ajax to achieve this, I can't get it to work.
My localStorage item is named option and it exists (checked in browser and stored the value in a div)
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue: localStorage.getItem('option') },
success: function(data){
alert('success');
}
});
});
PHP Example:
$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';
I dont see any post data nor do I get a response.
Thank you!
Your page:
<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>
Your JS file:
document.getElementById('option').submit(); // This submits the form
var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue:storageValue },
success: function(data){
alert('success');
}
});
return false; // This stops the page from refreshing
});
Your PHP file to callback the data to AJAX and display the alert (activity.php):
...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page
mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
...

jQuery ajaxStart with php code

I am reading about Ajax Events from the jQuery docs.
My jQuery code with some HTML:
<p style="display:none">Loading...</p>
<div></div>
$(document).ready(function() {
$("p")
.ajaxStart(function(){
$(this).show();
})
.ajaxStop(function(){
$(this).hide();
});
$.ajax({
url : 'http://localhost/xampp/web_development/new_study_2014/my_files/test.php',
data : {id : 123},
type : "GET",
dataType : "html",
success: function(response) {
$("div").hide().html(response).fadeIn(1500);
},
error: function(xhr, status, errorThrown) {
console.log( xhr + status + errorThrown );
},
complete: function() {
console.log( );
}
});
});
The PHP:
<?php
sleep(1);
echo "<p> his name is jack</p>";
?>
I wanted the paragraph that says Loading... to display when the ajax request starts and hides when it is finished. As described in the jQuery docs. Yet it does none of the two and displays "his name is jack" from the php page. What am I doing wrong?
The target of the ajaxStart event is the document, not a particular element, so using $(this) in the handler won't work. Change it to select the specific element.
jQuery:
$(document).ajaxStart(function() {
$("#loading").show();
});
$(document).ajaxStop(function() {
$("#loading").hide();
});
HTML:
<p id="loading" style="display: none;">Loading...</p>

How to use chekbox with Jquery ajax

I am trying to use checkbox with Ajax. Without Ajax I have handle it.
Here is my Jquery code
$("#skillcat").click(function(e) {
var submit_val = new Array();
e.preventDefault();
var ids = $('check_subjects input:checked')
.map(function(){
return this.value;
}).get();
$.ajax( {
type : "POST",
dataType : "json",
url : "./wp-admin/admin-ajax.php",
data : {
action : 'each_category',
check_subjects : ids
},
success : function(data) {
alert(data);
$('#accordion').html(data);
}
});
});
Here is my php code where button and checkbox is generated in serverside
foreach($subjects as $key=> $data){
echo '<input type="checkbox" id="'. $data->id .'" value="'. $data->id .'" name="check_subjects[]"> '. $data->subject .'<br>';
}
Serverside I used to catch data from Post array
if(isset($_POST['check_subjects'])){
//var_dump(check_subjects);
$check_subjects = implode(',', $_POST['check_subjects']);
//echo '$check_subjects '. $check_subjects;
}
however when I run above codes, I notice that some data is sent to the server(via chrom developer tool). But I get null in alert box. I guess response is null becase data is not sent to server properly. I am not sure about the javasript code I use to passe the request to Ajax.
Can anybody explain where I have done the mistake?
It is expecting JSON and you are returning html. So make the dataType HTML or json encode your return...
Try this:
$("#skillcat").on('click', function (e) {
e.preventDefault();
var ids = [];
var $el = $('[name*=check_subjects]:checked'); //Get all checked Checkboxes
$el.each(function () {
ids.push($(this).attr('id')); //get the Id from each checkbox
});
$.ajax({
type: "POST",
dataType: "html",
url : "./wp-admin/admin-ajax.php",
data: {
action: 'each_category',
check_subjects: ids
},
success: function (data) {
alert(data);
$('#accordion').html(data);
}
});
});

getting variable from javascript to php

I have a simple combo box whose value I can get in JavaScript.
I am doing that so I don't need to refresh the page.
Also I want to use the selected value to do some conditional branching after combo box so how do I get the value of combo box from JavaScript to my variable $change.
echo '<select id="combo_1">';
echo '<option value="2">Submative</option>';
echo '<option value="1">formative</option>';
echo '</select>';
Below is my JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
});
});
</script>
Here I want to do $change = $(this).val(), but obviously I cant do it like this.
Any suggestions?
i want to do it on the same page without refreshing or without submitting
my url kinda look like this
http://localhost/lms/grade/report/userdef/index.php
and i want it to be on click action
cuz depending on the choice of combobox 2 very different procedures will be called
You're gonna want to use AJAX and submit the form, then you can access the returned data without ever refreshing the page.
Basically:
HTML
<select name="combo" id="combo_1">
<option value="2">Submative</option>
<option value="1">formative</option>
</select>
JavaScript
$('#combo_1').change(function() {
$.post('calcScript.php', $(this).serialize(), function(data) {
alert(data);
});
});
in PHP, you can access your combo data via $_POST['combo'].
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
var combo_1 = $(this).val();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {'combo_1':combo_1},
success: function(data){
alert(data)
}
});
});
});
</script>
ajax.php
if( isset($_GET['combo_1]) ) {
echo $change = $_GET['combo_1'];
}
JS:
$.ajax({
type: "POST",
url: './filename.php',
beforeSend: function(){
//If you want to do something
},
data: 'data='$('#combo_1').val(), //Optional '&data2='+value+'&datan='+value,
success: function(msg){
alert(msg);
}
});
PHP:
$val = $_POST['data'];
return 'received successfully';
This will alert 'received successfully'

javascript wont read .post php submit input (in php)

Javascript part...
It stops at the $("#deletar").click...
$(document).ready(function() {
$("#deletar").click(function() { // it fails here !!
var sendu = $("#ids").val();
$.ajax({
type : "POST",
url : "deletar.php",
data : "ids=" + sendu,
success : function(msg, string, jqXHR) {
$("#result").html(msg);
}
});
});
});
This is the php file... is a echo to other ajax post, and retrieves a list of a mysql db
.$row2['amigos']."
</td>
<td><inp ``ut type='submit' name='deletar' id='deletar' value='deletar'
OnClick='return confirm(\"Tem certeza que quer deletar esta linha?\");'>
<input type='hidden' name='ids' id='ids' value='".$row2['id']."'>
</td>
</tr>
";
enter code here
Your ajax is being called from a submit button click. You haven't done anything to prevent the default behaviour of the submit button, therefore after your ajax call, the browser will submit the form using a traditional request.
In your click event, you can return false to prevent the form submitting:
$("#deletar").click(function(){ //it fails here !!
var sendu = $("#ids").val();
$.ajax({
type:"POST",
url:"deletar.php",
data: "ids="+sendu,
success: function(msg,string,jqXHR){
$("#result").html(msg);
}
});
return false; // <--- stop the form submitting
});
You can also use e.preventDefault to achieve the same result.
I think you need to stop the form submitting after the submit button has been clicked:
$(document).ready(function () {
$("#deletar").click(function (event) {//it fails here !!
event.preventDefault(); // one of these
event.stopPropagation(); // lines should do the trick
var sendu = $("#ids").val();
$.ajax({
type : "POST",
url : "deletar.php",
data : "ids=" + sendu,
success : function (msg, string, jqXHR) {
$("#result").html(msg);
}
});
});
});

Categories