Ryan
Ryan

Reputation: 14659

Problem with ajax, jquery

function sendValues() {
var str = $("#myForm").serialize();
var response = $('input[name=brand[]]:checked').val();
$.ajax({
    url: "/trying.php?avoidcache=' + myTimestamp();",
    data: {str}
    cache: false
});
}

I want to be able to send the data onclick (checking the checkbox) and I need the checkbox to stay checked when it is sent to the server. Right now it does not stay checked, but the value of the checked is shot out.

Below is an example of what I am trying to accomplish..

http://www.abt.com/category/45/Bookshelf-Speakers.html

I can get the script to filter results, but there is 2 problems with it.

Upvotes: -1

Views: 175

Answers (1)

no.good.at.coding
no.good.at.coding

Reputation: 20371

It doesn't look like you're submitting the form via ajax, you're causing the form submission using JavaScript. I imagine that when you say the checkbox does not stay checked it's because your page is being submitted and reloaded without state.

I'd say your options are

  1. Modify your PHP script to check the checkboxes if their state is checked in the database.
  2. Actually submit via jQuery .ajax() making use of .serialize().

Update

  1. You didn't show how you're triggering the function in the updated code but if it's on the submit event of a form, you should make sure that you return false; to cancel the form submission. Other than that you have some errors in your code - {str} is invalid syntax and is also missing a trailing comma.

  2. Here is a fiddle that submit a form on checking/unchecking checkboxes in the form using ajax. Note that message returned is always an error message since this form is running on jsFiddle.net but in your case, it will be the response of your PHP script that you will handle appropriately.

Upvotes: 1

Related Questions