Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In my form action there's a url: www.url.com/?quantity=$quantity

And in the form there's a select box where customers choose the quantity.

<form method="post" name="jform" action="www.url.com/?quantity=$quantity">
<select class="font_12" id="quantity" name="quantity">
    <option value="10">10 PCs</option>
    <option value="25">25 PCs</option>
    <option value="50">50 PCs</option>
    <option value="99">99 PCs</option>
</select>

I am trying to get the value in the select box using ajax, and then display into the action form url. I did a alert and it works, I am getting the value of the select box. But I don't know how to put this vaue into the PHP varaible $quantity?

Here's my Ajax code:

$('#quantity').on('change', function() {
var val = $(this).val();
if(val != '') {
    $.get('index.php', {'quantity' : val}, function(resp) {
        alert(val);
    });
}
});

Actually I want it to change the php variable right away when the quantity in the select box change before submitting the form.

Any help?

share|improve this question
1  
When do you want PHP to be able to access the quantity variable? –  Explosion Pills Jan 30 at 18:45
1  
what have you tried? –  Jeff Jan 30 at 18:46
 
I try $_GET, but when the page load I am getting a undefined error –  Ya Fa Su Jan 30 at 18:49
add comment

1 Answer

up vote 2 down vote accepted

Use $_GET

If your URL is ?quantity=### then just use $_GET['quantity'] in your PHP code.

To change the action attribute on the form when you change the quantity you can just put the following inside your onchange event:

$('form[name="jform"]').attr('action','http://url.com/?quantity=' + val);
share|improve this answer
 
and be careful to properly control your users' input –  niahoo Jan 30 at 18:47
 
not working, the url is in the form action. I want it to change the quantity of the form action url when a value in the select value is changed. –  Ya Fa Su Jan 30 at 19:01
 
Well then since you're using jQuery you can just say $('form[name="jform"]').attr('action','http://url.com/?quantity=' + val); –  Marcus Recck Jan 30 at 19:03
 
Oh thank you so much, but how about if I am using a php function in the action like:<form method="post" name="jform" action="<?php echo url($quantity) ?>"> –  Ya Fa Su Jan 30 at 19:13
 
Then you can use action="http://url.com/?quantity=<?php echo (int)$_GET['quantity']; ?>" –  Marcus Recck Jan 30 at 19:14
show 5 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.