ajax records in a selector - javascript

I do not really know what terminology to call this but its just that am stock with my school assignment. This is what I want to do
I have a code like this
<information user_number_random="12345678" />. Now I want to periodically/dynamically change the user_number_random values by making ajax call to php file eg. user.php each time page is being refreshed.
<?php
$u_id=rand(0000,9999);
echo $u_id;
?>
below is my ajax call
<script>
$(document).ready(function(){
$('#btn').click(function(){
$.ajax({
type : 'POST',
url : 'user.php',
data : $(this).serialize(),
success : function(data)
{
$("#record").html(data);
}
});
});
});
</script>
below is how am trying to get the ajax record values passed to user_number_random but its not showing anything. can someone help me fix that. Thanks
<information user_number_random="record" />

Possible solution:
<information user_number_random="record" />
<script>
$(function() {
$('#btn').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'user.php',
success: function(data) {
$("information").attr("user_number_random", data);
}
});
});
});
</script>
Explanation:
$('#btn').click(function(e) {
e.preventDefault();
The click event passes in an "event object" to to event handler function, which we receive as e. Normally, when you click on a link, the browser loads the URL provided in the href attribute of the link, or simply reloads the page if an empty href is given. To prevent this default action, we call e.preventDefault on the event object. This way the page won't reload when you click the link.
I removed the data: $(this).serialize() property from your AJAX call, because you don't seem to need it in this case. You can use the data property to pass custom data attributes in the POST request to user.php. Any parameters you pass in there are made available in the $_POST array in your PHP code. Since you don't access $_POST in this case, you don't need to pass in any data attributes. And besides, $(this).serialize() only works when submitting forms, which is not the case here.
$("information").attr("user_number_random", data);
Since the HTML element you want to change is an <information> element, the jQuery selector needed to be adjusted accordingly. To set an attribute on an element, you can use element.attr("attribute_name", "new_value").

Related

store data via ajax and then go to that URL

I am here for an help.
<a class="text" href="http://test.com?id=87"><img src="/2016/02/BlueFantasyThumb.jpg"><h3>Milky</h3></a>
When i click on this, i need to do certain ajax things that i know how to do. But the problem is i need to perform ajax and then go to that href link.
Upon clicking i know using e.preventDefault(); we can prevent default behaviour. But the case is i dont want to prevent this. I want to occur that event just after that ajax implementation without any obstruction in viewers point.
Any kind of inputs will help me a lot. Thanks.
You can store the href value in a variable, call e.preventDefault() to prevent redirection and run your ajax code. In your ajax success callback, you can pick the href value and redirect to that link using javascript.
$("a.text").on("click", function(e){
e.preventDefault();
var href = $(this).attr("href");
$.ajax({
url: URL,
data: DATA,
success: function(response){
// your code here to be executed before redirecting
window.location.href = href;
}//success
});//ajax
});//click
1) Set html like
<a class="text" data-href="http://test.com?id=87"><img src="/2016/02/BlueFantasyThumb.jpg"><h3>Milky</h3></a>
2) add click event
$(".text").click(function() { // set ajax
var url = $(this).attr("data-href");
$.ajax({
url: "ajax.php", // set required url here
}).done(function() {
alert("sucess")
window.location.href = url; // redirect page in ajax success
});
});
change href to javascript:;
and then your ancor tag onclick event call a function of ajax call
inside ajax success function
write
window.location.href = "http://test.com?id=87";

How to disable redirecting when clicking on a button?

