Krijn van der Burg Krijn van der Burg - 6 months ago 16
Ajax Question

Jquery var to php but do not return

I have a HTML form that I want to send to PHP but also some javascript variables. These JS vars are not in the form. How can I get both to th PHP class?

Below is the code I have so far.

$("#login_FORM").submit(function() {
event.preventDefault();
$.post('../class/login.Class.php',{
//.. serialized form data
screen:screen.width
//...ser
//...
},function(data){
alert(data);
window.location.href = "";
});
});


The
screen
variable ends up perfectly in
login.Class.php
but when it gets to the end of the php file... it returns to above javascript function.

Even when using a
header
into php it returns to the javascript function. It simply reads that page as well and returns everything thats returned in there.
echo $_POST['hash'];
header('Location: ../index.php'); die();

Only if I use a
window.location.href = "";
in javascript I can redirect to a correct page after processing the javascript data in the
login.class.php
file (redirecting to correct page isn't the only reason I'm asking the question...fyi)

How can I send variables from jquery / javascript to PHP and continue from there? aka not return to the (success) function the variables were send from.

Answer

If I understand you correctly you want to pass the serialized form data plus some jquery variables if that's the case you could use serializeArray()

var data = $('#myForm').serializeArray();
data.push({var1: 'value', var2: 'value'});

$.post("myPage.php", data);

EDIT

I think i got what you are trying to do, if you submit the form using jquery ajax it will always return to the success function because any redirection in php will only redirect the ajax request and not the current "screen".In that case try the following (not a 100% but here it goes): add hidden fields to your form say:

<form action="/class/login.Class.php">
    <!-- form content n stuff -->
    <input id="var1" name="var1" type="hidden" value="someValue" />
    <button id="letsGo" type="submit">Submit</button>
</form>

$('#letsGo').click(function(e) {
    e.preventDefault();
    var form = $(this).closest('form');
    $('#var1').val('dasValue');
    // replace as many hidden inputs as you need
    form.submit();
});

Hope this helps.

Comments