I have the following function, how can I simplify it using jquery?
function updateCards(){
var form = document.getElementById("sets");
var chks = form.querySelectorAll('input[type="checkbox"]');
var checked = [];
for(var i = 0; i < chks.length; i++){
if(chks[i].checked){
checked.push(chks[i].value)
}
}
// test code
//alert("SELECTED SETS:"+checked);
if (checked == ""){
document.getElementById("all-cards").innerHTML = "";
return;
}
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("all-cards").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_cards.php?sets="+checked, true);
xmlhttp.send();
}
Try
function updateCards(){
var $form = $('#sets'), $chks = $form.find('input:checkbox'), checked ;
checked = $chks.map(function(){
return this.checked ? this.value : undefined;
}).get();
if (checked.length == 0){
$('#all-cards').html('');
return;
}
$.ajax({
url: 'update_cards.php',
type: 'GET',
data: {
sets: checked
},
dataType: 'html'
}).done(function(html){
$('#all-cards').html(html);
})
}
Same function in jQuery can be written like below.
function updateCards() {
var $form = $('#sets'),
$chks = $('input[type="checkbox"]:checked'),
$allCards = $('#all-cards');
var checked = $chks.map(function() {
return this.value
});
if(checked.length === 0) {
$allCards.html('');
return
}
// Ajax
$.ajax({
url : "update_cards.php?sets="+checked,
type: 'get',
dataType: 'html'
}).done(function(data) {
$allCards.html(data);
}).fail(function(xhr, status, error) {
console.log(error);
});
}
Related
I want to call a jQuery function that acts upon a form in AJAX response.
How do I do it???
jQuery Function
$(document).ready(function (e) {
$("#load_timetable").on('submit',function(e) {
e.preventDefault();
$.ajax({
url: "load_timetable.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#time_table").html(data);
},
error: function() {}
});
});
});
Another AJAX Function
$(document).on("click", ".open-viewFacultyDialog", function () {
var uid = $(this).data('id');
$('#update').click(function() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
**//I would like to call JQUERY here**
document.getElementById("update_action_response").innerHTML = "";
var ajaxDisplay = document.getElementById('update_action_response');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var dept_slot = document.getElementById('dept_slot').value;
var subject = document.getElementById('subject').value;
var faculty1 = document.getElementById('faculty1').value;
var faculty2 = document.getElementById('faculty2').value;
var faculty3 = document.getElementById('faculty3').value;
var queryString="?id="+uid+"&dept_slot="+dept_slot+"&subject="+subject+"&faculty1="+faculty1+"&faculty2="+faculty2+"&faculty3="+faculty3;
ajaxRequest.open("GET", "update_timetable.php"+queryString, true);
ajaxRequest.send(null);
});
});
In simple I would like to reload the contents after updation without page reload by submitting the same parameters that are used to load the contents before update.
Use Promise method which is already defined in jquery.you can use it if data transfer successfully. such that if promise returns true then perform this task.else other task.
If I add caption to image it's working, if I add one more caption without refreshing the page the 1st value is posting to the second one...
$(document).ready(function () {
$(".cap_btn").click(function(){
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
$.ajax({
type: "POST",
url: "addcap.php",
data: { id: li.data("imageId"), "cap": cap},
success: function(data){
alert("Caption Added");
},
error: function(){
alert("failure");
}
});
});
});
php code:
if(isset($_POST['id'])){
$ids = $_POST['id'];
$cap = $_POST['cap'];
try
{
$query = "UPDATE image SET caption='$cap' WHERE id='$ids'";
$sql=$con->prepare($query);
$sql->execute();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
You can do it like this
$(document).ready(function () {
$(".cap_btn").click(
function()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
alert("Caption Added");
}
else
{
alert("failure");
}
};
xmlhttp.open("POST", "addcap.php", true);
var formdata = new FormData();
var li = $(this).closest("li");
var cap = $('input[name="cap"]').val();
formdata.append("id",li.data("imageId"));
formdata.append("cap",li.data("cap"));
xmlhttp.send(formdata);
});
});
Hope it helps :)
I want to pass multiple values from from different <div> tags to another php page(onewaytrip_passenger_data.php) using ajax code on button onclick() function. This is my ajax function:
<script language="javascript">
function continoue(){
var a=$("#temp").text();
var b=$("#sno").text();
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("temp").innerHTML=xmlhttp.responseText;
document.getElementById("sno").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","onewaytrip_passenger_data.php?count="+a+"seatno="+b,true);
xmlhttp.send();
}
</script>
#temp and sno are my two different <div> id's these are my <div> tags
<div id="temp" style="visibility:hidden;"></div>
<div id="sno" style="visibility:hidden;"></div>
This is my button:
<input name="continoue" type="image" src="images/contioue.png" onclick="continoue()"/>
Use jQuery ajax function:
function continoue(){
var a=$("#temp").text();
var b=$("#sno").text();
$.ajax({
type: "GET",
url: "onewaytrip_passenger_data.php",
data : {count:a, seatno:b},
success: function (response) {
if (response == "success" ) {
//do something
} else {
//something
}
},
error: function () {
//console.log('Error --------');
}
});
}
in PHP file after your success code is done,
just write
<?php echo "success"; ?>
for failure,
<?php echo "failure"; ?>
Try this :
<script type="text/javascript">
var a = $("#temp").html();
var b = $("#sno").html();
$.get("onewaytrip_passenger_data.php", {count: a, seatno: b})
.done(function (data) {
alert("Data Loaded: " + data);
}).fail(function () {
alert("error");
});
</script>
Please read this also for your reference.
I want to pass value from AJAX file to PHP using below script, but it fail. What is the correct way to do this? Thanks
Sample code as below:
function createNewWindow()
{
var newWindowModel = new DHTMLSuite.windowModel({windowsTheme:true,id:'newWindow1',title:'Response Time to Invitation',xPos:130,yPos:400,minWidth:100,minHeight:100 } );
newWindowModel.addTab({ id:'myTab1',htmlElementId:'myTab1',tabTitle:'TAB',textContent:'Send data', contentUrl:'load.php?loadNo:loadNo' } );
var newWindowWidget = new DHTMLSuite.windowWidget(newWindowModel);
newWindowWidget.init();
}
Passing values? you mean parameters? if yes:
Create an AJAX obj first: var http = new XMLHttpRequest();
The GET method:
var url = "load.php";
var params = "loadNo=loadNo¶m=value";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
The POST method:
var url = "laod.php";
var params = "loadNo=loadNo¶m=value";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Simple and easy way to do a AJAX Request using Jquery
var request = $.ajax({
url: "script.php", // script path goes here
type: "GET",
data: {id : param}, // Parameters go here
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg ); // On success
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus ); // On failure
});
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x=xmlhttp.responseText;
alert(x);
}
}
}
xmlhttp.open("GET","load.php?loadNo="+loadNo+"¶m="+value,true);
xmlhttp.send();
I would like to trigger the php post to database script without refreshing the page (like it happens with regular php self).
Check out jQuery $.post( ) functionality. Here is a link to get you started: http://api.jquery.com/jQuery.post/
I'm using this to do what you want:
function parseJsonIfPossible(code){
try {
return $.parseJSON(code);
} catch (e) {
return code;
}
}
function cmd(command,p1,p2,p3,p4,p5,p6){
return parseJsonIfPossible($.ajax({
url: core_url,
global: false,
type: "POST",
data: {command : command,p1:p1,p2:p2,p3:p3,p4:p4,p5:p5,p6:p6},
dataType: "html",
async:false,
success: function(msg){
//alert(msg);
}
}).responseText);
}
PHP:
function cmd()
{
$command = &$_POST['command'];
$p1 = &$_POST['p1'];$p2 = &$_POST['p2'];$p3 = &$_POST['p3'];$p4 = &$_POST['p4'];$p5 = &$_POST['p5'];$p6 = &$_POST['p6'];
if($command)echo($command($p1,$p2,$p3,$p4,$p5,$p6));
}
function test($i)
{
//simple
return mysql_query("UPDATE ... SET b='$i'");
//array
return json_encode(array(
mysql_query("UPDATE ... SET b='$i'"),
"fklsdnflsdnl",
));
}
usage (script):
$('#btn').click(function(){
var i = 99;
var result = cmd("test",i);
//simple
alert(result);
//array
console.log([result[0],result[1]]);
});
Here is a basic sample code for Ajax request.
function postData()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Do anything you want with the response
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","page_to_be_post.php",true);
xmlhttp.send();
}
However you can use some frameworks to do this easily with less code.
Ex:
http://www.prototypejs.org/learn/introduction-to-ajax
http://api.jquery.com/jQuery.post/
There are many more frameworks available.
Cheers!
The below code might help you in php post using jquery ajax.
Suppose you have a form with id=form and a button to submit the form whose id=submit1.
Now to send the form data to another page using jquery ajax you need the following code just before the end of body.Dont forget to attach the jquery script before writing the below code.
$(document).ready(function(){
$('submit1').click(function(event){
//first stop the default submit action
event.preventDefault();
//now we will do some ajax
$.ajax({
url:'test.php',//the target page where to submit the data
type:'post',
cache:false,
data:$('#form').serialize(),//data to be sent from the form
dataType:'json',//expected data type from the server
error:function(xhr){
alert("the error is"+xhr.status);
}
})
//success function in terms of .done
.done(function(data){
alert("your data successfully submitted");
});
});
});