I use Codeigniter and Bootstrap.
I have a button:
<a class="btn btn-success" id="btnid" href="http://site/controllerName/parameter">Text</a>
If I click to the button its call a controller with one parameter then the controller redirects to a site.
My question is that is there a way to call the controller with a parameter but skipping the redirection?
Try following
$(document).ready(function(){ // Add your event handlers inside ready block
$("#btnid").click(function(event) { // button event handler
event.preventDefault(); // prevent page from redirecting
$.ajax($(this).attr('href')).done(function(response) { // send call
// after call
});
});
});
For details refer to - ajax, preventDefault
Edit
As there are more than one link. You can use class selector. Currently, you have 2 classes btn and btn-success. You can use either of them, however, I will suggest you to add one more class let us say btn-api
Then update your click selector to
$(".btn-api").click(function(event)) {
event.preventDefault(); // prevent page from redirecting
$.ajax($(this).attr('href')).done(function(response) { // send call
// after call
});
});
https://api.jquery.com/event.preventdefault/ - prevents the default action
$( "a" ).click(function( event ) {
event.preventDefault();
}
You need to use event.preventDefault();
This is an exemple with just JavaScript (Not jQuery)
<script>
function stopDefAction(evt) {
evt.preventDefault();
}
document.getElementById('btnid').addEventListener(
'click', stopDefAction, false
);
</script>
You can find documentation and complete exemple here:
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
You can call a javascript method which does a ajax call. Then there will be no redirect.
<a class="btn btn-success" id="btnid" onclick="javascript:theFunction();" href="#">Text</a>
<script type="text/javascript">
function theFunction () {
event.preventDefault();
// add your ajax call to the controller here e.g
$.ajax({
url: "http://site/controllerName/parameter"
}).done(function() {
// action when the controller call returns
});
}
</script>
By default a click on the a link to a controller will either render this controller's view or redirect to another view. To stop redirecting, you must call the controller via AJAX. To fully understand this, lets see what happens when you don't use ajax:
You click on the link which triggers the request.
The request is routed to your controller.
The controller processes the request. The ending line of the controller is something like $this->load->view('your-view');
This loads the raw HTML after any view logic has been processed and sends it back to your browser via normal HTTP. This issues a redirect (or a refresh if it was the same page).
What AJAX does, is that it takes the data received in step 4, and makes it available in a variable via javascript. To see this, we can write a code snippet:
HTML
<a onclick="getAjaxData()" class="btn btn-success" id="btnid">Text</a>
The easiest way to use ajax is via JQuery.
Javascript
function getAjaxData(e) {
// Make sure that the link default action doesnt occur.
e.preventDefault();
$.ajax({
type: 'GET', // depending on the controller method.
url: 'http://site/controllerName/parameter',
success: function(data)
{
// The variable data contains the data returned from the controller.
},
error: function()
{
alert('Something went wrong!');
}
});
Now if you leave things as they are, the vairable data will contain the raw HTML returned from the controller. Usually if you will use AJAX, it is better to either return HTML snippets which you can append directly to your current HTML DOM, or return data in JSON format, which you can then process via javascript.

How to use checkbox value asdata parameter in ajax

I need to reload a page when clicking in a submit button. What the new page should show depends on the checkboxes selected previously to the reloading.
My problem is that, when I click "submit", $("button").click(function()... takes the correct values but $(document).ready(function ()... takes always the values true (which are selected as default).
How can I save those values before the reloading so that I can use them on $(document).ready(function ()...? Can I send them as data parameter
$(document).ready(function() {
var selectedCheckboxes = new Array();
$.ajax({
url: 'getNewForm.php?accion=value1',
data: 'selectedCheckboxes',
dataType: 'json',
error: function() {
alert("ERROR");
},
success: function(res) {
//Do something
}
}
});
$("button").click(function() {
var selectedCheckboxes = new Array();
selectedCheckboxes[0] = document.getElementById("checkbox1").checked;
selectedCheckboxes[1] = document.getElementById("checkbox1").checked;
});
});
Note: I did var selectedCheckboxes twice trying to get different results, donĀ“t know where I should do it.
You have several problems here:
You have a syntax error in your code sample. Make sure the code you post to StackOverflow compiles and runs without syntax errors (assuming you're not asking why a particular code snippet is generating syntax errors :) ).
The data attribute of your AJAX request is incorrectly specified as the literal string 'selectedCheckboxes', which means that your browser will send the literal string "selectedCheckboxes" as the payload to your server.
In addition, as you correctly surmise, you don't correctly handle the initialization of selectedCheckboxes. Variables initialized with var in JS are scoped to the containing function, which means the selectedCheckboxes declaration inside your click() handler are never going to be seen outside it.
Also, you're getting the value of "checkbox1" twice; you probably want to get something named "checkbox2" or similar. Related: If you are just serializing the only inputs in the form, use jquery's serialize() method so you have less code.
If you're really reloading the entire page anyway, don't use an AJAX request to do it? Using AJAX for form submissions is common when you do not want to reload the entire page (see below), but for your stated use case, it adds complexity you don't need. Just have a simple form with checkboxes and a submit button, and let the browser do it's default action.
Here's an example of using AJAX to submit a form behind the scenes, without reloading the entire page:
http://jsfiddle.net/Palpatim/rLeGv/
Given the HTML:
<form id="checkboxForm">
<input type="checkbox" name="check" value="check1" checked="checked" id="ch1"/>
<label for="ch1">check1</label>
<br/>
<input type="checkbox" name="check" value="check2" checked="checked" id="ch2" />
<label for="ch2">check2</label>
<br/>
<button>Click me</button>
</form>
This JS will submit a form when the button is clicked:
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url: 'getNewForm.php?accion=value1',
data: $('#checkboxForm').serialize(),
dataType: 'json',
error: function() {
alert("ERROR");
},
success: function(res) {
alert("SUCCESS");
}
});
});
});
As far as loading a new page with the previous selections, you will have to maintain the state somehow. Your options include passing the state back from the server, storing the selections in the browser's local storage, or a cookie. I'd suggest passing the state back from the server, but your use case is a bit unclear.

