I have a html form to make an order in a shop by clicking a button called Order.(button_id="order")
At the button click event i have performed a ajax request to a page(itemOrder_php2.php) which sends some data in the form to that mentioned page. It's working correctly. But the problem is ajax request is not functioning when two or more users order at the same time. Please help me to work with multiple ajax requests. Thank you! here is my code.
$(document).ready(function(){
$("#order").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "itemOrder_php2.php",
data: { selectedItem: $("#selectedItem").val(), sizeUnit: $("#sizeUnit").val(), quantity: $("#quantity").val(), value: x, lSize : $("#lSize").val(), lPrice : $("#lPrice").val() },
success:function(result){
$("#orderResult").html(result);
}});
});
});
Handle the click event with document on...
$(document).ready(function(){
$(document).on('click','#order',function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "itemOrder_php2.php",
data: { selectedItem: $("#selectedItem").val(), sizeUnit: $("#sizeUnit").val(), quantity: $("#quantity").val(), value: x, lSize : $("#lSize").val(), lPrice : $("#lPrice").val() },
success:function(result){
$("#orderResult").html(result);
}});
});
});
Related
Hi there is it possible to redirect to another page using ajax? I have this piece of code that I have been working on to try this.
<script type="text/javascript">
$(document.body).on('click', '#btnPrintPrev', function() {
$.ajax({
url: '/pdfdatacal',
data: {
dummydata: "This is a dummy data"
},
});
});
</script>
Now it should be able to carry data to another page and redirect there. Problem is it doesn't.
This is what I am using in my route
Route::get('/pdfdatacal', 'GenerateReportController#pdfdatacal');
Then in the controller
public function pdfdatacal(Request $request) {
return $request->data['dummydata'];
}
My expected result should be a blank page containing the value of dummydata but it doesn't do that in my code. How do I accomplish this?
first your ajax must be something like
$.ajax({
url: '/pdfdatacal',
method: 'post',
data: { dummydata: "This is a dummy data" },
dataType: "JSON",
success: function(response){
console.log(response); // just to check if the data is being passed
// do something you want if ever .
}
});
then in your routes
Route::post('/pdfdatacal', 'GenerateReportController#pdfdatacal');
in your controller
public function pdfdatacal(Request $request) {
return response()->json($request->dummydata);
}
hope it helps ..
Use
window.location.href = "http://yourwebsite.com/pdfdatacal";
In your success call
The idea is that you send data to your controller, it sends back a response, then you redirect from javascript to where you want.
$.ajax({
url: '/pdfdatacal',
type : 'GET',
data : {
dummydata: "This is a dummy data"
},
success : function(data) {
window.location.href = "http://yourwebsite.com/pdfdatacal";
}
});
But if your controller does nothing with the data you send, then you don't need to use ajax at all, simple redirect using javascript.
you could use window.location.assign('your URL here!'); in the success.
success : function(data) {
window.location.assign('your URL here!');
}
I am a beginner in JavaScript means and programming, and I encountered a problem for a personal project. I made an anime fight website getting some information from MySQL Database each anime has ten videos and photos, through a random button it randomly takes one link for a video and photo. The problem is that it only work only one time if I random again nothing happens. I know that in order to make that work I have to rewrite the code again after the success of the first random for getting a second random but this will create an infinite loop. Can somebody help me solve this issue.
This is the code used:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
$('#random').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
})
}
});
})
});
</script>
I understand that $.ajax request overwrites initial .imgResponsive element, am I right? Along with overwritten .imgResponsive you permanently lose click event attached to this element.
In that case you need to attach event to element container, eg.
$(document).on('click', '.imgResponsive', function() {....
...
}
instead of
$('.imgResponsive').click(function(){ ....
You have to register EventListener in order to proceed.
Try this:
<script>
var showImage = function(e){
e.preventDefault();
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: function(response){
$('#hiddenPage').html(response);
}
});
};
$(document).ready(function () {
$('document').on('click', '.imgResponsive', showImage);
$('document').on('click','#random', showImage);
});
</script>
The way your code is written, you're handling only a single AJAX response (aside from the first one) with no way to handle more AJAX requests triggered by clicking the #random button. You need to write functions for handling button clicks and the AJAX responses instead of using anonymous functions; that way it's modular enough that you can listen for and handle more button clicks in the future.
Something like this:
<script>
$(document).ready(function () {
$('.imgResponsive').click(function(){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
$('#random').click(handleButtonClick);
});
function handleButtonClick(e){
$('#hiddenPage').hide();
$('#hiddenPage').html('<center><img src="img/loading.gif"></center>');
$('#hiddenPage').show();
$.ajax({
type: 'POST',
url: 'php/handler.php',
data: {
anime: $(this).prev().val()
},
success: handleResponse
});
}
function handleResponse(response){
$('#hiddenPage').html(response);
}
});
</script>
Edit: Another thing that might be happening is that your #random element is being overwritten every time you do $('#hiddenPage').html(response);. In that case you would need to attach a new event handler to the new #random element every time you handle an AJAX response:
function handleResponse(response){
$('#hiddenPage').html(response);
$('#random').click(handleButtonClick);
}
Hellp people...lets take a simple ajax code...
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert(msg.html());
});
I am Trying to fetch msg.html() after waiting for 5 seconds? so the process is as follows ...
send data to some.php
wait for 5 seconds
then return the html page data.
how can we achieve this?
Use setTimeout, The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. The function is only executed once.
And if you want to fetch the html of msg then first of all make sure msg is a valid HTML string and before fetching the .html() please convert it to a jQuery object by $(msg).
$.ajax({
method: "POST",
url: "some.php",
data: {
name: "John",
location: "Boston"
}
})
.done(function(msg) {
setTimeout(function() {
alert($(msg).html());
}, 5 * 1000);
});
$.ajax({
type : 'POST',
url : 'some.php',
data :{ name : 'John', location : 'Boston'},
beforeSend : function(){
//you can do whatever you want here (loading gif etc.) until some.php responds
},
complete : fuction(){
//Here is for after responding
},
success : function(data){
//data is the response of some.php, you can use the data to fill some elements in DOM etc.
}
});
setTimeout(function(){
//the codes you write here fires after 5 secs
},5000);
and you can pass this where do you want.
I'm having a problem with ajax, as it sends only once my request, i have a cssmap plugin, and that plugin have the option onSecondClick which gives me the ability to do something when i click on it twice, my post request sends some data, to the sessions.php, in session.php i delete session, and then i put one again.
The js lines :
'onSecondClick' : function(e){
var regionName = e.children("A").eq(0).text(),
regionHref = e.children("A").eq(0).attr("href"),
regionClass = e.attr("class").split(" ")[0];
if(regionClass == "eu13" || regionClass == "eu16" || regionClass == "eu47"){
//open model success
$.ajax({
type: "POST",
url: 'session',
data: { country : regionClass },
cache: false,
success: function(data){
$( "#success" ).click();
}
});
//$( "#success" ).click();
}else{
//open model error
$( "#error" ).click();
}
},
PS - the url is right, thats the url of the file, and the session is set, but only once and doesn't upadate.
session.php:
if(Input::get('country')){
$countries = array(
'eu13' => 'france',
'eu16' => 'germany',
'eu47' => 'united kingdom',
//end of playable countries, the rest is bots!
'eu5' => 'belgium',
'eu27' => 'luxembourg',
'eu33' => 'netherlands',
'eu44' => 'switzerland',
'eu20' => 'ireland'
);
if(Session::get('selected');){
Session::delete('selected');
}
Session::put('selected',$countries[Input::get('country')]);
}
On the success, i click a button, which open a "model" from Bootstrap.
everything is ok, but the session always return the previous clicked country, and no matter how much i click other country, it doesn't change.
i've got no idea what the problem is, tried e.preventdefault(), cache: false, and some more options, nothing seems to fix it.
It's hard to tell where the problem lies from your description, but if it's about presentation (i.e. you can verify that session.php does it's job, but still the modal presents the wrong info), this is probably the reason.
Bootstrap modals are only, by default, filled with content once. After that it will use .toggle to show or hide.
If you want to update the information, you'll have to clear it first:
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
This will clear any content from modals with class modal when it hides/closes. You can also use an id selector of course, like #myModal.
edit:
Try this ajax. What does the alert return?
$.ajax({
type: "POST",
url: "session",
data: { "country": regionClass },
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
cache: false,
success: function(data){
alert(data);
$("#success").click();
}
});
And add something like this to the end of your session.php:
echo $countries[Input::get('country')];
(php is not really my thing. I think that's correct though)
i am getting a form with user parameters when i make an AJAX call to a page which later on is submiited to a url so that i can create a session for the same user in advance and when
that person goes to that site he sees his name there.
i created one div tag with id "abc_session", assign that form (whose id is fm1) to it,and submitted the form.
now as per the requirement session is created but page automatically gets redirected to that site url to which form is submitted.i just don't wan't that to happen.
can anyone please suggest something..or some workaround
the form that AJAX returns looks something like this:
<html>
<body onload="document.fm1.submit();return false">
<form name = "fm1" method="post" action = "https://abcd.com/abc ">
<input type=hidden name ="name" value="xyz">
<input type=hidden name ="login_parameters" value="CDF5D71C5BDB942EE2FB6C285B8DEBFE4C5675137B615CD2276571813AAC872AC8942E26B71026414BED1FEA09427D0B20A50FE2F70032D2E5B382598EC3C71D73EAB4ECBF7273A73BEB98ACEA4A0B775E7772BDC7C6746C355">
</form></body>
</html>
and the script goes like this
$(document).ready(function() {
function callwebsite()
{
$.ajax({
url: "/NASApp/benemain/website",
data: {},
type:"POST",
dataType: 'text',
cache: false,
success: function (data) {
alert("Call made to website.. ");
console.log(data);
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit();
},
error : function(response){
console.log('ERROR');
},
statusCode : {
500 : function() {
console.log('500 error');
window.location.reload(true);
},
401 : function() {
console.log('401 error');
window.location.reload(true);
},
404 : function(){
console.log('400 error');
}
}
});
}
callwebsite();
tried extracting the data and maiking another ajax call as suggested by quentin but getting this error "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource.This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
url: lcAction,
data: {partner_id:lcPartner,login_parameters:lcLP },
type:"POST",
headers:{'Access-Control-Allow-Origin': '*'},
dataType: 'text',
//crossDomain: true,
//cache: false,
success: function(data)
{
alert("success");
},
error:function(response)
{
//alert("error");
console.log(response);
}
});
You are submitting the form:
document.getElementById("abc_session").innerHTML=data;
document.fm1.submit(); // Here
Don't do that.
Extract the data from it and make another Ajax request.
You should use e.preventDefault() as soon as you submit the form.