3

I'm trying to send a JavaScript variable to a php script using ajax. This is my first time using ajax and I don't know where I went wrong. Here's my code

function selectcat(v) {
        $.ajax({

        type: "GET",
        url: "myurl.php",
        dataType: "script",
        data: { "selected_category" :  v}
    }).done(function() { 
    window.location.href = "http://mywebsite.com";

    });
        }

All help is appreciated

Here's the HTML

<ul class="cat">
<li class="opt" onclick="selectcat('option1')">option1</li>
<li class="opt" onclick="selectcat('option2')">Option 2</li>

</ul>

This is the ajax php file

<?php
session_start();
$ctgry = $_GET['selected_category'];
$_SESSION['select_cat'] = $ctgry;
?>
user4559334
  • 383
  • 4
  • 13
  • 2
    There is not much point in using ajax if you redirect to another page in the `success` function. Can you provide a bit more information / context about what you are doing and how the function is called? And what is going wrong exactly? – jeroen Mar 04 '15 at 16:09
  • @jeroen There's a bunch of options on the page that all have the on click calling the ajax function. I need the value the user clicked on but I don't want to use radio buttons. I then need to put the value in a php variable which is what the ajax script does – user4559334 Mar 04 '15 at 16:13
  • when you say _"trying to send a JavaScript variable"_ I am assuming you have a defined variable somewhere in your code which you want to pass. If thats the case, then you would just need to put it in an object and send it via the `data` method.. However I do not see this variable you speak of, instead I see "v".. assuming this is your variable, is this not being sent to your php? – CodeGodie Mar 04 '15 at 16:14
  • @CodeGodie The v is the parameter received from the element clicked – user4559334 Mar 04 '15 at 16:15
  • please provide the html for your options so that we can see if youre doing it correctly. Also provide how your PHP is handling the information sent. – CodeGodie Mar 04 '15 at 16:15
  • I think what you would like is a solid example where a php file uses jQuery AJAX and then receives some data back and does something with it. Sound about right? – darlirium Mar 04 '15 at 16:15
  • @CodeGodie I've added the html – user4559334 Mar 04 '15 at 16:19
  • remove `dataType: "script"` – CodeGodie Mar 04 '15 at 16:22
  • @CodeGodie I've tried it without that too – user4559334 Mar 04 '15 at 16:24
  • then your problem is probably in PHP. provide your PHP code as well – CodeGodie Mar 04 '15 at 16:26
  • @CodeGodie I've added the php code – user4559334 Mar 04 '15 at 16:28
  • @user4559334 I posted an answer check it out. – CodeGodie Mar 04 '15 at 16:35
  • OK. I'll get back to you guys after I test it out. I'm in class right now – user4559334 Mar 04 '15 at 16:35
  • 1
    haha.. figures.. we will be waiting. – CodeGodie Mar 04 '15 at 16:37

4 Answers4

1

You need to remove dataType: "script" since you are just sending data. Do it like this:

 function selectcat(v) {
        $.ajax({
            type: "GET",
            url: "myurl.php",
            data: {"selected_category": v}
        }).done(function(result) {
            console.log(result);
            //window.location.href = "http://mywebsite.com";
        });
 }
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
  • geez, it looks like someone posted a template answer there.. regardless.. so you tried removing that line, and the problem still persists... your PHP looks good.. there must be some other problem. Where is your `myurl.php` file sitting? is it in the same directory as your script? – CodeGodie Mar 04 '15 at 16:32
0

Hi this is what I do to call an ajax request You can post data or load a file using following code:

 $("#button click or any other event").click(function(){
try
  {
    $.post("my php page address",
      {
         'Status':'6',
         'var one':$("#myid or .class").val().trim(),
         'var 2':'var 2'
     }, function(data){
           data=data.trim();
      //   alert(data);
// this  data is data that the server sends back in case of ajax request you 
//can send any type of data whether json or or json array or any other type 
//of data

         });
    }
    catch(ex)
    {
        alert(ex);
    }
  });

I hope this help!

cssGEEK
  • 994
  • 2
  • 15
  • 38
behzad babaei
  • 1,111
  • 10
  • 11
0

dataType: "script" has no sense here, I think you want json or leave it empty.

Your PHP script should work if you try to get the variable with $_GET['selected_category']

I suggest you this modification to help yourself for debugging

$.ajax({
    type: "GET",
    url: "myurl.php",
    data: { "selected_category" :  v},
    success: function(data){
      console.log(data);
      // you can also do redirection here (or in complete below)
    },
    complete: function(data){
      // when request is done, independent of success or error.
    },
    error: function(data){
      // display things to the user
      console.error(data);
    }
})
Juergen
  • 12,378
  • 7
  • 39
  • 55
Asenar
  • 6,732
  • 3
  • 36
  • 49
0

AJAX is easier than it sounds. You just need to see a few good examples.

Try these:

A simple example

More complicated example

Populate dropdown 2 based on selection in dropdown 1


The above examples demonstrate a few things:

(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )

Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:

$('#divID').click({
    $.ajax({
        type: 'post',
         url: 'contact.php', 
    dataType: 'json',
        data: 'email=' + form.email.value
    }).done(function(data) {
        if ( typeof(data) == 'object' ) {
            if ( data.status == 'valid') {
                form.submit();
            } else if(data.status !=='valid' {     
                alert('The e-mail address entered is wrong.');
                return false;
            } else {
                alert('Failed to connect to the server.');
                return false;
            }
        }
    });
});

(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.

(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.

(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:

<?php

//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']

$out =  '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';

echo $out;

Please try a couple of the above examples for yourself and you will see how it works.

It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.


So, you just need to echo back some data. It is the job of the PHP file to:

(1) receive the data from the AJAX routine,

(2) Use that data in a look up of some kind (usually in a database),

(3) Construct a response, and

(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.


Your example could be changed to look something like:

HTML:

<ul class="cat">
    <li class="opt" value="TheFirstOption">option1</li>
    <li class="opt" value="The Second Option">Option 2</li>
</ul>

javascript/jQuery:

$('.opt').click(function(){
    var v = $(this).val();
    $.ajax({
        type: "POST",
        url: "myurl.php",
        dataType: "html",
        data: { "selected_category" :  v}
    }).done(function(data) { 
        $('#div_to_insert_the_response').html(data);
    });
});

PHP:

<?php
    $val = $_POST['selected_category'];
    echo 'You selected: ' . $val;
Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • 2
    You have a missmatch between JS and PHP, on JS you are using GET and in PHP you are trying to read **selected_category** from POST – alphamikevictor Mar 04 '15 at 17:14
  • @AgustinMuñoz Oi yoi ! You're so right -- thanks for catching that glaring error. That must be what CodieGodie was telling me also...! - Fixed *One hates to spend all that time on an answer only to blow it completely with a dumb mistake* – cssyphus Mar 04 '15 at 17:15
  • yes sir.. they both either need to be GET or both POST – CodeGodie Mar 04 '15 at 17:21