unable to give exact target to refresh my div in jquery function

sir,
when i click on "Rename Day button" jquery popop calender appears in my screen , once if i click on its submit button it is forwarding to my page but is not refreshing the exact div.. I do not where should i specify div target for refreshing my particular div..
jquery function for submit
function okButton(){
$("#formId").submit();
};
$(this).submit({
target: '#userTemplateRightmiddlediv'});
};
struts.xml
<!-- Rename Selected Day for User Template -->
<action name="EditDayAction"class="com.ebhasin.fitnessbliss.dao.DynamicTableOperationsService" method="RenameDayUserTemp">
<result name="success">/jsps/userTemplateRightmiddlediv.jsp</result>
</action>
Extend the functionality of your 'okButton' to stop the default form submission behavior, then create an ajax function to connect to your XML file, return the data, and then insert the data into the .html() of the element with an ID of userTemplateRightmiddlediv
function okButton(){
$("#formId").submit(function(e){ //'e' for 'event'
e.preventDefault();//stop the page from refreshing
$.ajax({
url: 'Struts2 URL Here',
dataType: 'xml',
success: function(xml){
//function(xml) represents an object returned from our XML file, we can work with it however we want by using normalized jquery procedures
$("#userTemplateRightmiddlediv").html(xml);
}
});
});
}
Edit
Changed to reflect portability with Struts 2.
You're trying to fire two submits. $ is a function that returns an object. 'submit' is a method of that object. If the jquery object is holding a form, it's like pressing the submit button on that form so the page refreshes and all the remaining code doesn't matter. You're trying to submit twice but $(this).submit doesn't really make sense.
If I had to guess, maybe you want something more like this:
$('#formId').submit( function(e){
e.preventDefault(); // stops the page from reloading
//maybe ajax or something else to change this div you're talking about.
} )

How to submit a POST form in a new window with javascript?

That is ,I want to keep the original page while POST a form.
You could simply use the target attribute of the form:
<form method="post" target="_blank" action="...">
Note that even though this will work in all major browsers, it is deprecated and your page will not validate as per W3C standards.
There are two ways you can accomplish this. If the page can be reloaded, just post the form to the page you are currently on. If you want to submit the form with AJAX (no page reload), then a javascript library such as jQuery is recommended (to save you the trouble of manually constructing an XHR request. Here is an example of ajax with jQuery:
window.onload = function(){
$('.image').click(function(){
var image_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "/ajaxpage.php",
data: {
id:image_id
}
success: function(data){
alert(data);
},
failure: function(){
alert('failed');
}
});
});
}
From the page you call here, you can echo a response that will be handled by the ajax success handler.

Categories

Resources